Programs & Examples On #Automation

Automation is the process of having a computer do a repetitive task or a task that requires great precision or multiple steps, without requiring human intervention.

Matlab: Running an m-file from command-line

Here are the steps:

  1. Start the command line.
  2. Enter the folder containing the .m file with cd C:\M1\M2\M3
  3. Run the following: C:\E1\E2\E3\matlab.exe -r mfile

Windows systems will use your current folder as the location for MATLAB to search for .m files, and the -r option tries to start the given .m file as soon as startup occurs.

Clicking submit button of an HTML form by a Javascript code

You can do :

document.forms["loginForm"].submit()

But this won't call the onclick action of your button, so you will need to call it by hand.

Be aware that you must use the name of your form and not the id to access it.

How can I pass an argument to a PowerShell script?

# ENTRY POINT MAIN()
Param(
    [Parameter(Mandatory=$True)]
    [String] $site,
    [Parameter(Mandatory=$True)]
    [String] $application,
    [Parameter(Mandatory=$True)]
    [String] $dir,
    [Parameter(Mandatory=$True)]
    [String] $applicationPool
)

# Create Web IIS Application
function ValidateWebSite ([String] $webSiteName)
{
    $iisWebSite = Get-Website -Name $webSiteName
    if($Null -eq $iisWebSite)
    {
        Write-Error -Message "Error: Web Site Name: $($webSiteName) not exists."  -Category ObjectNotFound
    }
    else
    {
        return 1
    }
}

# Get full path from IIS WebSite
function GetWebSiteDir ([String] $webSiteName)
{
    $iisWebSite = Get-Website -Name $webSiteName
    if($Null -eq $iisWebSite)
    {
        Write-Error -Message "Error: Web Site Name: $($webSiteName) not exists."  -Category ObjectNotFound
    }
    else
    {
        return $iisWebSite.PhysicalPath
    }
}

# Create Directory
function CreateDirectory([string]$fullPath)
{
    $existEvaluation = Test-Path $fullPath -PathType Any
    if($existEvaluation -eq $false)
    {
        new-item $fullPath -itemtype directory
    }
    return 1
}

function CreateApplicationWeb
{
    Param(
        [String] $WebSite,
        [String] $WebSitePath,
        [String] $application,
        [String] $applicationPath,
        [String] $applicationPool
        )
    $fullDir = "$($WebSitePath)\$($applicationPath)"
    CreateDirectory($fullDir)
    New-WebApplication -Site $WebSite -Name $application -PhysicalPath $fullDir -ApplicationPool $applicationPool -Force
}

$fullWebSiteDir = GetWebSiteDir($Site)f($null -ne $fullWebSiteDir)
{
    CreateApplicationWeb -WebSite $Site -WebSitePath $fullWebSiteDir -application $application  -applicationPath $dir -applicationPool $applicationPool
}

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

Another way-too-complicated workaround, with the benefit of not having to re-install the application as the previous workaround required. This requires that you have access to the msi (or a setup.exe with the msi embedded).

If you have Visual Studio 2012 (or possibly other editions) and install the free "InstallShield LE", then you can create a new setup project using InstallShield.

One of the configuration options in the "Organize your Setup" step is called "Upgrade Paths". Open the properties for Upgrade Paths, and in the left pane right click "Upgrade Paths" and select "New Upgrade Path" ... now browse to the msi (or setup.exe containing the msi) and click "open". The upgrade code will be populated for you in the settings page in the right pane which you should now see.

Excel VBA Automation Error: The object invoked has disconnected from its clients

I have had this problem on multiple projects converting Excel 2000 to 2010. Here is what I found which seems to be working. I made two changes, but not sure which caused the success:

1) I changed how I closed and saved the file (from close & save = true to save as the same file name and close the file:

...
    Dim oFile           As Object       ' File being processed
...
[Where the error happens - where aArray(i) is just the name of an Excel.xlsb file]
   Set oFile = GetObject(aArray(i))
...
'oFile.Close SaveChanges:=True    - OLD CODE WHICH ERROR'D
'New Code
oFile.SaveAs Filename:=oFile.Name
oFile.Close SaveChanges:=False

2) I went back and looked for all of the .range in the code and made sure it was the full construct..

Application.Workbooks("workbook name").Worksheets("worksheet name").Range("G19").Value

or (not 100% sure if this is correct syntax, but this is the 'effort' i made)

ActiveSheet.Range("A1").Select

Have bash script answer interactive prompts

A simple

echo "Y Y N N Y N Y Y N" | ./your_script

This allow you to pass any sequence of "Y" or "N" to your script.

Automatic confirmation of deletion in powershell

Try using the -Force parameter on Remove-Item.

OS X Bash, 'watch' command

Use the Nix package manager!

Install Nix, and then do nix-env -iA nixpkgs.watch and it should be available for use after the completing the install instructions (including sourcing . "$HOME/.nix-profile/etc/profile.d/nix.sh" in your shell).

How to use Selenium with Python?

You just need to get selenium package imported, that you can do from command prompt using the command

pip install selenium

When you have to use it in any IDE just import this package, no other documentation required to be imported

For Eg :

import selenium 
print(selenium.__filepath__)

This is just a general command you may use in starting to check the filepath of selenium

Is it possible to modify a registry entry via a .bat/.cmd script?

Yes, you can script using the reg command. Example:

reg add HKCU\Software\SomeProduct
reg add HKCU\Software\SomeProduct /v Version /t REG_SZ /d v2.4.6

This would create key HKEY_CURRENT_USER\Software\SomeProduct, and add a String value "v2.4.6" named "Version" to that key.

reg /? has the details.

Automating running command on Linux from Windows using PuTTY

In case you are using Key based authentication, using saved Putty session seems to work great, for example to run a shell script on a remote server(In my case an ec2).Saved configuration will take care of authentication.

C:\Users> plink saved_putty_session_name path_to_shell_file/filename.sh

Please remember if you save your session with name like(user@hostname), this command would not work as it will be treated as part of the remote command.

Sending email from Command-line via outlook without having to click send

Send SMS/Text Messages from Command Line with VBScript!

If VBA meets the rules for VB Script then it can be called from command line by simply placing it into a text file - in this case there's no need to specifically open Outlook.

I had a need to send automated text messages to myself from the command line, so I used the code below, which is just a compressed version of @Geoff's answer above.

Most mobile phone carriers worldwide provide an email address "version" of your mobile phone number. For example in Canada with Rogers or Chatr Wireless, an email sent to <YourPhoneNumber> @pcs.rogers.com will be immediately delivered to your Rogers/Chatr phone as a text message.

* You may need to "authorize" the first message on your phone, and some carriers may charge an additional fee for theses message although as far as I know, all Canadian carriers provide this little-known service for free. Check your carrier's website for details.

There are further instructions and various compiled lists of worldwide carrier's Email-to-Text addresses available online such as this and this and this.


Code & Instructions

  1. Copy the code below and paste into a new file in your favorite text editor.
  2. Save the file with any name with a .VBS extension, such as TextMyself.vbs.

That's all!
Just double-click the file to send a test message, or else run it from a batch file using START.

Sub SendMessage()
    Const EmailToSMSAddy = "[email protected]"
    Dim objOutlookRecip
    With CreateObject("Outlook.Application").CreateItem(0)
        Set objOutlookRecip = .Recipients.Add(EmailToSMSAddy)
        objOutlookRecip.Type = 1
        .Subject = "The computer needs your attention!"
        .Body = "Go see why Windows Command Line is texting you!"
        .Save
        .Send
    End With
End Sub

Example Batch File Usage:

START x:\mypath\TextMyself.vbs

Of course there are endless possible ways this could be adapted and customized to suit various practical or creative needs.

Excel VBA Open workbook, perform actions, save as, close

I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..

Opening A Seperate File:

ChDir "[Path here]"                          'get into the right folder here
Workbooks.Open Filename:= "[Path here]"      'include the filename in this path

'copy data into current workbook or whatever you want here

ActiveWindow.Close                          'closes out the file

Opening A File With Specified Date If It Exists:

I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.

Some common error checking statements:

On Error Resume Next   'if error occurs continues on to the next line (ignores it)

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

Or (better option):

if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?

you would most likely want to use the GoTo ErrorHandler shown below to achieve this

On Error GoTo ErrorHandler:

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

ErrorHandler:
'Display error message or any code you want to run on error here

Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm


Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/

Hope this helps!


Example on how to ensure error code doesn't run EVERYtime:

if you debug through the code without the Exit Sub BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.

  Sub Macro

    On Error GoTo ErrorHandler:

    ChDir "[Path here]"                         
    Workbooks.Open Filename:= "[Path here]"      'try to open file here

    Exit Sub      'Code will exit BEFORE ErrorHandler if everything goes smoothly
                  'Otherwise, on error, ErrorHandler will be run

    ErrorHandler:
    'Display error message or any code you want to run on error here

  End Sub

Also, look at this other question in you need more reference to how this works: goto block not working VBA


Switch tabs using Selenium WebDriver with Java

String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL, Keys.RETURN);
    WebElement e = driver.findElement(By
            .xpath("html/body/header/div/div[1]/nav/a"));
e.sendKeys(selectLinkOpeninNewTab);//to open the link in a current page in to the browsers new tab

    e.sendKeys(Keys.CONTROL + "\t");//to move focus to next tab in same browser
    try {
        Thread.sleep(8000);
    } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    //to wait some time in that tab
    e.sendKeys(Keys.CONTROL + "\t");//to switch the focus to old tab again

Hope it helps to you..

Auto insert date and time in form input field?

If you are using HTML5 date

use this code

HTML

<input type="date" name="bday" id="start_date"/>

Java Script

document.getElementById('start_date').value = Date();

How can I login to a website with Python?

import cookielib
import urllib
import urllib2

url = 'http://www.someserver.com/auth/login'
values = {'email-email' : '[email protected]',
          'password-clear' : 'Combination',
          'password-password' : 'mypassword' }

data = urllib.urlencode(values)
cookies = cookielib.CookieJar()

opener = urllib2.build_opener(
    urllib2.HTTPRedirectHandler(),
    urllib2.HTTPHandler(debuglevel=0),
    urllib2.HTTPSHandler(debuglevel=0),
    urllib2.HTTPCookieProcessor(cookies))

response = opener.open(url, data)
the_page = response.read()
http_headers = response.info()
# The login cookies should be contained in the cookies variable

For more information visit: https://docs.python.org/2/library/urllib2.html

how to delete default values in text field using selenium?

.clear() can be used to clear the text

  (locator).clear();

using clear with the locator deletes all the value in that exact locator.

Check if element is clickable in Selenium Java

There are certain things you have to take care:

  • WebDriverWait inconjunction with ExpectedConditions as elementToBeClickable() returns the WebElement once it is located and clickable i.e. visible and enabled.
  • In this process, WebDriverWait will ignore instances of NotFoundException that are encountered by default in the until condition.
  • Once the duration of the wait expires on the desired element not being located and clickable, will throw a timeout exception.
  • The different approach to address this issue are:
    • To invoke click() as soon as the element is returned, you can use:

      new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]"))).click();
      
    • To simply validate if the element is located and clickable, wrap up the WebDriverWait in a try-catch{} block as follows:

      try {
             new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]")));
             System.out.println("Element is clickable");
           }
      catch(TimeoutException e) {
             System.out.println("Element isn't clickable");
          }
      
    • If WebDriverWait returns the located and clickable element but the element is still not clickable, you need to invoke executeScript() method as follows:

      WebElement element = new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]"))); 
      ((JavascriptExecutor)driver).executeScript("arguments[0].click();", element);
      

R command for setting working directory to source file location in Rstudio

The here package provides the here() function, which returns your project root directory based on some heuristics.

Not the perfect solution, since it doesn't find the location of the script, but it suffices for some purposes so I thought I'd put it here.

How to copy a file to a remote server in Python using SCP or SSH?

There are a couple of different ways to approach the problem:

  1. Wrap command-line programs
  2. use a Python library that provides SSH capabilities (eg - Paramiko or Twisted Conch)

Each approach has its own quirks. You will need to setup SSH keys to enable password-less logins if you are wrapping system commands like "ssh", "scp" or "rsync." You can embed a password in a script using Paramiko or some other library, but you might find the lack of documentation frustrating, especially if you are not familiar with the basics of the SSH connection (eg - key exchanges, agents, etc). It probably goes without saying that SSH keys are almost always a better idea than passwords for this sort of stuff.

NOTE: its hard to beat rsync if you plan on transferring files via SSH, especially if the alternative is plain old scp.

I've used Paramiko with an eye towards replacing system calls but found myself drawn back to the wrapped commands due to their ease of use and immediate familiarity. You might be different. I gave Conch the once-over some time ago but it didn't appeal to me.

If opting for the system-call path, Python offers an array of options such as os.system or the commands/subprocess modules. I'd go with the subprocess module if using version 2.4+.

Upload file to SFTP using PowerShell

Using PuTTY's pscp.exe (which I have in an $env:path directory):

pscp -sftp -pw passwd c:\filedump\* user@host:/Outbox/
mv c:\filedump\* c:\backup\*

How to Automatically Start a Download in PHP?

Send the following headers before outputting the file:

header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($File));
header("Connection: close");

@grom: Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :)

CRON job to run on the last day of the month

The last day of month can be 28-31 depending on what month it is (Feb, March etc). However in either of these cases, the next day is always 1st of next month. So we can use that to make sure we run some job always on the last day of a month using the code below:

0 8 28-31 * * [ "$(date +%d -d tomorrow)" = "01" ] && /your/script.sh

element not interactable exception in selenium web automation

Try setting an implicit wait of maybe 10 seconds.

gmail.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Or set an explicit wait. An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. In your case, it is the visibility of the password input field. (Thanks to ainlolcat's comment)

WebDriver gmail= new ChromeDriver();
gmail.get("https://www.gmail.co.in"); 
gmail.findElement(By.id("Email")).sendKeys("abcd");
gmail.findElement(By.id("next")).click();
WebDriverWait wait = new WebDriverWait(gmail, 10);
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("Passwd")));
gmail.findElement(By.id("Passwd")).sendKeys("xyz");

Explanation: The reason selenium can't find the element is because the id of the password input field is initially Passwd-hidden. After you click on the "Next" button, Google first verifies the email address entered and then shows the password input field (by changing the id from Passwd-hidden to Passwd). So, when the password field is still hidden (i.e. Google is still verifying the email id), your webdriver starts searching for the password input field with id Passwd which is still hidden. And hence, an exception is thrown.

automatically execute an Excel macro on a cell change

Handle the Worksheet_Change event or the Workbook_SheetChange event.

The event handlers take an argument "Target As Range", so you can check if the range that's changing includes the cell you're interested in.

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

You should replace WebDriver wb = new FirefoxDriver(); with driver = new FirefoxDriver(); in your @Before Annotation.

As you are accessing driver object with null or you can make wb reference variable as global variable.

Microsoft.Office.Core Reference Missing

You need to download and install the PIA (primary interop assemblies) for the version of Office you are using. Once installed you can then add a reference to your project and they will be available from the add reference dialog. Here are the links to download them...

Office 2010 PIA

Office 2007 PIA

Office 2003 PIA

How to use ADB to send touch events to device using sendevent command?

In order to do a particular action (for example to open the web browser), you need to first figure out where to tap. To do that, you can first run:

adb shell getevent -l

Once you press on the device, at the location that you want, you will see this output:

<...>
/dev/input/event3: EV_KEY       BTN_TOUCH            DOWN
/dev/input/event3: EV_ABS       ABS_MT_POSITION_X    000002f5
/dev/input/event3: EV_ABS       ABS_MT_POSITION_Y    0000069e

adb is telling you that a key was pressed (button down) at position 2f5, 69e in hex which is 757 and 1694 in decimal.

If you now want to generate the same event, you can use the input tap command at the same position:

adb shell input tap 757 1694

More info can be found at:

https://source.android.com/devices/input/touch-devices.html http://source.android.com/devices/input/getevent.html

How can I start InternetExplorerDriver using Selenium WebDriver

package Browser;

import org.openqa.selenium.WebDriver; import org.openqa.selenium.ie.InternetExplorerDriver;

public class Hello {

public static void main(String[] args) {


    // setting IEdriver property
    System.setProperty("webdriver.ie.driver",
            "paste the path of the IEDriverserver.exe");

    WebDriver driver = new InternetExplorerDriver();

    // launching the google home screen
    driver.get("https://www.google.com/?gws_rd=ssl");

}

} //Hope this will work

How to get the range of occupied cells in excel sheet

You should try the currentRegion property, if you know from where you are to find the range. This will give you the boundaries of your used range.

Typing the Enter/Return key using Python and Selenium

import org.openqa.selenium.Keys

WebElement.sendKeys(Keys.RETURN);

The import statement is for Java. For other languages, it is maybe different. For example, in Python it is from selenium.webdriver.common.keys import Keys

How to remove unused imports in Intellij IDEA on commit?

Choose the project/module you want to remove unused import from in Project view. Then from Code menu choose Optimize imports and confirm with Run. The imports will be cleaned in whole project/module.

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

Automated testing for REST Api

I collaborated with one of my coworkers to start the PyRestTest framework for this reason: https://github.com/svanoort/pyresttest

Although you can work with the tests in Python, the normal test format is in YAML.

Sample test suite for a basic REST app -- verifies that APIs respond correctly, checking HTTP status codes, though you can make it examine response bodies as well:

---
- config:
    - testset: "Tests using test app"

- test: # create entity
    - name: "Basic get"
    - url: "/api/person/"
- test: # create entity
    - name: "Get single person"
    - url: "/api/person/1/"
- test: # create entity
    - name: "Get single person"
    - url: "/api/person/1/"
    - method: 'DELETE'
- test: # create entity by PUT
    - name: "Create/update person"
    - url: "/api/person/1/"
    - method: "PUT"
    - body: '{"first_name": "Gaius","id": 1,"last_name": "Baltar","login": "gbaltar"}'
    - headers: {'Content-Type': 'application/json'}
- test: # create entity by POST
    - name: "Create person"
    - url: "/api/person/"
    - method: "POST"
    - body: '{"first_name": "Willim","last_name": "Adama","login": "theadmiral"}'
    - headers: {Content-Type: application/json}

JavaScript: Passing parameters to a callback function

//Suppose function not taking any parameter means just add the GetAlterConfirmation(function(result) {});
GetAlterConfirmation('test','messageText',function(result) {
                        alert(result);
    }); //Function into document load or any other click event.


function GetAlterConfirmation(titleText, messageText, _callback){
         bootbox.confirm({
                    title: titleText,
                    message: messageText,
                    buttons: {
                        cancel: {
                            label: '<i class="fa fa-times"></i> Cancel'
                        },
                        confirm: {
                            label: '<i class="fa fa-check"></i> Confirm'
                        }
                    },
                    callback: function (result) {
                        return _callback(result); 
                    }
                });

How to Uninstall RVM?

It’s easy; just do the following:

rvm implode

or

rm -rf ~/.rvm

And don’t forget to remove the script calls in the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

And maybe others depending on whatever shell you’re using.

Chrome desktop notification example

In modern browsers, there are two types of notifications:

  • Desktop notifications - simple to trigger, work as long as the page is open, and may disappear automatically after a few seconds
  • Service Worker notifications - a bit more complicated, but they can work in the background (even after the page is closed), are persistent, and support action buttons

The API call takes the same parameters (except for actions - not available on desktop notifications), which are well-documented on MDN and for service workers, on Google's Web Fundamentals site.


Below is a working example of desktop notifications for Chrome, Firefox, Opera and Safari. Note that for security reasons, starting with Chrome 62, permission for the Notification API may no longer be requested from a cross-origin iframe, so we can't demo this using StackOverflow's code snippets. You'll need to save this example in an HTML file on your site/application, and make sure to use localhost:// or HTTPS.

_x000D_
_x000D_
// request permission on page load_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
 if (!Notification) {_x000D_
  alert('Desktop notifications not available in your browser. Try Chromium.');_x000D_
  return;_x000D_
 }_x000D_
_x000D_
 if (Notification.permission !== 'granted')_x000D_
  Notification.requestPermission();_x000D_
});_x000D_
_x000D_
_x000D_
function notifyMe() {_x000D_
 if (Notification.permission !== 'granted')_x000D_
  Notification.requestPermission();_x000D_
 else {_x000D_
  var notification = new Notification('Notification title', {_x000D_
   icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',_x000D_
   body: 'Hey there! You\'ve been notified!',_x000D_
  });_x000D_
  notification.onclick = function() {_x000D_
   window.open('http://stackoverflow.com/a/13328397/1269037');_x000D_
  };_x000D_
 }_x000D_
}
_x000D_
 <button onclick="notifyMe()">Notify me!</button>
_x000D_
_x000D_
_x000D_

We're using the W3C Notifications API. Do not confuse this with the Chrome extensions notifications API, which is different. Chrome extension notifications obviously only work in Chrome extensions, and don't require any special permission from the user.

W3C notifications work in many browsers (see support on caniuse), and require user permission. As a best practice, don't ask for this permission right off the bat. Explain to the user first why they would want notifications and see other push notifications patterns.

Note that Chrome doesn't honor the notification icon on Linux, due to this bug.

Final words

Notification support has been in continuous flux, with various APIs being deprecated over the last years. If you're curious, check the previous edits of this answer to see what used to work in Chrome, and to learn the story of rich HTML notifications.

Now the latest standard is at https://notifications.spec.whatwg.org/.

As to why there are two different calls to the same effect, depending on whether you're in a service worker or not - see this ticket I filed while I worked at Google.

See also notify.js for a helper library.

Date format in dd/MM/yyyy hh:mm:ss

SELECT CONVERT(CHAR(10),GETDATE(),103) + ' ' + RIGHT(CONVERT(CHAR(26),GETDATE(),109),14)

Making an array of integers in iOS

You can use a plain old C array:

NSInteger myIntegers[40];

for (NSInteger i = 0; i < 40; i++)
    myIntegers[i] = i;

// to get one of them
NSLog (@"The 4th integer is: %d", myIntegers[3]);

Or, you can use an NSArray or NSMutableArray, but here you will need to wrap up each integer inside an NSNumber instance (because NSArray objects are designed to hold class instances).

NSMutableArray *myIntegers = [NSMutableArray array];

for (NSInteger i = 0; i < 40; i++)
    [myIntegers addObject:[NSNumber numberWithInteger:i]];

// to get one of them
NSLog (@"The 4th integer is: %@", [myIntegers objectAtIndex:3]);

// or
NSLog (@"The 4th integer is: %d", [[myIntegers objectAtIndex:3] integerValue]);

How to remove specific element from an array using python

Using filter() and lambda would provide a neat and terse method of removing unwanted values:

newEmails = list(filter(lambda x : x != '[email protected]', emails))

This does not modify emails. It creates the new list newEmails containing only elements for which the anonymous function returned True.

Reverse / invert a dictionary mapping

I would do it that way in python 2.

inv_map = {my_map[x] : x for x in my_map}

Nullable types: better way to check for null or zero in c#

You code sample will fail. If obj is null then the obj.ToString() will result in a null reference exception. I'd short cut the process and check for a null obj at the start of your helper function. As to your actual question, what's the type you're checking for null or zero? On String there's a great IsNullOrEmpty function, seems to me this would be a great use of extension methods to implement an IsNullOrZero method on the int? type.

Edit: Remember, the '?' is just compiler sugar for the INullable type, so you could probably take an INullable as the parm and then jsut compare it to null (parm == null) and if not null compare to zero.

What is the "right" way to iterate through an array in Ruby?

I think there is no one right way. There are a lot of different ways to iterate, and each has its own niche.

  • each is sufficient for many usages, since I don't often care about the indexes.
  • each_ with _index acts like Hash#each - you get the value and the index.
  • each_index - just the indexes. I don't use this one often. Equivalent to "length.times".
  • map is another way to iterate, useful when you want to transform one array into another.
  • select is the iterator to use when you want to choose a subset.
  • inject is useful for generating sums or products, or collecting a single result.

It may seem like a lot to remember, but don't worry, you can get by without knowing all of them. But as you start to learn and use the different methods, your code will become cleaner and clearer, and you'll be on your way to Ruby mastery.

How do I install boto?

If you're on a mac, by far the simplest way to install is to use easy_install

sudo easy_install boto3

python: creating list from string

More concise than others:

def parseString(string):
    try:
        return int(string)
    except ValueError:
        return string

b = [[parseString(s) for s in clause.split(', ')] for clause in a]

Alternatively if your format is fixed as <string>, <int>, <int>, you can be even more concise:

def parseClause(a,b,c):
    return [a, int(b), int(c)]

b = [parseClause(*clause) for clause in a]

Get file from project folder java

in javaFx 8

javafx.scene.image.Image img = new javafx.scene.image.Image("/myPic.jpg", true);

URL url = new URL(img.impl_getUrl());

How to use RecyclerView inside NestedScrollView?

Try to use this library - https://github.com/serso/android-linear-layout-manager.

LayoutManager of the library makes RecyclerView wraps its contents. In this case RecyclerView will be "as big as inner views", so it will not have a scrollbars and user will use scrolling abilities of NestedScrollView. Therefore, it will not be ambiguous like "scrollable inside scrollable".

How does DHT in torrents work?

With trackerless/DHT torrents, peer IP addresses are stored in the DHT using the BitTorrent infohash as the key. Since all a tracker does, basically, is respond to put/get requests, this functionality corresponds exactly to the interface that a DHT (distributed hash table) provides: it allows you to look up and store IP addresses in the DHT by infohash.

So a "get" request would look up a BT infohash and return a set of IP addresses. A "put" stores an IP address for a given infohash. This corresponds to the "announce" request you would otherwise make to the tracker to receive a dictionary of peer IP addresses.

In a DHT, peers are randomly assigned to store values belonging to a small fraction of the key space; the hashing ensures that keys are distributed randomly across participating peers. The DHT protocol (Kademlia for BitTorrent) ensures that put/get requests are routed efficiently to the peers responsible for maintaining a given key's IP address lists.

"FATAL: Module not found error" using modprobe

The best thing is to actually use the kernel makefile to install the module:

Here is are snippets to add to your Makefile

around the top add:

PWD=$(shell pwd)
VER=$(shell uname -r)
KERNEL_BUILD=/lib/modules/$(VER)/build
# Later if you want to package the module binary you can provide an INSTALL_ROOT
# INSTALL_ROOT=/tmp/install-root

around the end add:

install:
        $(MAKE) -C $(KERNEL_BUILD) M=$(PWD) \
           INSTALL_MOD_PATH=$(INSTALL_ROOT) modules_install

and then you can issue

    sudo make install

this will put it either in /lib/modules/$(uname -r)/extra/

or /lib/modules/$(uname -r)/misc/

and run depmod appropriately

oracle - what statements need to be committed?

And a key point - although TRUNCATE TABLE seems like a DELETE with no WHERE clause, TRUNCATE is not DML, it is DDL. DELETE requires a COMMIT, but TRUNCATE does not.

Python strptime() and timezones?

Ran into this exact problem.

What I ended up doing:

# starting with date string
sdt = "20190901"
std_format = '%Y%m%d'

# create naive datetime object
from datetime import datetime
dt = datetime.strptime(sdt, sdt_format)

# extract the relevant date time items
dt_formatters = ['%Y','%m','%d']
dt_vals = tuple(map(lambda formatter: int(datetime.strftime(dt,formatter)), dt_formatters))

# set timezone
import pendulum
tz = pendulum.timezone('utc')

dt_tz = datetime(*dt_vals,tzinfo=tz)

How do I generate random numbers in Dart?

Here's a snippet for generating a list of random numbers

import 'dart:math';

main() {
  var rng = new Random();
  var l = new List.generate(12, (_) => rng.nextInt(100));
}

This will generate a list of 12 integers from 0 to 99 (inclusive).

Apache VirtualHost 403 Forbidden

If you did everything right, just give the permission home directory like:

sudo chmod o+x $HOME

then

sudo systemctl restart apache2

RHEL 6 - how to install 'GLIBC_2.14' or 'GLIBC_2.15'?

To install GLIBC_2.14 or GLIBC_2.15, download package from /gnu/libc/ index at

https://ftp.gnu.org/gnu/libc/

Then follow instructions listed by Timo:

For example glibc-2.14.tar.gz in your case.

  1. tar xvfz glibc-2.14.tar.gz

  2. cd glibc-2.14

  3. mkdir build

  4. cd build

  5. ../configure --prefix=/opt/glibc-2.14

  6. make

  7. sudo make install

  8. export LD_LIBRARY_PATH=/opt/glibc-2.14/lib:$LD_LIBRARY_PATH

Change Image of ImageView programmatically in Android

In your XML for the image view, where you have android:background="@drawable/thumbs_down change this to android:src="@drawable/thumbs_down"

Currently it is placing that image as the background to the view and not the actual image in it.

Object passed as parameter to another class, by value or reference?

I found the other examples unclear, so I did my own test which confirmed that a class instance is passed by reference and as such actions done to the class will affect the source instance.

In other words, my Increment method modifies its parameter myClass everytime its called.

class Program
{
    static void Main(string[] args)
    {
        MyClass myClass = new MyClass();
        Console.WriteLine(myClass.Value);  // Displays 1
        Increment(myClass);
        Console.WriteLine(myClass.Value);  // Displays 2
        Increment(myClass);
        Console.WriteLine(myClass.Value);  // Displays 3           
        Increment(myClass);
        Console.WriteLine(myClass.Value);  // Displays 4
        Console.WriteLine("Hit Enter to exit.");
        Console.ReadLine();
    }

    public static void Increment(MyClass myClassRef)
    {
        myClassRef.Value++;
    }
}

public class MyClass
{
    public int Value {get;set;}
    public MyClass()
    {
        Value = 1;
    }
}

invalid target release: 1.7

You need to set JAVA_HOME to your jdk7 home directory, for example on Microsoft Windows:

  • "C:\Program Files\Java\jdk1.7.0_40"

or on OS X:

  • /Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home

Converting HTML to plain text in PHP for e-mail

There's the trusty strip_tags function. It's not pretty though. It'll only sanitize. You could combine it with a string replace to get your fancy underscores.


<?php
// to strip all tags and wrap italics with underscore
strip_tags(str_replace(array("<i>", "</i>"), array("_", "_"), $text));

// to preserve anchors...
str_replace("|a", "<a", strip_tags(str_replace("<a", "|a", $text)));

?>

How do I check if PHP is connected to a database already?

Try using PHP's mysql_ping function:

echo @mysql_ping() ? 'true' : 'false';

You will need to prepend the "@" to suppose the MySQL Warnings you'll get for running this function without being connected to a database.

There are other ways as well, but it depends on the code that you're using.

Casting interfaces for deserialization in JSON.NET

(Copied from this question)

In cases where I have not had control over the incoming JSON (and so cannot ensure that it includes a $type property) I have written a custom converter that just allows you to explicitly specify the concrete type:

public class Model
{
    [JsonConverter(typeof(ConcreteTypeConverter<Something>))]
    public ISomething TheThing { get; set; }
}

This just uses the default serializer implementation from Json.Net whilst explicitly specifying the concrete type.

An overview are available on this blog post. Source code is below:

public class ConcreteTypeConverter<TConcrete> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        //assume we can convert to anything for now
        return true;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        //explicitly specify the concrete type we want to create
        return serializer.Deserialize<TConcrete>(reader);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        //use the default serialization - it works fine
        serializer.Serialize(writer, value);
    }
}

How to remove first 10 characters from a string?

Calling SubString() allocates a new string. For optimal performance, you should avoid that extra allocation. Starting with C# 7.2 you can take advantage of the Span pattern.

When targeting .NET Framework, include the System.Memory NuGet package. For .NET Core projects this works out of the box.

static void Main(string[] args)
{
    var str = "hello world!";
    var span = str.AsSpan(10); // No allocation!

    // Outputs: d!
    foreach (var c in span)
    {
        Console.Write(c);
    }

    Console.WriteLine();
}

Insert image after each list item

The easier way to do it is just:

ul li:after {
    content: url('../images/small_triangle.png');
}

docker error - 'name is already in use by container'

Simple Solution: Goto your docker folder in the system and delete .raw file or docker archive with large size.

MySQL - ignore insert error: duplicate entry

$duplicate_query=mysql_query("SELECT * FROM student") or die(mysql_error());
$duplicate=mysql_num_rows($duplicate_query);
if($duplicate==0)
{
    while($value=mysql_fetch_array($duplicate_query)
    {
        if(($value['name']==$name)&& ($value['email']==$email)&& ($value['mobile']==$mobile)&& ($value['resume']==$resume))
        {
            echo $query="INSERT INTO student(name,email,mobile,resume)VALUES('$name','$email','$mobile','$resume')";
            $res=mysql_query($query);
            if($query)
            {
                echo "Success";
            }
            else
            {
                echo "Error";
            }
            else
            {
                echo "Duplicate Entry";
            }
        }
    }
}
else
{
    echo "Records Already Exixts";
}

Select n random rows from SQL Server table

I was using it in subquery and it returned me same rows in subquery

 SELECT  ID ,
            ( SELECT TOP 1
                        ImageURL
              FROM      SubTable 
              ORDER BY  NEWID()
            ) AS ImageURL,
            GETUTCDATE() ,
            1
    FROM    Mytable

then i solved with including parent table variable in where

SELECT  ID ,
            ( SELECT TOP 1
                        ImageURL
              FROM      SubTable 
              Where Mytable.ID>0
              ORDER BY  NEWID()
            ) AS ImageURL,
            GETUTCDATE() ,
            1
    FROM    Mytable

Note the where condtition

How can I enable auto complete support in Notepad++?

Autocomplete in Notepad++ is as simple as hitting Ctrl + Enter or Ctrl + Space in the interface.

Ctrl + Enter - as simple as that!

This, for many people, will be better than autocompleting on everything.

C# LINQ select from list

The "in" in Linq-To-Sql uses a reverse logic compared to a SQL query.

Let's say you have a list of integers, and want to find the items that match those integers.

int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var items = from p in context.Items
                 where numbers.Contains(p.ItemId)
                select p;

Anyway, the above works fine in linq-to-sql but not in EF 1.0. Haven't tried it in EF 4.0

Is it possible to serialize and deserialize a class in C++?

I recommend using boost serialization as described by other posters. Here is a good detailed tutorial on how to use it which complements the boost tutorials nicely: http://www.ocoudert.com/blog/2011/07/09/a-practical-guide-to-c-serialization/

how to use XPath with XDocument?

you can use the example from Microsoft - for you without namespace:

using System.Xml.Linq;
using System.Xml.XPath;
var e = xdoc.XPathSelectElement("./Report/ReportInfo/Name");     

should do it

Duplicate AssemblyVersion Attribute

I came across the same when tried add GitVersion tool to update my version in AssemblyInfo.cs. Use VS2017 and .NET Core project. So I just mixed both worlds. My AssemblyInfo.cs contains only version info that was generated by GitVersion tool, my csproj contains remaingin things. Please note I don't use <GenerateAssemblyInfo>false</GenerateAssemblyInfo> I use attributes related to version only (see below). More details here AssemblyInfo properties.

AssemblyInfo.cs

[assembly: AssemblyVersion("0.2.1.0")]
[assembly: AssemblyFileVersion("0.2.1.0")]
[assembly: AssemblyInformationalVersion("0.2.1+13.Branch.master.Sha.119c35af0f529e92e0f75a5e6d8373912d457818")]

my.csproj contains all related to other assemblyu attributes:

<PropertyGroup>
...
<Company>SOME Company </Company>
<Authors>Some Authors</Authors>
<Product>SOME Product</Product>
...
<GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
<GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute><GenerateAssemblyInformationalVersionAttribute>false</GenerateAssemblyInformationalVersionAttribute>

csproj maps to package tab at project properties

JavaScript Array splice vs slice

The slice() method returns a copy of a portion of an array into a new array object.

$scope.participantForms.slice(index, 1);

This does NOT change the participantForms array but returns a new array containing the single element found at the index position in the original array.

The splice() method changes the content of an array by removing existing elements and/or adding new elements.

$scope.participantForms.splice(index, 1);

This will remove one element from the participantForms array at the index position.

These are the Javascript native functions, AngularJS has nothing to do with them.

How to copy a file to multiple directories using the gnu cp command

These answers all seem more complicated than the obvious:

for i in /foo /bar; do cp "$file1" "$i"; done

Laravel Eloquent "WHERE NOT IN"

You can use this example for dynamically calling the Where NOT IN

$user = User::where('company_id', '=', 1)->select('id)->get()->toArray();

$otherCompany = User::whereNotIn('id', $user)->get();

Change the Arrow buttons in Slick slider

Here is my example of how to change the arrows for Slick Carousel in React to anything you would like. First you need to set the nextArrow and prevArrow in settings to a function then return a div in that function with whatever icon you would like to use. For mine I used Font Awesome. Then you will need to add a className in your icon, you will see that in the NextArrow and PrevArrow functions. Then add the scss code to customize whatever you would like.

JSX Code:

function NextArrow(props) {
  const { style, onClick } = props;
  return (
    <div style={{ ...style, display: "block" }} onClick={onClick}>
      <FontAwesomeIcon icon={faChevronRight} size="3x" className="slick-arrow-icon-right" />
    </div>
  );
}

function PrevArrow(props) {
  const { style, onClick } = props;
  return (
    <div style={{ ...style, display: "block" }} onClick={onClick}>
      <FontAwesomeIcon icon={faChevronLeft} size="3x" className="slick-arrow-icon-left" />
    </div>
  );
}

function SlickCarouselArrowChange(props) {
  var settings = {
    className: "slider variable-width",
    dots: true,
    infinite: true,
    centerMode: true,
    slidesToShow: 1,
    slidesToScroll: 1,
    variableWidth: true,
    autoplay: true,
    autoplaySpeed: 2000,
    nextArrow: <NextArrow />,
    prevArrow: <PrevArrow />,
  };

  return (
    <div className="slick-slider">
      <Slider {...settings}>
        {props.searchResults.map((image, index) => (
          <div key={index}>
            <img src={image.urls.small} />{" "}
          </div>
        ))}
      </Slider>
    </div>
  );
}

SCSS Code:

.slick-arrow-icon-left,
.slick-arrow-icon-right {
  position: absolute;
  display: block;
  cursor: pointer;
  background: transparent;
  color: black;
  top: 50%;
  -webkit-transform: translate(0, -50%);
  -ms-transform: translate(0, -50%);
  transform: translate(0, -50%);
  padding: 0;
  border: none;
  outline: none;
  transition: 0.5s ease-in-out;
  &:hover,
  &:focus {
    outline: none;
    background: transparent;
    color: black;
    font-size: 40px;
    &::before {
      opacity: 1;
    }
  }
}

.slick-arrow-icon-left {
  left: -50px;
  [dir="rtl"] & {
    left: auto;
    right: -50px;
  }
}

.slick-arrow-icon-right {
  right: -50px;
  [dir="rtl"] & {
    left: -50px;
    right: auto;
  }
}

Example Link:

https://slick-carousel-arrow-change.herokuapp.com/

Source Code:

https://github.com/Apocilyptica/slick-carousel-arrow-change

How to implement an STL-style iterator and avoid common pitfalls?

And now a keys iterator for range-based for loop.

template<typename C>
class keys_it
{
    typename C::const_iterator it_;
public:
    using key_type        = typename C::key_type;
    using pointer         = typename C::key_type*;
    using difference_type = std::ptrdiff_t;

    keys_it(const typename C::const_iterator & it) : it_(it) {}

    keys_it         operator++(int               ) /* postfix */ { return it_++         ; }
    keys_it&        operator++(                  ) /*  prefix */ { ++it_; return *this  ; }
    const key_type& operator* (                  ) const         { return it_->first    ; }
    const key_type& operator->(                  ) const         { return it_->first    ; }
    keys_it         operator+ (difference_type v ) const         { return it_ + v       ; }
    bool            operator==(const keys_it& rhs) const         { return it_ == rhs.it_; }
    bool            operator!=(const keys_it& rhs) const         { return it_ != rhs.it_; }
};

template<typename C>
class keys_impl
{
    const C & c;
public:
    keys_impl(const C & container) : c(container) {}
    const keys_it<C> begin() const { return keys_it<C>(std::begin(c)); }
    const keys_it<C> end  () const { return keys_it<C>(std::end  (c)); }
};

template<typename C>
keys_impl<C> keys(const C & container) { return keys_impl<C>(container); }

Usage:

std::map<std::string,int> my_map;
// fill my_map
for (const std::string & k : keys(my_map))
{
    // do things
}

That's what i was looking for. But nobody had it, it seems.

You get my OCD code alignment as a bonus.

As an exercise, write your own for values(my_map)

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

For me, I didn't have xcode installed (on Mojave OS). I went to the App Store on my mac and downloaded it, then went back to terminal and typed git and hit enter, then it worked.

Android Fastboot devices not returning device

I had the same issue, but I was running Ubuntu 12.04 through a VM. I am using a Nexus 10. I had added the usb device as a filter for the VM (using virtual box in the virtual machine's settings).

The device I had added was "samsung Nexus 10".

The problem is that once the device is in fastboot mode, it shows up as a different device: "Google, Inc Android 1.0." So doing "lsusb" in the VM showed no device connected, and obviously "fastboot devices" returned nothing until I added the "second" device as a filter for the VM as well.

Hope this helps someone.

Keytool is not recognized as an internal or external command

Run the cmd as run as administrator this worked for me

how to clear JTable

Basically, it depends on the TableModel that you are using for your JTable. If you are using the DefaultTableModel then you can do it in two ways:

DefaultTableModel dm = (DefaultTableModel)table.getModel();
dm.getDataVector().removeAllElements();
dm.fireTableDataChanged(); // notifies the JTable that the model has changed

or

DefaultTableModel dm = (DefaultTableModel)table.getModel();
while(dm.getRowCount() > 0)
{
    dm.removeRow(0);
}

See the JavaDoc of DefaultTableModel for more details

What is Node.js' Connect, Express and "middleware"?

middleware as the name suggests actually middleware is sit between middle.. middle of what? middle of request and response..how request,response,express server sit in express app in this picture you can see requests are coming from client then the express server server serves those requests.. then lets dig deeper.. actually we can divide this whole express server's whole task in to small seperate tasks like in this way. how middleware sit between request and response small chunk of server parts doing some particular task and passed request to next one.. finally doing all the tasks response has been made.. all middle ware can access request object,response object and next function of request response cycle..

this is good example for explaining middleware in express youtube video for middleware

How do I get the serial key for Visual Studio Express?

I have an improvement on the answer @DewiMorgan gave for VS 2008 express. I have since confirmed it also works on VS 2005 express.
It lets you run the software without it EVER requiring registration, and also makes it so you don't have to manually delete the key every 30 days. It does this by preventing the key from ever being written.

(Deleting the correct key can also let you avoid registering VS 2015 "Community Edition," but using permissions to prevent the key being written will make the IDE crash, so I haven't found a great solution for it yet.)

The directions assume Visual C# Express 2008, but this works on all the other visual studio express apps I can find.

  1. Open regedit, head to HKEY_CURRENT_USER\Software\Microsoft\VCSExpress\9.0\Registration.
  2. Delete the value Params. picture of me deleting the value 'Params' in the registry.
  3. Right click on the key 'Registration' in the tree, and click permissions.
  4. Click Advanced...
  5. Go to the permissions tab, and uncheck the box labeled Inherit from parent the permission entries that apply to child objects. Include these with entries explicitly defined here. me unchecking the box
  6. In the dialog that opens, click copy.
    the security dialog that pops up
    Note that in Windows 7 (and 8/8.1, I think), it appears the copy button was renamed to add, as in add inherited permissions as explicit permissions.

    In Windows 10, it appears things changed again. @ravuya says that you might have to manually re-create some of the permissions, as the registry editor no longer offers this exact functionality directly. I don't use Windows very much anymore, so I'll defer to them:

    On Win10, there is a button called "Disable Inheritance" that does the same thing as the checkbox mentioned in step 5. It is necessary to create new permissions just for Registration, instead of inheriting those permissions from an upstream registry key.

  7. Hit OK in the 'Advanced' window.
  8. Back in the first permissions window, click your user, and uncheck Full Control. Me unchecking 'full control'

  9. Do the same thing for the Administrators group. Me unchecking 'full control' for the Administrators group

  10. Hit OK or Apply. Congratulations, you will never again be plagued by the registration nag, and just like WinRAR, your trial will never expire.

You may have to do the same thing for other (non-Visual C#) programs, like Visual Basic express or Visual C++ express.

It has been reported by @IronManMark20 in the comments that simply deleting the registry key works and that Visual Studio does not attempt to re-create the key. I am not sure if I believe this because when I installed VS on a clean windows installation, the key was not created until I ran VS at least once. But for what it's worth, that may be an option as well.

Import cycle not allowed

You may have imported,

project/controllers/base

inside the

project/controllers/routes

You have already imported before. That's not supported.

Button that refreshes the page on click

<a onClick="window.location.reload()">Refresh</a>

This really works perfect for me.

How should I have explained the difference between an Interface and an Abstract class?

All your statements are valid except your first statement (after the Java 8 release):

Methods of a Java interface are implicitly abstract and cannot have implementations

From the documentation page:

An interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods,and nested types

Method bodies exist only for default methods and static methods.

Default methods:

An interface can have default methods, but are different than abstract methods in abstract classes.

Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.

When you extend an interface that contains a default method, you can do the following:

  1. Not mention the default method at all, which lets your extended interface inherit the default method.
  2. Redeclare the default method, which makes it abstract.
  3. Redefine the default method, which overrides it.

Static Methods:

In addition to default methods, you can define static methods in interfaces. (A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods.)

This makes it easier for you to organize helper methods in your libraries;

Example code from documentation page about interface having static and default methods.

import java.time.*;

public interface TimeClient {
    void setTime(int hour, int minute, int second);
    void setDate(int day, int month, int year);
    void setDateAndTime(int day, int month, int year,
                               int hour, int minute, int second);
    LocalDateTime getLocalDateTime();

    static ZoneId getZoneId (String zoneString) {
        try {
            return ZoneId.of(zoneString);
        } catch (DateTimeException e) {
            System.err.println("Invalid time zone: " + zoneString +
                "; using default time zone instead.");
            return ZoneId.systemDefault();
        }
    }

    default ZonedDateTime getZonedDateTime(String zoneString) {
        return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
    }
}

Use the below guidelines to chose whether to use an interface or abstract class.

Interface:

  1. To define a contract ( preferably stateless - I mean no variables )
  2. To link unrelated classes with has a capabilities.
  3. To declare public constant variables (immutable state)

Abstract class:

  1. Share code among several closely related classes. It establishes is a relation.

  2. Share common state among related classes ( state can be modified in concrete classes)

Related posts:

Interface vs Abstract Class (general OO)

Implements vs extends: When to use? What's the difference?

By going through these examples, you can understand that

Unrelated classes can have capabilities through interface but related classes change the behaviour through extension of base classes.

Adding ID's to google map markers

Marker already has unique id

marker.__gm_id

how to extract only the year from the date in sql server 2008?

DATEPART(yyyy, date_column) could be used to extract year. In general, DATEPART function is used to extract specific portions of a date value.

An array of List in c#

You do like this:

List<int>[] a = new List<int>[100];

Now you have an array of type List<int> containing 100 null references. You have to create lists and put in the array, for example:

a[0] = new List<int>();

What does "static" mean in C?

static means different things in different contexts.

  1. You can declare a static variable in a C function. This variable is only visible in the function however it behaves like a global in that it is only initialized once and it retains its value. In this example, everytime you call foo() it will print an increasing number. The static variable is initialized only once.

    void foo ()
    {
    static int i = 0;
    printf("%d", i); i++
    }
    
  2. Another use of static is when you implement a function or global variable in a .c file but don't want its symbol to be visible outside of the .obj generated by the file. e.g.

    static void foo() { ... }
    

How to split comma separated string using JavaScript?

_x000D_
_x000D_
var result;_x000D_
result = "1,2,3".split(","); _x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

More info on W3Schools describing the String Split function.

Sending an HTTP POST request on iOS

Using Swift 3 or 4 you can access these http request for sever communication.

// For POST data to request

 func postAction()  {
//declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid
let parameters = ["id": 13, "name": "jack"] as [String : Any]
//create the url with URL
let url = URL(string: "www.requestURL.php")! //change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
do {
    request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
    print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
    guard error == nil else {
        return
    }
    guard let data = data else {
        return
    }
    do {
        //create json object from data
        if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
            print(json)
            // handle json...
        }
    } catch let error {
        print(error.localizedDescription)
    }
})
task.resume() }

// For get the data from request

func GetRequest()  {
    let urlString = URL(string: "http://www.requestURL.php") //change the url

    if let url = urlString {
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print(error ?? "")
            } else {
                if let responceData = data {
                    print(responceData) //JSONSerialization
                    do {
                        //create json object from data
                        if let json = try JSONSerialization.jsonObject(with:responceData, options: .mutableContainers) as? [String: Any] {
                            print(json)
                            // handle json...
                        }
                    } catch let error {
                        print(error.localizedDescription)
                    }
                }
            }
        }
        task.resume()
    }
}

// For get the download content like image or video from request

func downloadTask()  {
    // Create destination URL
    let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
    let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg")
    //Create URL to the source file you want to download
    let fileURL = URL(string: "http://placehold.it/120x120&text=image1")
    let sessionConfig = URLSessionConfiguration.default
    let session = URLSession(configuration: sessionConfig)
    let request = URLRequest(url:fileURL!)

    let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
        if let tempLocalUrl = tempLocalUrl, error == nil {
            // Success
            if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                print("Successfully downloaded. Status code: \(statusCode)")
            }

            do {
                try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
            } catch (let writeError) {
                print("Error creating a file \(destinationFileUrl) : \(writeError)")
            }

        } else {
            print("Error took place while downloading a file. Error description: %@", error?.localizedDescription ?? "");
        }
    }
    task.resume()

}

How can I kill whatever process is using port 8080 so that I can vagrant up?

This might help

lsof -n -i4TCP:8080 

The PID is the second field in the output.

Or try:

lsof -i -P

Difference between <context:annotation-config> and <context:component-scan>

The <context:annotation-config> tag tells Spring to scan the codebase for automatically resolving dependency requirements of the classes containing @Autowired annotation.

Spring 2.5 also adds support for JSR-250 annotations such as @Resource, @PostConstruct, and @PreDestroy.Use of these annotations also requires that certain BeanPostProcessors be registered within the Spring container. As always, these can be registered as individual bean definitions, but they can also be implicitly registered by including <context:annotation-config> tag in spring configuration.

Taken from Spring documentation of Annotation Based Configuration


Spring provides the capability of automatically detecting 'stereotyped' classes and registering corresponding BeanDefinitions with the ApplicationContext.

According to javadoc of org.springframework.stereotype:

Stereotypes are Annotations denoting the roles of types or methods in the overall architecture (at a conceptual, rather than implementation, level). Example: @Controller @Service @Repository etc. These are intended for use by tools and aspects (making an ideal target for pointcuts).

To autodetect such 'stereotype' classes, <context:component-scan> tag is required.

The <context:component-scan> tag also tells Spring to scan the code for injectable beans under the package (and all its subpackages) specified.

What's the scope of a variable initialized in an if statement?

Scope in python follows this order:

  • Search the local scope

  • Search the scope of any enclosing functions

  • Search the global scope

  • Search the built-ins

(source)

Notice that if and other looping/branching constructs are not listed - only classes, functions, and modules provide scope in Python, so anything declared in an if block has the same scope as anything decleared outside the block. Variables aren't checked at compile time, which is why other languages throw an exception. In python, so long as the variable exists at the time you require it, no exception will be thrown.

If Else If In a Sql Server Function

Look at these lines:

If yes_ans > no_ans and yes_ans > na_ans

and similar. To what do "yes_ans" etc. refer? You're not using these in the context of a query; the "if exists" condition doesn't extend to the column names you're using inside.

Consider assigning those values to variables you can then use for your conditional flow below. Thus,

if exists (some record)
begin
   set @var = column, @var2 = column2, ...

   if (@var1 > @var2)
      -- do something

end

The return type is also mismatched with the declaration. It would help a lot if you indented, used ANSI-standard punctuation (terminate statements with semicolons), and left out superfluous begin/end - you don't need these for single-statement lines executed as the result of a test.

How do I reformat HTML code using Sublime Text 2?

I recommend this plugin: HTML/CSS/JS Prettify, It really works.

After the installation, just select the code and press Ctrl+Shift+H.

Done!

CardView not showing Shadow in Android L

After going through the docs again, I finally found the solution.

Just add card_view:cardUseCompatPadding="true" to your CardView and shadows will appear on Lollipop devices.

What happens is, the content area in a CardView take different sizes on pre-lollipop and lollipop devices. So in lollipop devices the shadow is actually covered by the card so its not visible. By adding this attribute the content area remains the same across all devices and the shadow becomes visible.

My xml code is like :

<android.support.v7.widget.CardView
    android:id="@+id/media_card_view"
    android:layout_width="match_parent"
    android:layout_height="130dp"
    card_view:cardBackgroundColor="@android:color/white"
    card_view:cardElevation="2dp"
    card_view:cardUseCompatPadding="true"
    >
...
</android.support.v7.widget.CardView>

How to run vbs as administrator from vbs?

If UAC is enabled on the computer, something like this should work:

If Not WScript.Arguments.Named.Exists("elevate") Then
  CreateObject("Shell.Application").ShellExecute WScript.FullName _
    , """" & WScript.ScriptFullName & """ /elevate", "", "runas", 1
  WScript.Quit
End If

'actual code

Regex pattern for checking if a string starts with a certain substring?

You could use:

^(mailto|ftp|joe)

But to be honest, StartsWith is perfectly fine to here. You could rewrite it as follows:

string[] prefixes = { "http", "mailto", "joe" };
string s = "joe:bloggs";
bool result = prefixes.Any(prefix => s.StartsWith(prefix));

You could also look at the System.Uri class if you are parsing URIs.

Is there a way to link someone to a YouTube Video in HD 1080p quality?

Yes there is:

https://www.youtube.com/embed/kObNpTFPV5c?vq=hd1440
https://www.youtube.com/embed/kObNpTFPV5c?vq=hd1080
etc...

Options are:

Code for 1440: vq=hd1440
Code for 1080: vq=hd1080
Code for 720: vq=hd720
Code for 480p: vq=large
Code for 360p: vq=medium
Code for 240p: vq=small

UPDATE
As of 10 of April 2018, this code still works.
Some users reported "not working", if it doesn't work for you, please read below:

From what I've learned, the problem is related with network speed and or screen size.
When YT player starts, it collects the network speed, screen and player sizes, among other information, if the connection is slow or the screen/player size smaller than the quality requested(vq=), a lower quality video is displayed despite the option selected on vq=.

Also make sure you read the comments below.

Warning about SSL connection when connecting to MySQL database

I use this property for hibernate in config xml

<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/bookshop?serverTimezone=UTC&amp;useSSL=false
</property>

without - serverTimezone=UTC - it doesn't work

How to delete a localStorage item when the browser window/tab is closed?

Use with window global keyword:-

 window.localStorage.removeItem('keyName');

How to do an update + join in PostgreSQL?

First Table Name: tbl_table1 (tab1). Second Table Name: tbl_table2 (tab2).

Set the tbl_table1's ac_status column to "INACTIVE"

update common.tbl_table1 as tab1
set ac_status= 'INACTIVE' --tbl_table1's "ac_status"
from common.tbl_table2 as tab2
where tab1.ref_id= '1111111' 
and tab2.rel_type= 'CUSTOMER';

How do you make a LinearLayout scrollable?

This can be done using the tag <ScrollView>. For ScrollView, one thing you have to remind that, ScrollView must have a single child.

If you want your full layout to be scrollable then add <ScrollView> at the top. Check the example given below.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scroll" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout 
        android:id="@+id/container" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
            <!-- Content here -->
    </LinearLayout>

</ScrollView>

But if you want some part of your layout to be scrollable then add <ScrollView> within that part. Check the example given below.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="400dp">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">
                <!-- Content here -->
        </LinearLayout>

    </ScrollView>

</LinearLayout>

Timestamp to human readable format

getDay() returns the day of the week. To get the date, use date.getDate(). getMonth() retrieves the month, but month is zero based, so using getMonth()+1 should give you the right month. Time value seems to be ok here, albeit the hour is 23 here (GMT+1). If you want universal values, add UTC to the methods (e.g. date.getUTCFullYear(), date.getUTCHours())

var timestamp = 1301090400,
date = new Date(timestamp * 1000),
datevalues = [
   date.getFullYear(),
   date.getMonth()+1,
   date.getDate(),
   date.getHours(),
   date.getMinutes(),
   date.getSeconds(),
];
alert(datevalues); //=> [2011, 3, 25, 23, 0, 0]

jQuery .val change doesn't change input value

$('#link').prop('value', 'new value');

Explanation: Attr will work on jQuery 1.6 but as of jQuery 1.6.1 things have changed. In the majority of cases, prop() does what attr() used to do. Replacing calls to attr() with prop() in your code will generally work. Attr will give you the value of element as it was defined in the html on page load and prop gives the updated values of elements which are modified via jQuery.

How do I check if a given Python string is a substring of another one?

string.find("substring") will help you. This function returns -1 when there is no substring.

Hadoop: «ERROR : JAVA_HOME is not set»

In some distributives(CentOS/OpenSuSe,...) will work only if you set JAVA_HOME in the /etc/environment.

Shell - Write variable contents to a file

All of the above work, but also have to work around a problem (escapes and special characters) that doesn't need to occur in the first place: Special characters when the variable is expanded by the shell. Just don't do that (variable expansion) in the first place. Use the variable directly, without expansion.

Also, if your variable contains a secret and you want to copy that secret into a file, you might want to not have expansion in the command line as tracing/command echo of the shell commands might reveal the secret. Means, all answers which use $var in the command line may have a potential security risk by exposing the variable contents to tracing and logging of the shell.

Use this:

printenv var >file

That means, in case of the OP question:

printenv var >"$destfile"

Note: variable names are case sensitive.

Selecting rows where remainder (modulo) is 1 after division by 2?

Note: Disregard this answer, as I must have misunderstood the question.

select *
  from Table
  where len(ColName) mod 2 = 1

The exact syntax depends on what flavor of SQL you're using.

Passing parameters in rails redirect_to

routes.rb

 match 'controller_name/action_name' => 'controller_name#action_name', via: [:get, :post], :as => :abc

Any controller you want to redirect with parameters are given below:

redirect_to abc_path(@abc, id: @id), :notice => "message fine" 

Is the 'as' keyword required in Oracle to define an alias?

(Tested on Oracle 11g)

About AS:

  • When used on result column, AS is optional.
  • When used on table name, AS shouldn't be added, otherwise it's an error.

About double quote:

  • It's optional & valid for both result column & table name.

e.g

-- 'AS' is optional for result column
select (1+1) as result from dual;
select (1+1) result from dual;


-- 'AS' shouldn't be used for table name
select 'hi' from dual d;


-- Adding double quotes for alias name is optional, but valid for both result column & table name,
select (1+1) as "result" from dual;
select (1+1) "result" from dual;

select 'hi' from dual "d";

adding classpath in linux

For linux users, and to sum up and add to what others have said here, you should know the following:

  1. Global variables are not evil. $CLASSPATH is specifically what Java uses to look through multiple directories to find all the different classes it needs for your script (unless you explicitly tell it otherwise with the -cp override).

  2. The colon (":") character separates the different directories. There is only one $CLASSPATH and it has all the directories in it. So, when you run "export CLASSPATH=...." you want to include the current value "$CLASSPATH" in order to append to it. For example:

    export CLASSPATH=.
    export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java-5.1.12.jar
    

    In the first line above, you start CLASSPATH out with just a simple 'dot' which is the path to your current working directory. With that, whenever you run java it will look in the current working directory (the one you're in) for classes. In the second line above, $CLASSPATH grabs the value that you previously entered (.) and appends the path to a mysql dirver. Now, java will look for the driver AND for your classes.

  3. echo $CLASSPATH
    

    is super handy, and what it returns should read like a colon-separated list of all the directories you want java looking in for what it needs to run your script.

  4. Tomcat does not use CLASSPATH. Read what to do about that here: https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html

How to write and read a file with a HashMap?

since HashMap implements Serializable interface, you can simply use ObjectOutputStream class to write whole Map to file, and read it again using ObjectInputStream class

below simple code that explain usage of ObjectOutStream and ObjectInputStream

import java.util.*;
import java.io.*;
public class A{

    HashMap<String,String> hm;
    public A() {
        hm=new HashMap<String,String>();

        hm.put("1","A");
        hm.put("2","B");
        hm.put("3","C");

        method1(hm);

    }

public void method1(HashMap<String,String> map) {
    //write to file : "fileone"
    try {
        File fileOne=new File("fileone");
        FileOutputStream fos=new FileOutputStream(fileOne);
        ObjectOutputStream oos=new ObjectOutputStream(fos);

        oos.writeObject(map);
        oos.flush();
        oos.close();
        fos.close();
    } catch(Exception e) {}

    //read from file 
    try {
        File toRead=new File("fileone");
        FileInputStream fis=new FileInputStream(toRead);
        ObjectInputStream ois=new ObjectInputStream(fis);

        HashMap<String,String> mapInFile=(HashMap<String,String>)ois.readObject();

        ois.close();
        fis.close();
        //print All data in MAP
        for(Map.Entry<String,String> m :mapInFile.entrySet()){
            System.out.println(m.getKey()+" : "+m.getValue());
        }
    } catch(Exception e) {}
  }

public static void main(String args[]) {
        new A();
}

}

or if you want to write data as text to file you can simply iterate through Map and write key and value line by line, and read it again line by line and add to HashMap

import java.util.*;
import java.io.*;
public class A{

    HashMap<String,String> hm;
    public A(){
        hm=new HashMap<String,String>();

        hm.put("1","A");
        hm.put("2","B");
        hm.put("3","C");

        method2(hm);

    }

public void method2(HashMap<String,String> map) {
    //write to file : "fileone"
    try {
        File fileTwo=new File("filetwo.txt");
        FileOutputStream fos=new FileOutputStream(fileTwo);
        PrintWriter pw=new PrintWriter(fos);

        for(Map.Entry<String,String> m :map.entrySet()){
            pw.println(m.getKey()+"="+m.getValue());
        }

        pw.flush();
        pw.close();
        fos.close();
    } catch(Exception e) {}

    //read from file 
    try {
        File toRead=new File("filetwo.txt");
        FileInputStream fis=new FileInputStream(toRead);

        Scanner sc=new Scanner(fis);

        HashMap<String,String> mapInFile=new HashMap<String,String>();

        //read data from file line by line:
        String currentLine;
        while(sc.hasNextLine()) {
            currentLine=sc.nextLine();
            //now tokenize the currentLine:
            StringTokenizer st=new StringTokenizer(currentLine,"=",false);
            //put tokens ot currentLine in map
            mapInFile.put(st.nextToken(),st.nextToken());
        }
        fis.close();

        //print All data in MAP
        for(Map.Entry<String,String> m :mapInFile.entrySet()) {
            System.out.println(m.getKey()+" : "+m.getValue());
        }
    }catch(Exception e) {}
  }

public static void main(String args[]) {
        new A();
}

}

NOTE: above code may not be the fastest way to doing this task, but i want to show some application of classes

See ObjectOutputStream , ObjectInputStream, HashMap, Serializable, StringTokenizer

How do I convert two lists into a dictionary?

A more natural way is to use dictionary comprehension

keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')    
dict = {keys[i]: values[i] for i in range(len(keys))}

Maximum size for a SQL Server Query? IN clause? Is there a Better Approach

The SQL Server Maximums are disclosed http://msdn.microsoft.com/en-us/library/ms143432.aspx (this is the 2008 version)

A SQL Query can be a varchar(max) but is shown as limited to 65,536 * Network Packet size, but even then what is most likely to trip you up is the 2100 parameters per query. If SQL chooses to parameterize the literal values in the in clause, I would think you would hit that limit first, but I havn't tested it.

Edit : Test it, even under forced parameteriztion it survived - I knocked up a quick test and had it executing with 30k items within the In clause. (SQL Server 2005)

At 100k items, it took some time then dropped with:

Msg 8623, Level 16, State 1, Line 1 The query processor ran out of internal resources and could not produce a query plan. This is a rare event and only expected for extremely complex queries or queries that reference a very large number of tables or partitions. Please simplify the query. If you believe you have received this message in error, contact Customer Support Services for more information.

So 30k is possible, but just because you can do it - does not mean you should :)

Edit : Continued due to additional question.

50k worked, but 60k dropped out, so somewhere in there on my test rig btw.

In terms of how to do that join of the values without using a large in clause, personally I would create a temp table, insert the values into that temp table, index it and then use it in a join, giving it the best opportunities to optimse the joins. (Generating the index on the temp table will create stats for it, which will help the optimiser as a general rule, although 1000 GUIDs will not exactly find stats too useful.)

How to parse a JSON string to an array using Jackson

The other answer is correct, but for completeness, here are other ways:

List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { });
SomeClass[] array = mapper.readValue(jsonString, SomeClass[].class);

Escape sequence \f - form feed - what exactly is it?

It skips to the start of the next page. (Applies mostly to terminals where the output device is a printer rather than a VDU.)

How does DateTime.Now.Ticks exactly work?

You can get the milliseconds since 1/1/1970 using such code:

private static DateTime JanFirst1970 = new DateTime(1970, 1, 1);
public static long getTime()
{
    return (long)((DateTime.Now.ToUniversalTime() - JanFirst1970).TotalMilliseconds + 0.5);
}

Stateless vs Stateful

I suggest that you start from a question in StackOverflow that discusses the advantages of stateless programming. This is more in the context of functional programming, but what you will read also applies in other programming paradigms.

Stateless programming is related to the mathematical notion of a function, which when called with the same arguments, always return the same results. This is a key concept of the functional programming paradigm and I expect that you will be able to find many relevant articles in that area.

Another area that you could research in order to gain more understanding is RESTful web services. These are by design "stateless", in contrast to other web technologies that try to somehow keep state. (In fact what you say that ASP.NET is stateless isn't correct - ASP.NET tries hard to keep state using ViewState and are definitely to be characterized as stateful. ASP.NET MVC on the other hand is a stateless technology). There are many places that discuss "statelessness" of RESTful web services (like this blog spot), but you could again start from an SO question.

Using CSS :before and :after pseudo-elements with inline CSS?

you can use

parent.style.setProperty("--padding-top", (height*100/width).toFixed(2)+"%");

in css

el:after{
  ....
  padding-top:var(--padding-top, 0px);
}

Tool to compare directories (Windows 7)

The tool that richardtz suggests is excellent.

Another one that is amazing and comes with a 30 day free trial is Araxis Merge. This one does a 3 way merge and is much more feature complete than winmerge, but it is a commercial product.

You might also like to check out Scott Hanselman's developer tool list, which mentions a couple more in addition to winmerge

PHP Warning: PHP Startup: Unable to load dynamic library

It means there is an extension=... or zend_extension=... line in one of your php configuration files (php.ini, or another close to it) that is trying to load that extension : ixed.5.2.lin

Unfortunately that file or path doesn't exist or the permissions are incorrect.

  1. Try to search in the .ini files that are loaded by PHP (phpinfo() can indicate which ones are) - one of them should try to load that extension.
  2. Either correct the path to the file or comment out the corresponding line.

SQL Insert Query Using C#

class Program
{
    static void Main(string[] args)
    {
        string connetionString = null;
        SqlConnection connection;
        SqlCommand command;
        string sql = null;

        connetionString = "Data Source=Server Name;Initial Catalog=DataBaseName;User ID=UserID;Password=Password";
        sql = "INSERT INTO LoanRequest(idLoanRequest,RequestDate,Pickupdate,ReturnDate,EventDescription,LocationOfEvent,ApprovalComments,Quantity,Approved,EquipmentAvailable,ModifyRequest,Equipment,Requester)VALUES('5','2016-1-1','2016-2-2','2016-3-3','DescP','Loca1','Appcoment','2','true','true','true','4','5')";
        connection = new SqlConnection(connetionString);

        try
        {
            connection.Open();
            Console.WriteLine(" Connection Opened ");
            command = new SqlCommand(sql, connection);                
            SqlDataReader dr1 = command.ExecuteReader();         

            connection.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Can not open connection ! ");
        }
    }
}

Prevent flex items from overflowing a container

One easy solution is to use overflow values other than visible to make the text flex basis width reset as expected.

  1. Here with value auto the text wraps as expected and the article content does not overflow main container.

  2. Also, the article flex value must either have a auto basis AND be able to shrink, OR, only grow AND explicit 0 basis

_x000D_
_x000D_
main, aside, article {_x000D_
  margin: 10px;_x000D_
  border: solid 1px #000;_x000D_
  border-bottom: 0;_x000D_
  height: 50px;_x000D_
  overflow: auto; /* 1. overflow not `visible` */_x000D_
}_x000D_
main {_x000D_
  display: flex;_x000D_
}_x000D_
aside {_x000D_
  flex: 0 0 200px;_x000D_
}_x000D_
article {_x000D_
  flex: 1 1 auto; /* 2. Allow auto width content to shrink */_x000D_
  /* flex: 1 0 0; /* Or, explicit 0 width basis that grows */_x000D_
}
_x000D_
<main>_x000D_
  <aside>x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x </aside>_x000D_
  <article>don't let flex item overflow container.... y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y </article>_x000D_
</main>
_x000D_
_x000D_
_x000D_

Add a UIView above all, even the navigation bar

UIApplication.shared.keyWindow?.insertSubview(yourView, at: 1)

This method works with xcode 9.4 , iOS 11.4

Java Garbage Collection Log messages

Most of it is explained in the GC Tuning Guide (which you would do well to read anyway).

The command line option -verbose:gc causes information about the heap and garbage collection to be printed at each collection. For example, here is output from a large server application:

[GC 325407K->83000K(776768K), 0.2300771 secs]
[GC 325816K->83372K(776768K), 0.2454258 secs]
[Full GC 267628K->83769K(776768K), 1.8479984 secs]

Here we see two minor collections followed by one major collection. The numbers before and after the arrow (e.g., 325407K->83000K from the first line) indicate the combined size of live objects before and after garbage collection, respectively. After minor collections the size includes some objects that are garbage (no longer alive) but that cannot be reclaimed. These objects are either contained in the tenured generation, or referenced from the tenured or permanent generations.

The next number in parentheses (e.g., (776768K) again from the first line) is the committed size of the heap: the amount of space usable for java objects without requesting more memory from the operating system. Note that this number does not include one of the survivor spaces, since only one can be used at any given time, and also does not include the permanent generation, which holds metadata used by the virtual machine.

The last item on the line (e.g., 0.2300771 secs) indicates the time taken to perform the collection; in this case approximately a quarter of a second.

The format for the major collection in the third line is similar.

The format of the output produced by -verbose:gc is subject to change in future releases.

I'm not certain why there's a PSYoungGen in yours; did you change the garbage collector?

How to register multiple implementations of the same interface in Asp.Net Core?

While it seems @Miguel A. Arilla has pointed it out clearly and I voted up for him, I created on top of his useful solution another solution which looks neat but requires a lot more work.

It definitely depends on the above solution. So basically I created something similar to Func<string, IService>> and I called it IServiceAccessor as an interface and then I had to add a some more extensions to the IServiceCollection as such:

public static IServiceCollection AddSingleton<TService, TImplementation, TServiceAccessor>(
            this IServiceCollection services,
            string instanceName
        )
            where TService : class
            where TImplementation : class, TService
            where TServiceAccessor : class, IServiceAccessor<TService>
        {
            services.AddSingleton<TService, TImplementation>();
            services.AddSingleton<TServiceAccessor>();
            var provider = services.BuildServiceProvider();
            var implementationInstance = provider.GetServices<TService>().Last();
            var accessor = provider.GetServices<TServiceAccessor>().First();

            var serviceDescriptors = services.Where(d => d.ServiceType == typeof(TServiceAccessor));
            while (serviceDescriptors.Any())
            {
                services.Remove(serviceDescriptors.First());
            }

            accessor.SetService(implementationInstance, instanceName);
            services.AddSingleton<TServiceAccessor>(prvd => accessor);
            return services;
        }

The service Accessor looks like:

 public interface IServiceAccessor<TService>
    {
         void Register(TService service,string name);
         TService Resolve(string name);

    }

The end result,you will be able to register services with names or named instances like we used to do with other containers..for instance:

    services.AddSingleton<IEncryptionService, SymmetricEncryptionService, EncyptionServiceAccessor>("Symmetric");
    services.AddSingleton<IEncryptionService, AsymmetricEncryptionService, EncyptionServiceAccessor>("Asymmetric");

That is enough for now, but to make your work complete, it is better to add more extension methods as you can to cover all types of registrations following the same approach.

There was another post on stackoverflow, but I can not find it, where the poster has explained in details why this feature is not supported and how to work around it, basically similar to what @Miguel stated. It was nice post even though I do not agree with each point because I think there are situation where you really need named instances. I will post that link here once I find it again.

As a matter of fact, you do not need to pass that Selector or Accessor:

I am using the following code in my project and it worked well so far.

 /// <summary>
    /// Adds the singleton.
    /// </summary>
    /// <typeparam name="TService">The type of the t service.</typeparam>
    /// <typeparam name="TImplementation">The type of the t implementation.</typeparam>
    /// <param name="services">The services.</param>
    /// <param name="instanceName">Name of the instance.</param>
    /// <returns>IServiceCollection.</returns>
    public static IServiceCollection AddSingleton<TService, TImplementation>(
        this IServiceCollection services,
        string instanceName
    )
        where TService : class
        where TImplementation : class, TService
    {
        var provider = services.BuildServiceProvider();
        var implementationInstance = provider.GetServices<TService>().LastOrDefault();
        if (implementationInstance.IsNull())
        {
            services.AddSingleton<TService, TImplementation>();
            provider = services.BuildServiceProvider();
            implementationInstance = provider.GetServices<TService>().Single();
        }
        return services.RegisterInternal(instanceName, provider, implementationInstance);
    }

    private static IServiceCollection RegisterInternal<TService>(this IServiceCollection services,
        string instanceName, ServiceProvider provider, TService implementationInstance)
        where TService : class
    {
        var accessor = provider.GetServices<IServiceAccessor<TService>>().LastOrDefault();
        if (accessor.IsNull())
        {
            services.AddSingleton<ServiceAccessor<TService>>();
            provider = services.BuildServiceProvider();
            accessor = provider.GetServices<ServiceAccessor<TService>>().Single();
        }
        else
        {
            var serviceDescriptors = services.Where(d => d.ServiceType == typeof(IServiceAccessor<TService>));
            while (serviceDescriptors.Any())
            {
                services.Remove(serviceDescriptors.First());
            }
        }
        accessor.Register(implementationInstance, instanceName);
        services.AddSingleton<TService>(prvd => implementationInstance);
        services.AddSingleton<IServiceAccessor<TService>>(prvd => accessor);
        return services;
    }

    //
    // Summary:
    //     Adds a singleton service of the type specified in TService with an instance specified
    //     in implementationInstance to the specified Microsoft.Extensions.DependencyInjection.IServiceCollection.
    //
    // Parameters:
    //   services:
    //     The Microsoft.Extensions.DependencyInjection.IServiceCollection to add the service
    //     to.
    //   implementationInstance:
    //     The instance of the service.
    //   instanceName:
    //     The name of the instance.
    //
    // Returns:
    //     A reference to this instance after the operation has completed.
    public static IServiceCollection AddSingleton<TService>(
        this IServiceCollection services,
        TService implementationInstance,
        string instanceName) where TService : class
    {
        var provider = services.BuildServiceProvider();
        return RegisterInternal(services, instanceName, provider, implementationInstance);
    }

    /// <summary>
    /// Registers an interface for a class
    /// </summary>
    /// <typeparam name="TInterface">The type of the t interface.</typeparam>
    /// <param name="services">The services.</param>
    /// <returns>IServiceCollection.</returns>
    public static IServiceCollection As<TInterface>(this IServiceCollection services)
         where TInterface : class
    {
        var descriptor = services.Where(d => d.ServiceType.GetInterface(typeof(TInterface).Name) != null).FirstOrDefault();
        if (descriptor.IsNotNull())
        {
            var provider = services.BuildServiceProvider();
            var implementationInstance = (TInterface)provider?.GetServices(descriptor?.ServiceType)?.Last();
            services?.AddSingleton(implementationInstance);
        }
        return services;
    }

Mean Squared Error in Numpy?

Another alternative to the accepted answer that avoids any issues with matrix multiplication:

 def MSE(Y, YH):
     return np.square(Y - YH).mean()

From the documents for np.square: "Return the element-wise square of the input."

Jquery function BEFORE form submission

You can use the onsubmit function.

If you return false the form won't get submitted. Read up about it here.

$('#myform').submit(function() {
  // your code here
});

Avoid printStackTrace(); use a logger call instead

Almost every logging framework provides a method in which we can pass the throwable object along with a message. Like:

public trace(Marker marker, String msg, Throwable t);

They print the stacktrace of the throwable object.

jQuery: get data attribute

You could use the .attr() function:

$(this).attr('data-fullText')

or if you lowercase the attribute name:

data-fulltext="This is a span element"

then you could use the .data() function:

$(this).data('fulltext')

The .data() function expects and works only with lowercase attribute names.

How do I compile and run a program in Java on my Mac?

I will give you steps to writing and compiling code. Use this example:

 public class Paycheck {
    public static void main(String args[]) {
        double amountInAccount;
        amountInAccount = 128.57;
        System.out.print("You earned $");
        System.out.print(amountInAccount);
        System.out.println(" at work today.");
    }
}
  1. Save the code as Paycheck.java
  2. Go to terminal and type cd Desktop
  3. Type javac Paycheck.java
  4. Type java Paycheck
  5. Enjoy your program!

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

  1. Search for sqllocaldb or localDB in your windows start menu and right click on open file location
  2. Open command prompt in the file location you found from the search
  3. On your command prompt type sqllocaldb start

  4. Use <add name="defaultconnection" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=tododb;Integrated Security=True" providerName="System.Data.SqlClient" />

How do I get the current username in .NET using C#?

I've tried all the previous answers and found the answer on MSDN after none of these worked for me. See 'UserName4' for the correct one for me.

I'm after the Logged in User, as displayed by:

<asp:LoginName ID="LoginName1" runat="server" />

Here's a little function I wrote to try them all. My result is in the comments after each row.

protected string GetLoggedInUsername()
{
    string UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; // Gives NT AUTHORITY\SYSTEM
    String UserName2 = Request.LogonUserIdentity.Name; // Gives NT AUTHORITY\SYSTEM
    String UserName3 = Environment.UserName; // Gives SYSTEM
    string UserName4 = HttpContext.Current.User.Identity.Name; // Gives actual user logged on (as seen in <ASP:Login />)
    string UserName5 = System.Windows.Forms.SystemInformation.UserName; // Gives SYSTEM
    return UserName4;
}

Calling this function returns the logged in username by return.

Update: I would like to point out that running this code on my Local server instance shows me that Username4 returns "" (an empty string), but UserName3 and UserName5 return the logged in User. Just something to beware of.

Could not install packages due to an EnvironmentError: [Errno 13]

The answer is in the error message. In the past you or a process did a sudo pip and that caused some of the directories under /Library/Python/2.7/site-packages/... to have permissions that make it unaccessable to your current user.

Then you did a pip install whatever which relies on the other thing.

So to fix it, visit the /Library/Python/2.7/site-packages/... and find the directory with the root or not-your-user permissions and either remove then reinstall those packages, or just force ownership to the user to whom ought to have access.

How to hide form code from view code/inspect element browser?

This code removes the inner html of an element from the dom when the debugger is open (tested in Chrome and IE)

var currentInnerHtml;
var element = new Image();
var elementWithHiddenContent = document.querySelector("#element-to-hide");
var innerHtml = elementWithHiddenContent.innerHTML;

element.__defineGetter__("id", function() {
    currentInnerHtml = "";
});

setInterval(function() {
    currentInnerHtml = innerHtml;
    console.log(element);
    console.clear();
    elementWithHiddenContent.innerHTML = currentInnerHtml;
}, 1000);

Here #element-to-hide is the id of element you want to hide. It is a hack, but I hope it helps you.

Loading another html page from javascript

Is it possible (work only online and load only your page or file): https://w3schools.com/xml/xml_http.asp Try my code:

function load_page(){
qr=new XMLHttpRequest();
qr.open('get','YOUR_file_or_page.htm');
qr.send();
qr.onload=function(){YOUR_div_id.innerHTML=qr.responseText}
};load_page();

qr.onreadystatechange instead qr.onload also use.

exceeds the list view threshold 5000 items in Sharepoint 2010

I had the same problem.please do the following it may help you: By Default List View Threshold set at only 5,000 items this is because of Sharepoint server performance.

To Change the LVT:

  1. Click SharePoint Central Administration,
  2. Go to Application Management
  3. Manage Web Applications
  4. Select your application
  5. Click General Settings at the ribbon
  6. Select Resource Throttling
  7. List View Threshold limit --> change the value to your need.
  8. Also change the List View Threshold for Auditors and Administrators.if you are a administrator.

Click OK to save it.

What's the most efficient way to erase duplicates and sort a vector?

Here's the example of the duplicate delete problem that occurs with std::unique(). On a LINUX machine, the program crashes. Read the comments for details.

// Main10.cpp
//
// Illustration of duplicate delete and memory leak in a vector<int*> after calling std::unique.
// On a LINUX machine, it crashes the progam because of the duplicate delete.
//
// INPUT : {1, 2, 2, 3}
// OUTPUT: {1, 2, 3, 3}
//
// The two 3's are actually pointers to the same 3 integer in the HEAP, which is BAD
// because if you delete both int* pointers, you are deleting the same memory
// location twice.
//
//
// Never mind the fact that we ignore the "dupPosition" returned by std::unique(),
// but in any sensible program that "cleans up after istelf" you want to call deletex
// on all int* poitners to avoid memory leaks.
//
//
// NOW IF you replace std::unique() with ptgi::unique(), all of the the problems disappear.
// Why? Because ptgi:unique merely reshuffles the data:
// OUTPUT: {1, 2, 3, 2}
// The ptgi:unique has swapped the last two elements, so all of the original elements in
// the INPUT are STILL in the OUTPUT.
//
// 130215   [email protected]
//============================================================================

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

#include "ptgi_unique.hpp"

// functor used by std::unique to remove adjacent elts from vector<int*>
struct EqualToVectorOfIntegerStar: public std::equal_to<int *>
{
    bool operator() (const int* arg1, const int* arg2) const
    {
        return (*arg1 == *arg2);
    }
};

void printVector( const std::string& msg, const std::vector<int*>& vnums);

int main()
{
    int inums [] = { 1, 2, 2, 3 };
    std::vector<int*> vnums;

    // convert C array into vector of pointers to integers
    for (size_t inx = 0; inx < 4; ++ inx)
        vnums.push_back( new int(inums[inx]) );

    printVector("BEFORE UNIQ", vnums);

    // INPUT : 1, 2A, 2B, 3
    std::unique( vnums.begin(), vnums.end(), EqualToVectorOfIntegerStar() );
    // OUTPUT: 1, 2A, 3, 3 }
    printVector("AFTER  UNIQ", vnums);

    // now we delete 3 twice, and we have a memory leak because 2B is not deleted.
    for (size_t inx = 0; inx < vnums.size(); ++inx)
    {
        delete(vnums[inx]);
    }
}

// print a line of the form "msg: 1,2,3,..,5,6,7\n", where 1..7 are the numbers in vnums vector
// PS: you may pass "hello world" (const char *) because of implicit (automatic) conversion
// from "const char *" to std::string conversion.

void printVector( const std::string& msg, const std::vector<int*>& vnums)
{
    std::cout << msg << ": ";

    for (size_t inx = 0; inx < vnums.size(); ++inx)
    {
        // insert comma separator before current elt, but ONLY after first elt
        if (inx > 0)
            std::cout << ",";
        std::cout << *vnums[inx];

    }
    std::cout << "\n";
}

Matplotlib scatter plot with different text at each data point

As a one liner using list comprehension and numpy:

[ax.annotate(x[0], (x[1], x[2])) for x in np.array([n,z,y]).T]

setup is ditto to Rutger's answer.

How do I view the Explain Plan in Oracle Sql developer?

EXPLAIN PLAN FOR

In SQL Developer, you don't have to use EXPLAIN PLAN FOR statement. Press F10 or click the Explain Plan icon.

enter image description here

It will be then displayed in the Explain Plan window.

If you are using SQL*Plus then use DBMS_XPLAN.

For example,

SQL> EXPLAIN PLAN FOR
  2  SELECT * FROM DUAL;

Explained.

SQL> SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);

PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------
Plan hash value: 272002086

--------------------------------------------------------------------------
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |      |     1 |     2 |     2   (0)| 00:00:01 |
|   1 |  TABLE ACCESS FULL| DUAL |     1 |     2 |     2   (0)| 00:00:01 |
--------------------------------------------------------------------------

8 rows selected.

SQL>

See How to create and display Explain Plan

How to create enum like type in TypeScript?

Enums in typescript:

Enums are put into the typescript language to define a set of named constants. Using enums can make our life easier. The reason for this is that these constants are often easier to read than the value which the enum represents.

Creating a enum:

enum Direction {
    Up = 1,
    Down,
    Left,
    Right,
}

This example from the typescript docs explains very nicely how enums work. Notice that our first enum value (Up) is initialized with 1. All the following members of the number enum are then auto incremented from this value (i.e. Down = 2, Left = 3, Right = 4). If we didn't initialize the first value with 1 the enum would start at 0 and then auto increment (i.e. Down = 1, Left = 2, Right = 3).

Using an enum:

We can access the values of the enum in the following manner:

Direction.Up;     // first the enum name, then the dot operator followed by the enum value
Direction.Down;

Notice that this way we are much more descriptive in the way we write our code. Enums basically prevent us from using magic numbers (numbers which represent some entity because the programmer has given a meaning to them in a certain context). Magic numbers are bad because of the following reasons:

  1. We need to think harder, we first need to translate the number to an entity before we can reason about our code.
  2. If we review our code after a long while, or other programmers review our code, they don't necessarily know what is meant with these numbers.

Return HTTP status code 201 in flask

You can read about it here.

return render_template('page.html'), 201

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

From your output:

no listening sockets available, shutting down

what basically means, that any port in which one apache is going to be listening is already being used by another application.

netstat -punta | grep LISTEN

Will give you a list of all the ports being used and the information needed to recognize which process is so you can kill stop or do whatever you want to do with it.

After doing a nmap of your ip I can see that

80/tcp    open     http

so I guess you sorted it out.

Excel telling me my blank cells aren't blank

I had a similar problem where scattered blank cells from an export from another application were still showing up in cell counts.

I managed to clear them by

  1. Selecting the columns/rows I wanted to clean, then doing
  2. "Find" [no text] and "Replace" [word of choice].
  3. Then I did "Find" [word of choice] and "Replace" with [no text].

It got rid of all hidden/phantom characters in those cells. Maybe this will work for you?

Environment variable to control java.io.tmpdir?

You could set your _JAVA_OPTIONS environmental variable. For example in bash this would do the trick:

export _JAVA_OPTIONS=-Djava.io.tmpdir=/new/tmp/dir

I put that into my bash login script and it seems to do the trick.

What languages are Windows, Mac OS X and Linux written in?

Linux: C. Some parts in assembly.

[...] It's mostly in C, but most people wouldn't call what I write C. It uses every conceivable feature of the 386 I could find, as it was also a project to teach me about the 386. As already mentioned, it uses a MMU, for both paging (not to disk yet) and segmentation. It's the segmentation that makes it REALLY 386 dependent (every task has a 64Mb segment for code & data - max 64 tasks in 4Gb. Anybody who needs more than 64Mb/task - tough cookies). [...] Some of my "C"-files (specifically mm.c) are almost as much assembler as C. [...] Unlike minix, I also happen to LIKE interrupts, so interrupts are handled without trying to hide the reason behind them. (Source)

Mac OS X: Cocoa mostly in Objective-C. Kernel written in C, some parts in assembly.

Mac OS X, at the kernel layer, is mostly an older, free operating system called BSD (specifically, it’s Darwin, a sort of hybrid of BSD, Mach, and a few other things)... almost entirely C, with a bit of assembler thrown in. (Source)

Much of Cocoa is implemented in Objective-C, an object-oriented language that is compiled to run at incredible speed, yet employes a truly dynamic runtime making it uniquely flexible. Because Objective-C is a superset of C, it is easy to mix C and even C++ into your Cocoa applications. (Source)

Windows: C, C++, C#. Some parts in assembler.

We use almost entirely C, C++, and C# for Windows. Some areas of code are hand tuned/hand written assembly. (Source)

Unix: C. Some parts in assembly. (Source)

getting JRE system library unbound error in build path

oh boy, this got resolved, I just had to name my Installed JRE appropriately. I had only the jdk installed and eclipse had taken the default jdk name, i renamed it to JavaSE-1.6 and voila it worked, though i had to redo everthing from the scratch.

correct way to use super (argument passing)

If you're going to have a lot of inheritence (that's the case here) I suggest you to pass all parameters using **kwargs, and then pop them right after you use them (unless you need them in upper classes).

class First(object):
    def __init__(self, *args, **kwargs):
        self.first_arg = kwargs.pop('first_arg')
        super(First, self).__init__(*args, **kwargs)

class Second(First):
    def __init__(self, *args, **kwargs):
        self.second_arg = kwargs.pop('second_arg')
        super(Second, self).__init__(*args, **kwargs)

class Third(Second):
    def __init__(self, *args, **kwargs):
        self.third_arg = kwargs.pop('third_arg')
        super(Third, self).__init__(*args, **kwargs)

This is the simplest way to solve those kind of problems.

third = Third(first_arg=1, second_arg=2, third_arg=3)

GridView Hide Column by code

There is a small change to happen, it will not come under rowdatabound, first all the rows should get bound, only then could we hide that. So it will be a separate method after the grid is dataBound.

Does Eclipse have line-wrap

As mentioned in the post by VonC on this same page. Eclipse now has this capability as of 06/2016 Neon.

Try this plugin Eclipse platform plugin

It looks like eclipse only has the ability to do it manually on its own and here are the commands. At that point you must reformat the highlighted text manually.

It's not terribly obvious how to control Eclipse line width and line wrapping in your Java source files. Here's how and where:

Comment width and line wrapping is set in Preferences->Java->Code Style->Formatter, then click on the Edit button and select the Comments tab. I like Line Width for Comments to be 120.

Code line wrapping is set nearby, in Preferences->Java->Code Style- >Formatter, then click on the Edit button and select the Line Wrapping tab. I like a line width of 120 and indent size of 4.

Indentation is set separately, in Preferences->Java->Code Style- >Formatter, then click on the Edit button and select the Indentation tab. I like an indent size of 4, consistent with the Line Wrapping indent setting.

As if that's not enough, you can also set printer margins, tab size, etc, in Preferences>General>Editors>Text Editors where I set the Displayed Tab Width to 4 and Print Margin Column to 120 or more.

You can also check the Show Print Margin box to get a faint vertical line at the printer margin column

How to get response body using HttpURLConnection, when code other than 2xx is returned?

If the response code isn't 200 or 2xx, use getErrorStream() instead of getInputStream().

How do I render a shadow?

All About margins

this works in Android, but did not test it in ios

import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { View, Platform } from 'react-native'
import EStyleSheet from 'react-native-extended-stylesheet'

const styles = EStyleSheet.create({
    wrapper: {
        margin: '-1.4rem'
    },
    shadow: {
        padding: '1.4rem',
        margin: '1.4rem',
        borderRadius: 4,
        borderWidth: 0,
        borderColor: 'transparent',
        ...Platform.select({
            ios: {
                shadowColor: 'rgba(0,0,0, 0.4)',
                shadowOffset: { height: 1, width: 1 },
                shadowOpacity: 0.7,
                shadowRadius: '1.4rem'
            },
            android: {
                elevation: '1.4rem'
            }
        })
    },
    container: {
        padding: 10,
        margin: '-1.4rem',
        borderRadius: 4,
        borderWidth: 0,
        borderColor: '#Fff',
        backgroundColor: '#fff'
    }
})

class ShadowWrapper extends PureComponent {
    static propTypes = {
        children: PropTypes.oneOfType([
            PropTypes.element,
            PropTypes.node,
            PropTypes.arrayOf(PropTypes.element)
        ]).isRequired
    }

    render () {
        return (
            View style={styles.wrapper}
                View style={styles.shadow}
                    View style={styles.container}
                        {this.props.children}
                    View
                View
            View
        )
    }
}

export default ShadowWrapper

How to implement a property in an interface

In the interface, you specify the property:

public interface IResourcePolicy
{
   string Version { get; set; }
}

In the implementing class, you need to implement it:

public class ResourcePolicy : IResourcePolicy
{
   public string Version { get; set; }
}

This looks similar, but it is something completely different. In the interface, there is no code. You just specify that there is a property with a getter and a setter, whatever they will do.

In the class, you actually implement them. The shortest way to do this is using this { get; set; } syntax. The compiler will create a field and generate the getter and setter implementation for it.

Displaying the build date

Add below to pre-build event command line:

echo %date% %time% > "$(ProjectDir)\Resources\BuildDate.txt"

Add this file as resource, now you have 'BuildDate' string in your resources.

After inserting the file into the Resource (as public text file), I accessed it via

string strCompTime = Properties.Resources.BuildDate;

To create resources, see How to create and use resources in .NET.

AngularJS $location not changing the path

I had a similar problem some days ago. In my case the problem was that I changed things with a 3rd party library (jQuery to be precise) and in this case even though calling functions and setting variable works Angular doesn't always recognize that there are changes thus it never digests.

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).

Try to use $scope.$apply() right after you have changed the location and called replace() to let Angular know that things have changed.

One line ftp server in python

Obligatory Twisted example:

twistd -n ftp

And probably useful:

twistd ftp --help

Usage: twistd [options] ftp [options].
WARNING: This FTP server is probably INSECURE do not use it.
Options:
  -p, --port=           set the port number [default: 2121]
  -r, --root=           define the root of the ftp-site. [default:
                    /usr/local/ftp]
  --userAnonymous=  Name of the anonymous user. [default: anonymous]
  --password-file=  username:password-style credentials database
  --version         
  --help            Display this help and exit.

HTML 5 Video "autoplay" not automatically starting in CHROME

Try this when i tried giving muted , check this demo in codpen

    <video width="320" height="240" controls autoplay muted id="videoId">
  <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>

script

function toggleMute() {

  var video=document.getElementById("videoId");

  if(video.muted){
    video.muted = false;
  } else {
    debugger;
    video.muted = true;
    video.play()
  }

}

$(document).ready(function(){
  setTimeout(toggleMute,3000);
})

edited attribute content

autoplay muted playsinline

https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

Specify sudo password for Ansible

A more savvy way to do this is to store your sudo password in a secure vault such as LastPass or KeePass and then pass it to ansible-playbook using the -e@ but instead of hardcoding the contents in an actual file, you can use the construct -e@<(...) to run a command in a sub-shell, and redirect its output (STDOUT) to a anonymous file descriptor, effectively feeding the password to the -e@<(..).

Example

$ ansible-playbook -i /tmp/hosts pb.yml \
   -e@<(echo "ansible_sudo_pass: $(lpass show folder1/item1 --password)")

The above is doing several things, let's break it down.

  • ansible-playbook -i /tmp/hosts pb.yml - obviously running a playbook via ansible-playbook
  • $(lpass show folder1/item1 --password)" - runs the LastPass CLI lpass and retrieves the password to use
  • echo "ansible_sudo_pass: ...password..." - takes the string 'ansible_sudo_pass: ' and combines it with the password supplied by lpass
  • -e@<(..) - puts the above together, and connects the subshell of <(...) as a file descriptor for ansible-playbook to consume.

Further improvements

If you'd rather not type that every time you can simply things like so. First create an alias in your .bashrc like so:

$ cat ~/.bashrc
alias asp='echo "ansible_sudo_pass: $(lpass show folder1/item1 --password)"'

Now you can run your playbook like this:

$ ansible-playbook -i /tmp/hosts pb.yml -e@<(asp)

References

How to display databases in Oracle 11g using SQL*Plus

You can think of a MySQL "database" as a schema/user in Oracle. If you have the privileges, you can query the DBA_USERS view to see the list of schemas:

SELECT * FROM DBA_USERS;

Laravel Update Query

$update = \DB::table('student') ->where('id', $data['id']) ->limit(1) ->update( [ 'name' => $data['name'], 'address' => $data['address'], 'email' => $data['email'], 'contactno' => $data['contactno'] ]); 

How to create a new object instance from a Type

Given this problem the Activator will work when there is a parameterless ctor. If this is a constraint consider using

System.Runtime.Serialization.FormatterServices.GetSafeUninitializedObject()

How to list all tags along with the full message in git?

Mark Longair's answer (using git show) is close to what is desired in the question. However, it also includes the commit pointed at by the tag, along with the full patch for that commit. Since the commit can be somewhat unrelated to the tag (it's only one commit that the tag is attempting to capture), this may be undesirable. I believe the following is a bit nicer:

for t in `git tag -l`; do git cat-file -p `git rev-parse $t`; done

Maintain/Save/Restore scroll position when returning to a ListView

Neither of the solutions offered here seemed to work for me. In my case, I have a ListView in a Fragment which I'm replacing in a FragmentTransaction, so a new Fragment instance is created each time the fragment is shown, which means that the ListView state can not be stored as a member of the Fragment.

Instead, I ended up storing the state in my custom Application class. The code below should give you an idea how this works:

public class MyApplication extends Application {
    public static HashMap<String, Parcelable> parcelableCache = new HashMap<>();


    /* ... code omitted for brevity ... */
}

 

public class MyFragment extends Fragment{
    private ListView mListView = null;
    private MyAdapter mAdapter = null;


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mAdapter = new MyAdapter(getActivity(), null, 0);
        mListView = ((ListView) view.findViewById(R.id.myListView));

        Parcelable listViewState = MyApplication.parcelableCache.get("my_listview_state");
        if( listViewState != null )
            mListView.onRestoreInstanceState(listViewState);
    }


    @Override
    public void onPause() {
        MyApplication.parcelableCache.put("my_listview_state", mListView.onSaveInstanceState());
        super.onPause();
    }

    /* ... code omitted for brevity ... */

}

The basic idea is that you store the state outside the fragment instance. If you don't like the idea of having a static field in your application class, I guess you could do it by implementing a fragment interface and storing the state in your activity.

Another solution would be to store it in SharedPreferences, but it gets a bit more complicated, and you would need to make sure you clear it on application launch unless you want the state to be persisted across app launches.

 

Also, to avoid the "scroll position not saved when first item is visible", you can display a dummy first item with 0px height. This can be achieved by overriding getView() in your adapter, like this:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if( position == 0 ) {
        View zeroHeightView = new View(parent.getContext());
        zeroHeightView.setLayoutParams(new ViewGroup.LayoutParams(0, 0));
        return zeroHeightView;
    }
    else
        return super.getView(position, convertView, parent);
}

Multiple IF AND statements excel

Consider that you have multiple "tests", e.g.,

  1. If E2 = 'in play' and F2 = 'closed', output 3
  2. If E2 = 'in play' and F2 = 'suspended', output 2
  3. Etc.

What you really need to do is put successive tests in the False argument. You're presently trying to separate each test by a comma, and that won't work.

Your first three tests can all be joined in one expression like:

=IF(E2="In Play",IF(F2="Closed",3,IF(F2="suspended",2,IF(F2="Null",1))))

Remembering that each successive test needs to be the nested FALSE argument of the preceding test, you can do this:

=IF(E2="In Play",IF(F2="Closed",3,IF(F2="suspended",2,IF(F2="Null",1))),IF(AND(E2="Pre-Play",F2="Null"),-1,IF(AND(E2="completed",F2="closed"),2,IF(AND(E2="suspended",F2="Null"),3,-2))))

How to get/generate the create statement for an existing hive table?

Describe Formatted/Extended will show the data definition of the table in hive

hive> describe Formatted dbname.tablename;

Sending mass email using PHP

You may consider using CRON for that kind of operation. Sending mass mail at once is certainly not good, it may be detected as spam, ddos, crash your server etc.

So CRON could be a great solution, send 100 mails at once, then wait a few minutes, next 100, etc.

"Cannot start compilation: the output path is not specified for module..."

If none of the above method worked then try this it worked for me.

Go to File > Project Structure> Project and then in Project Compiler Output click on the three dots and provide the path of your project name(name of the file) and then click on Apply and than on Ok.

Remove all of x axis labels in ggplot

You have to set to element_blank() in theme() elements you need to remove

ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

How to put an image in div with CSS?

you can do this:

<div class="picture1">&nbsp;</div>

and put this into your css file:

div.picture1 {
   width:100px; /*width of your image*/
   height:100px; /*height of your image*/
   background-image:url('yourimage.file');
   margin:0; /* If you want no margin */
   padding:0; /*if your want to padding */
}

otherwise, just use them as plain

Some projects cannot be imported because they already exist in the workspace error in Eclipse

In my case, I copied one of the projects (say 'Project1') from the workspace and pasted it to the same workspace. After that I modified the name of the pasted project (say to 'Project2'). I could not see it in the repository.

The main reason was .project file from the new project still had: <name>Project1</name> instead of <name>Project2</name>.

So, I did following things in order to get the issue fixed:

  1. Cut and paste Project2 outside the workspace
  2. Change .project file to have <name>Project2</name>
  3. Try importing Project2 again.

It worked for me.

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

If you want to restart Postgresql on Linux, then you have to use the following command.

/etc/init.d/postgresql restart

Git: Could not resolve host github.com error while cloning remote repository in git

Maybe it help someone somewhere, in my case (which was a private repo of git), host was suspended, so the issue was with my GitHub server and the administrator resolved it.

How to check if a key exists in Json Object and get its value

Try

private boolean hasKey(JSONObject jsonObject, String key) {
    return jsonObject != null && jsonObject.has(key);
}

  try {
        JSONObject jsonObject = new JSONObject(yourJson);
        if (hasKey(jsonObject, "labelData")) {
            JSONObject labelDataJson = jsonObject.getJSONObject("LabelData");
            if (hasKey(labelDataJson, "video")) {
                String video = labelDataJson.getString("video");
            }
        }
    } catch (JSONException e) {

    }

PHP ini file_get_contents external url

Complementing Aillyn's answer, you could use a function like the one below to mimic the behavior of file_get_contents:

function get_content($URL){
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_URL, $URL);
      $data = curl_exec($ch);
      curl_close($ch);
      return $data;
}

echo get_content('http://example.com');

Running PHP script from the command line

I was looking for a resolution to this issue in Windows, and it seems to be that if you don't have the environments vars ok, you need to put the complete directory. For eg. with a file in the same directory than PHP:

F:\myfolder\php\php.exe -f F:\myfolder\php\script.php

Get the index of the object inside an array, matching a condition

function findIndexByKeyValue(_array, key, value) {
    for (var i = 0; i < _array.length; i++) { 
        if (_array[i][key] == value) {
            return i;
        }
    }
    return -1;
}
var a = [
    {prop1:"abc",prop2:"qwe"},
    {prop1:"bnmb",prop2:"yutu"},
    {prop1:"zxvz",prop2:"qwrq"}];
var index = findIndexByKeyValue(a, 'prop2', 'yutu');
console.log(index);

Configuring angularjs with eclipse IDE

Download angular js from this link and add as new software in eclipse http://oss.opensagres.fr/angularjs-eclipse/0.6.0/

How to use android emulator for testing bluetooth application?

You can't. The emulator does not support Bluetooth, as mentioned in the SDK's docs and several other places. Android emulator does not have bluetooth capabilities".

You can only use real devices.

Emulator Limitations

The functional limitations of the emulator include:

  • No support for placing or receiving actual phone calls. However, You can simulate phone calls (placed and received) through the emulator console
  • No support for USB
  • No support for device-attached headphones
  • No support for determining SD card insert/eject
  • No support for WiFi, Bluetooth, NFC

Refer to the documentation

Syntax error due to using a reserved word as a table or column name in MySQL

The Problem

In MySQL, certain words like SELECT, INSERT, DELETE etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.

As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.

...

If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.

...

The identifier quote character is the backtick ("`"):

A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.

  • ADD
  • AND
  • BEFORE
  • BY
  • CALL
  • CASE
  • CONDITION
  • DELETE
  • DESC
  • DESCRIBE
  • FROM
  • GROUP
  • IN
  • INDEX
  • INSERT
  • INTERVAL
  • IS
  • KEY
  • LIKE
  • LIMIT
  • LONG
  • MATCH
  • NOT
  • OPTION
  • OR
  • ORDER
  • PARTITION
  • RANK
  • REFERENCES
  • SELECT
  • TABLE
  • TO
  • UPDATE
  • WHERE

The Solution

You have two options.

1. Don't use reserved words as identifiers

The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.

Doing this has a couple of advantages:

  • It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.

  • The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.

Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.

2. Use backticks

If renaming the table or column isn't possible, wrap the offending identifier in backticks (`) as described in the earlier quote from 10.2 Schema Object Names.

An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):

mysql> CREATE TABLE interval (begin INT, end INT);
ERROR 1064 (42000): You have an error in your SQL syntax.
near 'interval (begin INT, end INT)'

mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)

Similarly, the query from the question can be fixed by wrapping the keyword key in backticks, as shown below:

INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)";               ^   ^

Compare two files line by line and generate the difference in another file

Yet, no grep solution?

  • lines which are exist only in file2:

    grep -Fxvf file1 file2 > file3
    
  • lines which are exist only in file1:

    grep -Fxvf file2 file1 > file3
    
  • lines which are exist in both files:

    grep -Fxf file1 file2 > file3
    

Improving bulk insert performance in Entity framework

 Use : db.Set<tale>.AddRange(list); 
Ref :
TESTEntities db = new TESTEntities();
List<Person> persons = new List<Person> { 
new  Person{Name="p1",Place="palce"},
new  Person{Name="p2",Place="palce"},
new  Person{Name="p3",Place="palce"},
new  Person{Name="p4",Place="palce"},
new  Person{Name="p5",Place="palce"}
};
db.Set<Person>().AddRange(persons);
db.SaveChanges();

What does android:layout_weight mean?

layout_weight tells Android how to distribute your Views in a LinearLayout. Android then first calculates the total proportion required for all Views that have a weight specified and places each View according to what fraction of the screen it has specified it needs. In the following example, Android sees that the TextViews have a layout_weight of 0 (this is the default) and the EditTexts have a layout_weight of 2 each, while the Button has a weight of 1. So Android allocates 'just enough' space to display tvUsername and tvPassword and then divides the remainder of the screen width into 5 equal parts, two of which are allocated to etUsername, two to etPassword and the last part to bLogin:

<LinearLayout android:orientation="horizontal" ...>

    <TextView android:id="@+id/tvUsername" 
    android:text="Username" 
    android:layout_width="wrap_content" ... />

    <EditText android:id="@+id/etUsername"
    android:layout_width="0dp"
    android:layout_weight="2" ... />

    <TextView android:id="@+id/tvPassword"
    android:text="Password"
    android:layout_width="wrap_content" />

    <EditText android:id="@+id/etPassword"
    android:layout_width="0dp"
    android:layout_weight="2" ... />

    <Button android:id="@+id/bLogin"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:text="Login"... />

</LinearLayout>

It looks like:
landscape orientation and
portrait orientation

How to get time in milliseconds since the unix epoch in Javascript?

Date.now() returns a unix timestamp in milliseconds.

_x000D_
_x000D_
const now = Date.now(); // Unix timestamp in milliseconds_x000D_
console.log( now );
_x000D_
_x000D_
_x000D_

Prior to ECMAScript5 (I.E. Internet Explorer 8 and older) you needed to construct a Date object, from which there are several ways to get a unix timestamp in milliseconds:

_x000D_
_x000D_
console.log( +new Date );_x000D_
console.log( (new Date).getTime() );_x000D_
console.log( (new Date).valueOf() );
_x000D_
_x000D_
_x000D_

How to use CSS to surround a number with a circle?

the easiest way is using bootstrap and badge class

 <span class="badge">1</span>

Adding a month to a date in T SQL

select * from Reference where reference_dt = DateAdd(month,1,another_date_reference)

Type List vs type ArrayList in Java

List is an interface. It doesn't have methods. When you call a method on a List reference, it in fact calls the method of ArrayList in both cases.

And for the future you can change List obj = new ArrayList<> to List obj = new LinkList<> or other types which implement List interface.

How can I add C++11 support to Code::Blocks compiler?

The answer with screenshots (put the checkbox as in the second pic, then press OK):

enter image description here enter image description here

How to solve SyntaxError on autogenerated manage.py?

Same issue occurred to me,But what I did was,

Just Replaced:

python manage.py runserver

with

python3 manage.py runserver

in the terminal(macOsX). Because I am using Python version 3.x

What are the differences between a superkey and a candidate key?

One candidate key is chosen as the primary key. Other candidate keys are called alternate keys.

Sorting Characters Of A C++ String

You have to include sort function which is in algorithm header file which is a standard template library in c++.

Usage: std::sort(str.begin(), str.end());

#include <iostream>
#include <algorithm>  // this header is required for std::sort to work
int main()
{
    std::string s = "dacb";
    std::sort(s.begin(), s.end());
    std::cout << s << std::endl;

    return 0;
}

OUTPUT:

abcd

How to find specified name and its value in JSON-string from Java?

I agree that Google's Gson is clear and easy to use. But you should create a result class for getting an instance from JSON string. If you can't clarify the result class, use json-simple:

// import static org.hamcrest.CoreMatchers.is;
// import static org.junit.Assert.assertThat;
// import org.json.simple.JSONObject;
// import org.json.simple.JSONValue;
// import org.junit.Test;

@Test
public void json2Object() {
    // given
    String jsonString = "{\"name\" : \"John\",\"age\" : \"20\","
            + "\"address\" : \"some address\","
            + "\"someobject\" : {\"field\" : \"value\"}}";

    // when
    JSONObject object = (JSONObject) JSONValue.parse(jsonString);

    // then
    @SuppressWarnings("unchecked")
    Set<String> keySet = object.keySet();
    for (String key : keySet) {
        Object value = object.get(key);
        System.out.printf("%s=%s (%s)\n", key, value, value.getClass()
                .getSimpleName());
    }

    assertThat(object.get("age").toString(), is("20"));
}

Pros and cons of Gson and json-simple is pretty much like pros and cons of user-defined Java Object and Map. The object you define is clear for all fields (name and type), but less flexible than Map.

How to cast ArrayList<> from List<>

The second approach is clearly wrong if you want to cast. It instantiate a new ArrayList.

However the first approach should work just fine, if and only if getAllTasks return an ArrayList.

It is really needed for you to have an ArrayList ? isn't the List interface enough ? What you are doing can leads to Runtime Exception if the type isn't correct.

If getAllTasks() return an ArrayList you should change the return type in the class definition and then you won't need a cast and if it's returning something else, you can't cast to ArrayList.

How to convert a string to lower case in Bash?

If using v4, this is baked-in. If not, here is a simple, widely applicable solution. Other answers (and comments) on this thread were quite helpful in creating the code below.

# Like echo, but converts to lowercase
echolcase () {
    tr [:upper:] [:lower:] <<< "${*}"
}

# Takes one arg by reference (var name) and makes it lowercase
lcase () { 
    eval "${1}"=\'$(echo ${!1//\'/"'\''"} | tr [:upper:] [:lower:] )\'
}

Notes:

  • Doing: a="Hi All" and then: lcase a will do the same thing as: a=$( echolcase "Hi All" )
  • In the lcase function, using ${!1//\'/"'\''"} instead of ${!1} allows this to work even when the string has quotes.

How to set root password to null

It's not a good idea to edit mysql database directly.

I prefer the following steps:

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY ''; 
mysql> flush privileges;

Where does flask look for image files?

It took me a while to figure this out too. url_for in Flask looks for endpoints that you specified in the routes.py script.

So if you have a decorator in your routes.py file like @blah.route('/folder.subfolder') then Flask will recognize the command {{ url_for('folder.subfolder') , filename = "some_image.jpg" }} . The 'folder.subfolder' argument sends it to a Flask endpoint it recognizes.

However let us say that you stored your image file, some_image.jpg, in your subfolder, BUT did not specify this subfolder as a route endpoint in your flask routes.py, your route decorator looks like @blah.routes('/folder'). You then have to ask for your image file this way: {{ url_for('folder'), filename = 'subfolder/some_image.jpg' }}

I.E. you tell Flask to go to the endpoint it knows, "folder", then direct it from there by putting the subdirectory path in the filename argument.

How to embed YouTube videos in PHP?

You can simply create a php input form for Varchar date,give it a varchar length of lets say 300. Then ask the users to copy and paste the Embed code.When you view the records, you will view the streamed video.

Should Jquery code go in header or footer?

Most jquery code executes on document ready, which doesn't happen until the end of the page anyway. Furthermore, page rendering can be delayed by javascript parsing/execution, so it's best practice to put all javascript at the bottom of the page.

Inline comments for Bash?

Most commands allow args to come in any order. Just move the commented flags to the end of the line:

ls -l -a /etc # -F is turned off

Then to turn it back on, just uncomment and remove the text:

ls -l -a /etc -F

How to check if any fields in a form are empty in php

Specify POST method in form
<form name="registrationform" action="register.php" method="post">


your form code

</form>

In Windows cmd, how do I prompt for user input and use the result in another command?

There is no documented /prompt parameter for SETX as there is for SET.

If you need to prompt for an environment variable that will survive reboots, you can use SETX to store it.

A variable created by SETX won't be usable until you restart the command prompt. Neatly, however, you can SETX a variable that has already been SET, even if it has the same name.

This works for me in Windows 8.1 Pro:

set /p UserInfo= "What is your name?  "
setx UserInfo "%UserInfo%"

(The quotation marks around the existing variable are necessary.)

This procedure allows you to use the temporary SET-created variable during the current session and will allow you to reuse the SETX-created variable upon reboot of the computer or restart of the CMD prompt.

(Edited to format code paragraphs properly.)

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

Red lines under the ViewBag was my headache for 3 month ). Just remove the Microsoft.CSharp reference from project and then add it again.

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

How to compare two Carbon Timestamps?

First, convert the timestamp using the built-in eloquent functionality, as described in this answer.

Then you can just use Carbon's min() or max() function for comparison. For example:

$dt1 = Carbon::create(2012, 1, 1, 0, 0, 0); $dt2 = Carbon::create(2014, 1, 30, 0, 0, 0); echo $dt1->min($dt2);

This will echo the lesser of the two dates, which in this case is $dt1.

See http://carbon.nesbot.com/docs/

Check if XML Element exists

A little bit late, but if it helps, this works for me...

XmlNodeList NodoEstudios = DocumentoXML.SelectNodes("//ALUMNOS/ALUMNO[@id=\"" + Id + "\"]/estudios");

string Proyecto = "";

foreach(XmlElement ElementoProyecto in NodoEstudios)
{
    XmlNodeList EleProyecto = ElementoProyecto.GetElementsByTagName("proyecto");
    Proyecto = (EleProyecto[0] == null)?"": EleProyecto[0].InnerText;
}

Skipping Incompatible Libraries at compile

Normally, that is not an error per se; it is a warning that the first file it found that matches the -lPI-Http argument to the compiler/linker is not valid. The error occurs when no other library can be found with the right content.

So, you need to look to see whether /dvlpmnt/libPI-Http.a is a library of 32-bit object files or of 64-bit object files - it will likely be 64-bit if you are compiling with the -m32 option. Then you need to establish whether there is an alternative libPI-Http.a or libPI-Http.so file somewhere else that is 32-bit. If so, ensure that the directory that contains it is listed in a -L/some/where argument to the linker. If not, then you will need to obtain or build a 32-bit version of the library from somewhere.

To establish what is in that library, you may need to do:

mkdir junk
cd junk
ar x /dvlpmnt/libPI-Http.a
file *.o
cd ..
rm -fr junk

The 'file' step tells you what type of object files are in the archive. The rest just makes sure you don't make a mess that can't be easily cleaned up.

How to insert a line break before an element using CSS

Add a margin-top:20px; to #restart. Or whatever size gap you feel is appropriate. If it's an inline-element you'll have to add display:block or display:inline-block although I don't think inline-block works on older versions of IE.

What's the best way to store Phone number in Django models

You might actually look into the internationally standardized format E.164, recommended by Twilio for example (who have a service and an API for sending SMS or phone-calls via REST requests).

This is likely to be the most universal way to store phone numbers, in particular if you have international numbers work with.

1. Phone by PhoneNumberField

You can use phonenumber_field library. It is port of Google's libphonenumber library, which powers Android's phone number handling https://github.com/stefanfoulis/django-phonenumber-field

In model:

from phonenumber_field.modelfields import PhoneNumberField

class Client(models.Model, Importable):
    phone = PhoneNumberField(null=False, blank=False, unique=True)

In form:

from phonenumber_field.formfields import PhoneNumberField
class ClientForm(forms.Form):
    phone = PhoneNumberField()

Get phone as string from object field:

    client.phone.as_e164 

Normolize phone string (for tests and other staff):

    from phonenumber_field.phonenumber import PhoneNumber
    phone = PhoneNumber.from_string(phone_number=raw_phone, region='RU').as_e164

2. Phone by regexp

One note for your model: E.164 numbers have a max character length of 15.

To validate, you can employ some combination of formatting and then attempting to contact the number immediately to verify.

I believe I used something like the following on my django project:

class ReceiverForm(forms.ModelForm):
    phone_number = forms.RegexField(regex=r'^\+?1?\d{9,15}$', 
                                error_message = ("Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."))

EDIT

It appears that this post has been useful to some folks, and it seems worth it to integrate the comment below into a more full-fledged answer. As per jpotter6, you can do something like the following on your models as well:

models.py:

from django.core.validators import RegexValidator

class PhoneModel(models.Model):
    ...
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list

How do I use the CONCAT function in SQL Server 2008 R2?

Just for completeness - in SQL 2008 you would use the plus + operator to perform string concatenation.

Take a look at the MSDN reference with sample code. Starting with SQL 2012, you may wish to use the new CONCAT function.

Best practices for SQL varchar column length

Whenever I set up a new SQL table I feel the same way about 2^n being more "even"... but to sum up the answers here, there is no significant impact on storage space simply by defining varchar(2^n) or even varchar(MAX).

That said, you should still anticipate the potential implications on storage and performance when setting a high varchar() limit. For example, let's say you create a varchar(MAX) column to hold product descriptions with full-text indexing. If 99% of descriptions are only 500 characters long, and then suddenly you get somebody who replaces said descriptions with wikipedia articles, you may notice unanticipated significant storage and performance hits.

Another thing to consider from Bill Karwin:

There's one possible performance impact: in MySQL, temporary tables and MEMORY tables store a VARCHAR column as a fixed-length column, padded out to its maximum length. If you design VARCHAR columns much larger than the greatest size you need, you will consume more memory than you have to. This affects cache efficiency, sorting speed, etc.

Basically, just come up with reasonable business constraints and error on a slightly larger size. As @onedaywhen pointed out, family names in UK are usually between 1-35 characters. If you decide to make it varchar(64), you're not really going to hurt anything... unless you're storing this guy's family name that's said to be up to 666 characters long. In that case, maybe varchar(1028) makes more sense.

And in case it's helpful, here's what varchar 2^5 through 2^10 might look like if filled:

varchar(32)     Lorem ipsum dolor sit amet amet.

varchar(64)     Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie

varchar(128)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas

varchar(256)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt

varchar(512)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt
                dolor tellus, sit amet porta neque varius vitae. Seduse molestie
                lacus id lacinia tempus. Vestibulum accumsan facilisis lorem, et
                mollis diam pretium gravida. In facilisis vitae tortor id vulput
                ate. Proin ornare arcu in sollicitudin pharetra. Crasti molestie

varchar(1024)   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt
                dolor tellus, sit amet porta neque varius vitae. Seduse molestie
                lacus id lacinia tempus. Vestibulum accumsan facilisis lorem, et
                mollis diam pretium gravida. In facilisis vitae tortor id vulput
                ate. Proin ornare arcu in sollicitudin pharetra. Crasti molestie
                dapibus leo lobortis eleifend. Vivamus vitae diam turpis. Vivamu
                nec tristique magna, vel tincidunt diam. Maecenas elementum semi
                quam. In ut est porttitor, sagittis nulla id, fermentum turpist.
                Curabitur pretium nibh a imperdiet cursus. Sed at vulputate este
                proin fermentum pretium justo, ac malesuada eros et Pellentesque
                vulputate hendrerit molestie. Aenean imperdiet a enim at finibus
                fusce ut ullamcorper risus, a cursus massa. Nunc non dapibus vel
                Lorem ipsum dolor sit amet, consectetur Praesent ut ultrices sit

How can I get all a form's values that would be submitted without submitting

In straight Javascript you could do something similar to the following:

var kvpairs = [];
var form = // get the form somehow
for ( var i = 0; i < form.elements.length; i++ ) {
   var e = form.elements[i];
   kvpairs.push(encodeURIComponent(e.name) + "=" + encodeURIComponent(e.value));
}
var queryString = kvpairs.join("&");

In short, this creates a list of key-value pairs (name=value) which is then joined together using "&" as a delimiter.

How to vertically align into the center of the content of a div with defined width/height?

This could also be done using display: flex with only a few lines of code. Here is an example:

.container {
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
}

Live Demo

How to squash commits in git after they have been pushed?

For squashing two commits, one of which was already pushed, on a single branch the following worked:

git rebase -i HEAD~2
    [ pick     older-commit  ]
    [ squash   newest-commit ]
git push --force

By default, this will include the commit message of the newest commit as a comment on the older commit.

How to easily resize/optimize an image size with iOS?

The above methods work well for small images, but when you try to resize a very large image, you will quickly run out of memory and crash the app. A much better way is to use CGImageSourceCreateThumbnailAtIndexto resize the image without completely decoding it first.

If you have the path to the image you want to resize, you can use this:

- (void)resizeImageAtPath:(NSString *)imagePath {
    // Create the image source (from path)
    CGImageSourceRef src = CGImageSourceCreateWithURL((__bridge CFURLRef) [NSURL fileURLWithPath:imagePath], NULL);

    // To create image source from UIImage, use this
    // NSData* pngData =  UIImagePNGRepresentation(image);
    // CGImageSourceRef src = CGImageSourceCreateWithData((CFDataRef)pngData, NULL);

    // Create thumbnail options
    CFDictionaryRef options = (__bridge CFDictionaryRef) @{
            (id) kCGImageSourceCreateThumbnailWithTransform : @YES,
            (id) kCGImageSourceCreateThumbnailFromImageAlways : @YES,
            (id) kCGImageSourceThumbnailMaxPixelSize : @(640)
    };
    // Generate the thumbnail
    CGImageRef thumbnail = CGImageSourceCreateThumbnailAtIndex(src, 0, options); 
    CFRelease(src);
    // Write the thumbnail at path
    CGImageWriteToFile(thumbnail, imagePath);
}

More details here.

MVVM: Tutorial from start to finish?

I read Josh Smith's article and found it very difficult. Once understood, I wrote a very simple one that should get you really started on it. Get it here.

How to set delay in vbscript

Here's another alternative:

Sub subSleep(strSeconds) ' subSleep(2)
    Dim objShell
    Dim strCmd
    set objShell = CreateObject("wscript.Shell")
    'objShell.Run cmdline,1,False

    strCmd = "%COMSPEC% /c ping -n " & strSeconds & " 127.0.0.1>nul"     
    objShell.Run strCmd,0,1 
End Sub 

How to analyse the heap dump using jmap in java

If you just run jmap -histo:live or jmap -histo, it outputs the contents on the console!

How can I convert a hex string to a byte array?

I did some research and found out that byte.Parse is even slower than Convert.ToByte. The fastest conversion I could come up with uses approximately 15 ticks per byte.

    public static byte[] StringToByteArrayFastest(string hex) {
        if (hex.Length % 2 == 1)
            throw new Exception("The binary key cannot have an odd number of digits");

        byte[] arr = new byte[hex.Length >> 1];

        for (int i = 0; i < hex.Length >> 1; ++i)
        {
            arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
        }

        return arr;
    }

    public static int GetHexVal(char hex) {
        int val = (int)hex;
        //For uppercase A-F letters:
        //return val - (val < 58 ? 48 : 55);
        //For lowercase a-f letters:
        //return val - (val < 58 ? 48 : 87);
        //Or the two combined, but a bit slower:
        return val - (val < 58 ? 48 : (val < 97 ? 55 : 87));
    }

// also works on .NET Micro Framework where (in SDK4.3) byte.Parse(string) only permits integer formats.

"Error 404 Not Found" in Magento Admin Login Page

Finally, I found the solution to my problem.

I looked into the Magento system log file (var/log/system.log). There I saw the exact error.

The error is as below:-

Recoverable Error: Argument 1 passed to Mage_Core_Model_Store::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 555 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store.php on line 285

Recoverable Error: Argument 1 passed to Mage_Core_Model_Store_Group::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 575 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store\Group.php on line 227

Actually, I had this error before. But, error display message like Error: 404 Not Found was new to me.

The reason for this error is that store_id and website_id for admin should be set to 0 (zero). But, when you import database to new server, somehow these values are not set to 0.

Open PhpMyAdmin and run the following query in your database:-

SET FOREIGN_KEY_CHECKS=0;
UPDATE `core_store` SET store_id = 0 WHERE code='admin';
UPDATE `core_store_group` SET group_id = 0 WHERE name='Default';
UPDATE `core_website` SET website_id = 0 WHERE code='admin';
UPDATE `customer_group` SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN';
SET FOREIGN_KEY_CHECKS=1;

I have written about this problem and solution over here:-

Magento: Solution to "Error: 404 Not Found" in Admin Login Page

NSString property: copy or retain?

Surely putting 'copy' on a property declaration flies in the face of using an object-oriented environment where objects on the heap are passed by reference - one of the benefits you get here is that, when changing an object, all references to that object see the latest changes. A lot of languages supply 'ref' or similar keywords to allow value types (i.e. structures on the stack) to benefit from the same behaviour. Personally, I'd use copy sparingly, and if I felt that a property value should be protected from changes made to the object it was assigned from, I could call that object's copy method during the assignment, e.g.:

p.name = [someName copy];

Of course, when designing the object that contains that property, only you will know whether the design benefits from a pattern where assignments take copies - Cocoawithlove.com has the following to say:

"You should use a copy accessor when the setter parameter may be mutable but you can't have the internal state of a property changing without warning" - so the judgement as to whether you can stand the value to change unexpectedly is all your own. Imagine this scenario:

//person object has details of an individual you're assigning to a contact list.

Contact *contact = [[[Contact alloc] init] autorelease];
contact.name = person.name;

//person changes name
[[person name] setString:@"new name"];
//now both person.name and contact.name are in sync.

In this case, without using copy, our contact object takes the new value automatically; if we did use it, though, we'd have to manually make sure that changes were detected and synced. In this case, retain semantics might be desirable; in another, copy might be more appropriate.

How can I handle the warning of file_get_contents() function in PHP?

Change the file php.ini

allow_url_fopen = On

allow_url_include = On

Timer function to provide time in nano seconds using C++

For C++11, here is a simple wrapper:

#include <iostream>
#include <chrono>

class Timer
{
public:
    Timer() : beg_(clock_::now()) {}
    void reset() { beg_ = clock_::now(); }
    double elapsed() const {
        return std::chrono::duration_cast<second_>
            (clock_::now() - beg_).count(); }

private:
    typedef std::chrono::high_resolution_clock clock_;
    typedef std::chrono::duration<double, std::ratio<1> > second_;
    std::chrono::time_point<clock_> beg_;
};

Or for C++03 on *nix,

class Timer
{
public:
    Timer() { clock_gettime(CLOCK_REALTIME, &beg_); }

    double elapsed() {
        clock_gettime(CLOCK_REALTIME, &end_);
        return end_.tv_sec - beg_.tv_sec +
            (end_.tv_nsec - beg_.tv_nsec) / 1000000000.;
    }

    void reset() { clock_gettime(CLOCK_REALTIME, &beg_); }

private:
    timespec beg_, end_;
};

Example of usage:

int main()
{
    Timer tmr;
    double t = tmr.elapsed();
    std::cout << t << std::endl;

    tmr.reset();
    t = tmr.elapsed();
    std::cout << t << std::endl;
    return 0;
}

From https://gist.github.com/gongzhitaao/7062087

Want to upgrade project from Angular v5 to Angular v6

Angular 6 has just been released.

https://blog.angular.io/version-6-of-angular-now-available-cc56b0efa7a4

Here is what worked for one of my smaller projects

  1. npm install -g @angular/cli
  2. npm install @angular/cli
  3. ng update @angular/cli --migrate-only --from=1.7.0
  4. ng update @angular/core
  5. npm install rxjs-compat
  6. ng serve

You might need to update your run scripts in package.json For eg. if you use flags like "app" and "environment" These have been updated to "project" and "configuration" respectively.

Refer https://update.angular.io/ for more detailed guide.

Eclipse Intellisense?

You don't have to press CTRL * space but maybe the delay is too big or you don't like the trigger (default is '.'). Go to

Window -> Preferences -> Java/Editor/Content Assist

And change the settings under Auto Activation to your likings.

If this does not work for windows users then see this answer.

how to check which version of nltk, scikit learn installed?

you may check from a python notebook cell as follows

!pip install --upgrade nltk     # needed if nltk is not already installed
import nltk      
print('The nltk version is {}.'.format(nltk.__version__))
print('The nltk version is '+ str(nltk.__version__))

and

#!pip install --upgrade sklearn      # needed if sklearn is not already installed
import sklearn
print('The scikit-learn version is {}.'.format(sklearn.__version__))
print('The scikit-learn version is '+ str(nltk.__version__))

A beginner's guide to SQL database design

I started out with this article

http://en.tekstenuitleg.net/articles/software/database-design-tutorial/intro.html

It's pretty concise compared to reading an entire book and it explains the basics of database design (normalization, types of relationships) very well.

Python: how can I check whether an object is of type datetime.date?

right way is

import datetime
isinstance(x, datetime.date)

When I try this on my machine it works fine. You need to look into why datetime.date is not a class. Are you perhaps masking it with something else? or not referencing it correctly for your import?

Clicking a button within a form causes page refresh

I also had the same problem, but gladelly I fixed this by changing the type like from type="submit" to type="button" and it worked.

How To Set Up GUI On Amazon EC2 Ubuntu server

For LXDE/Lubuntu


1. connect to your instance (local forwarding port 5901)

ssh -L 5901:localhost:5901 -i "xxx.pem" [email protected]

2. Install packages

sudo apt update && sudo apt upgrade
sudo apt-get install xorg lxde vnc4server lubuntu-desktop

3. Create /etc/lightdm/lightdm.conf

sudo nano /etc/lightdm/lightdm.conf

4. Copy and paste the following into the lightdm.conf and save

[SeatDefaults]
allow-guest=false
user-session=LXDE
#user-session=Lubuntu

5. setup vncserver (you will be asked to create a password for the vncserver)

vncserver
sudo echo "lxpanel & /usr/bin/lxsession -s LXDE &" >> ~/.vnc/xstartup

6. Restart your instance and reconnect

sudo reboot
ssh -L 5901:localhost:5901 -i "xxx.pem" [email protected]

7. Start vncserver

vncserver -geometry 1280x800

8. In your Remote Desktop Client (e.g. Remmina) set Server to localhost:5901 and protocol to VNC

Create a directory if it does not exist and then create the files in that directory as well

This code checks for the existence of the directory first and creates it if not, and creates the file afterwards. Please note that I couldn't verify some of your method calls as I don't have your complete code, so I'm assuming the calls to things like getTimeStamp() and getClassName() will work. You should also do something with the possible IOException that can be thrown when using any of the java.io.* classes - either your function that writes the files should throw this exception (and it be handled elsewhere), or you should do it in the method directly. Also, I assumed that id is of type String - I don't know as your code doesn't explicitly define it. If it is something else like an int, you should probably cast it to a String before using it in the fileName as I have done here.

Also, I replaced your append calls with concat or + as I saw appropriate.

public void writeFile(String value){
    String PATH = "/remote/dir/server/";
    String directoryName = PATH.concat(this.getClassName());
    String fileName = id + getTimeStamp() + ".txt";

    File directory = new File(directoryName);
    if (! directory.exists()){
        directory.mkdir();
        // If you require it to make the entire directory path including parents,
        // use directory.mkdirs(); here instead.
    }

    File file = new File(directoryName + "/" + fileName);
    try{
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(value);
        bw.close();
    }
    catch (IOException e){
        e.printStackTrace();
        System.exit(-1);
    }
}

You should probably not use bare path names like this if you want to run the code on Microsoft Windows - I'm not sure what it will do with the / in the filenames. For full portability, you should probably use something like File.separator to construct your paths.

Edit: According to a comment by JosefScript below, it's not necessary to test for directory existence. The directory.mkdir() call will return true if it created a directory, and false if it didn't, including the case when the directory already existed.

Avoiding "resource is out of sync with the filesystem"

For the new Indigo version, the Preferences change to "Refresh on access", and with a detail explanation : Automatically refresh external workspace changes on access via the workspace.

As “resource is out of sync with the filesystem” this problem happens when I use external workspace, so after I select this option, problem solved.

Are 2 dimensional Lists possible in c#?

I used:

List<List<String>> List1 = new List<List<String>>
var List<int> = new List<int>();
List.add("Test");
List.add("Test2");
List1.add(List);
var List<int> = new List<int>();
List.add("Test3");
List1.add(List);

that equals:

List1
(
[0] => List2 // List1[0][x]
    (
        [0] => Test  // List[0][0] etc.
        [1] => Test2

    )
[1] => List2
    (
        [0] => Test3