Programs & Examples On #Downloadfile

How do I install a Python package with a .whl file?

I would be suggesting you the exact way how to install .whl file. Initially I faced many issues but then I solved it, Here is my trick to install .whl files.

Follow The Steps properly in order to get a module imported

  1. Make sure your .whl file is kept in the python 2.7/3.6/3.7/.. folder. Initially when you download the .whl file the file is kept in downloaded folder, my suggestion is to change the folder. It makes it easier to install the file.
  2. Open command prompt and open the folder where you have kept the file by entering

cd c:\python 3.7

3.Now, enter the command written below

>py -3.7(version name) -m pip install (file name).whl
  1. Click enter and make sure you enter the version you are currently using with correct file name.

  2. Once you press enter, wait for few minutes and the file will be installed and you will be able to import the particular module.

  3. In order to check if the module is installed successfully, import the module in idle and check it.

Thank you:)

How to download a file from a URL in C#?

Also you can use DownloadFileAsync method in WebClient class. It downloads to a local file the resource with the specified URI. Also this method does not block the calling thread.

Sample:

    webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");

For more information:

http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/

Referring to a Column Alias in a WHERE Clause

The most effective way to do it without repeating your code is use of HAVING instead of WHERE

SELECT logcount, logUserID, maxlogtm
   , DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary
HAVING daysdiff > 120

How to [recursively] Zip a directory in PHP?

Try this link <-- MORE SOURCE CODE HERE

/** Include the Pear Library for Zip */
include ('Archive/Zip.php');

/** Create a Zipping Object...
* Name of zip file to be created..
* You can specify the path too */
$obj = new Archive_Zip('test.zip');
/**
* create a file array of Files to be Added in Zip
*/
$files = array('black.gif',
'blue.gif',
);

/**
* creating zip file..if success do something else do something...
* if Error in file creation ..it is either due to permission problem (Solution: give 777 to that folder)
* Or Corruption of File Problem..
*/

if ($obj->create($files)) {
// echo 'Created successfully!';
} else {
//echo 'Error in file creation';
}

?>; // We'll be outputting a ZIP
header('Content-type: application/zip');

// It will be called test.zip
header('Content-Disposition: attachment; filename="test.zip"');

//read a file and send
readfile('test.zip');
?>;

How to get a enum value from string in C#?

var value = (uint)Enum.Parse(typeof(basekey), "HKEY_LOCAL_MACHINE", true);

This code snippet illustrates obtaining an enum value from a string. To convert from a string, you need to use the static Enum.Parse() method, which takes 3 parameters. The first is the type of enum you want to consider. The syntax is the keyword typeof() followed by the name of the enum class in brackets. The second parameter is the string to be converted, and the third parameter is a bool indicating whether you should ignore case while doing the conversion.

Finally, note that Enum.Parse() actually returns an object reference, that means you need to explicitly convert this to the required enum type(string,int etc).

Thank you.

Read/write files within a Linux kernel module

Since version 4.14 of Linux kernel, vfs_read and vfs_write functions are no longer exported for use in modules. Instead, functions exclusively for kernel's file access are provided:

# Read the file from the kernel space.
ssize_t kernel_read(struct file *file, void *buf, size_t count, loff_t *pos);

# Write the file from the kernel space.
ssize_t kernel_write(struct file *file, const void *buf, size_t count,
            loff_t *pos);

Also, filp_open no longer accepts user-space string, so it can be used for kernel access directly (without dance with set_fs).

How can I check if char* variable points to empty string?

My preferred method:

if (*ptr == 0) // empty string

Probably more common:

if (strlen(ptr) == 0) // empty string

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

I didn't have the NuGet Package Provider, you can check running Get-PackageProvider:

PS C:\WINDOWS\system32> Get-PackageProvider 

Name                     Version          DynamicOptions                                                                                                                 
----                     -------          --------------                                                                                                                 
msi                      3.0.0.0          AdditionalArguments                                                                                                            
msu                      3.0.0.0                                                                                                                                         
NuGet  <NOW INSTALLED>   2.8.5.208        Destination, ...                             

The solution was installing it by running this command:

Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force

If that fails with the error below you can copy/paste the NuGet folder from another PC (admin needed): C:\Program Files\PackageManagement\ProviderAssemblies\NuGet:

WARNING: Unable to download from URI 'https://onegetcdn.azureedge.net/providers/Microsoft.PackageManagement.NuGetProvider-2.8.5.208.dll' to ''.
WARNING: Failed to bootstrap provider 'https://onegetcdn.azureedge.net/providers/nuget-2.8.5.208.package.swidtag'.
WARNING: Failed to bootstrap provider 'nuget'.
WARNING: The specified PackageManagement provider 'NuGet' is not available.
PackageManagement\Install-PackageProvider : Unable to download from URI 
'https://onegetcdn.azureedge.net/providers/Microsoft.PackageManagement.NuGetProvider-2.8.5.208.dll' to ''.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\PSModule.psm1:6463 char:21
+             $null = PackageManagement\Install-PackageProvider -Name $script:NuGe ...

How to pass a value to razor variable from javascript variable?

here is my solution that works:

in my form i use:

@using (Html.BeginForm("RegisterOrder", "Account", FormMethod.Post, new { @class = "form", role = "form" }))
  {

   @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })

   @Html.HiddenFor(m => m.quantity, new { id = "quantity", Value = 0 })

  }

in my file.js I get the quantity from a GET request and pass the variable as follows to the form:

    $http({
        method: 'Get',
        url: "https://xxxxxxx.azurewebsites.net/api/quantity/" + usr
    })
        .success(function (data){

            setQuantity(data.number);

            function setQuantity(number) {
                $('#quantity').val(number);
            }

        });

Serialize an object to XML

The following function can be copied to any object to add an XML save function using the System.Xml namespace.

/// <summary>
/// Saves to an xml file
/// </summary>
/// <param name="FileName">File path of the new xml file</param>
public void Save(string FileName)
{
    using (var writer = new System.IO.StreamWriter(FileName))
    {
        var serializer = new XmlSerializer(this.GetType());
        serializer.Serialize(writer, this);
        writer.Flush();
    }
}

To create the object from the saved file, add the following function and replace [ObjectType] with the object type to be created.

/// <summary>
/// Load an object from an xml file
/// </summary>
/// <param name="FileName">Xml file name</param>
/// <returns>The object created from the xml file</returns>
public static [ObjectType] Load(string FileName)
{
    using (var stream = System.IO.File.OpenRead(FileName))
    {
        var serializer = new XmlSerializer(typeof([ObjectType]));
        return serializer.Deserialize(stream) as [ObjectType];
    }
}

How do I load external fonts into an HTML document?

Regarding Jay Stevens answer: "The fonts available to use in an HTML file have to be present on the user's machine and accessible from the web browser, so unless you want to distribute the fonts to the user's machine via a separate external process, it can't be done." That's true.

But there is another way using javascript / canvas / flash - very good solution gives cufon: http://cufon.shoqolate.com/generate/ library that generates a very easy to use external fonts methods.

What's the best way to dedupe a table?

Using analytic function row_number:

WITH CTE (col1, col2, dupcnt)
AS
(
SELECT col1, col2,
ROW_NUMBER() OVER (PARTITION BY col1, col2 ORDER BY col1) AS dupcnt
FROM Youtable
)
DELETE
FROM CTE
WHERE dupcnt > 1
GO                                                                 

Format date and Subtract days using Moment.js

In angularjs moment="^1.3.0"

moment('15-01-1979', 'DD-MM-YYYY').subtract(1,'days').format(); //14-01-1979
or
moment('15-01-1979', 'DD-MM-YYYY').add(1,'days').format(); //16-01-1979
``



How can I brew link a specific version?

I asked in #machomebrew and learned that you can switch between versions using brew switch.

$ brew switch libfoo mycopy 

to get version mycopy of libfoo.

PHP error: "The zip extension and unzip command are both missing, skipping."

I'm Using Ubuntu and with the following command worked

apt-get install --yes zip unzip

What is process.env.PORT in Node.js?

  • if you run node index.js ,Node will use 3000

  • If you run PORT=4444 node index.js, Node will use process.env.PORT which equals to 4444 in this example. Run with sudo for ports below 1024.

Full Screen DialogFragment in Android

As far as the Android API got updated, the suggested method to show a full screen dialog is the following:

FragmentTransaction transaction = this.mFragmentManager.beginTransaction();
// For a little polish, specify a transition animation
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
// To make it fullscreen, use the 'content' root view as the container
// for the fragment, which is always the root view for the activity
transaction.add(android.R.id.content, this.mFragmentToShow).commit();

otherwise, if you don't want it to be shown fullscreen you can do this way:

this.mFragmentToShow.show(this.mFragmentManager, LOGTAG);

Hope it helps.

EDIT

Be aware that the solution I gave works but has got a weakness that sometimes could be troublesome. Adding the DialogFragment to the android.R.id.content container won't allow you to handle the DialogFragment#setCancelable() feature correctly and could lead to unexpected behaviors when adding the DialogFragment itself to the back stack as well.

So I'd suggested you to simple change the style of your DialogFragment in the onCreate method as follow:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Translucent_NoTitleBar);
}

Hope it helps.

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

Scenario #1: You accidentially re-deployed from the command line while tomcat was already running.

Short Answer: Stop Tomcat, delete target folder, mvn package, then re-deploy


Scenario #2: request.getRequestDispatcher("MIS_SPELLED_FILE_NAME.jsp")

Short Answer: Check file name spelling, make sure case is correct.


Scenario #3: Class Not Found Exceptions (Answer put here because: Question# 17982240 ) (java.lang.ClassNotFoundException for servlet in tomcat with eclipse ) (was marked as duplicate and directed me here )

Short Answer #3.1: web.xml has wrong package path in servlet-class tag.

Short Answer #3.2: java file has wrong import statement.


Below is further details for Scenario #1:


1: Stop Tomcat

  • Option 1: Via CTRL+C in terminal.
  • Option 2: (terminal closed while tomcat still running)
  • ------------ 2.1: press:Windows+R --> type:"services.msc"
  • ------------ 2.2: Find "Apache Tomcat #.# Tomcat#" in Name column of list.
  • ------------ 2.3: Right Click --> "stop"

2: Delete the "target" folder. (mvn clean will not help you here)

3: mvn package

4: YOUR_DEPLOYMENT_COMMAND_HERE

(Mine: java -jar target/dependency/webapp-runner.jar --port 5190 target/*.war )

Full Back Story:


Accidentially opened a new git-bash window and tried to deploy a .war file for my heroku project via:

java -jar target/dependency/webapp-runner.jar --port 5190 target/*.war

After a failure to deploy, I realized I had two git-bash windows open, and had not used CTLR+C to stop the previous deployment.

I was met with:

HTTP Status 404 – Not Found Type Status Report

Message /if-student-test.jsp

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

Apache Tomcat/8.5.31

Below is further details for Scenario #3:


SCENARIO 3.1: The servlet-class package path is wrong in your web.xml file.

It should MATCH the package statement at top of your java servlet class.

File: my_stuff/MyClass.java:

   package my_stuff;

File: PRJ_ROOT/src/main/webapp/WEB-INF/web.xml

   <servlet-class>
   my_stuff.MyClass
   </servlet-class>

SCENARIO 3.2:

You put the wrong "package" statement at top of your myClass.java file.

For example:

File is in: "/my_stuff" folder

You mistakenly write:

package com.my_stuff

This is tricky because:

1: The maven build (mvn package) will not report any errors here.

2: servlet-class line in web.xml can have CORRECT package path. E.g:

<servlet-class>
my_stuff.MyClass
</servlet-class>

Stack Used: Notepad++ + GitBash + Maven + Heroku Web App Runner + Tomcat9 + Windows10:

How does Google calculate my location on a desktop?

It is possible get your approximate locate based on your IP address (wireless or fixed).

See for example hostip.info or maxmind which basically provide a mapping from IP address to geographical coordinates. The probably use many kinds of heuristics and datasources. This kind of system has probably enough accuracy to put you in right major city, in most cases.

Google probably uses somewhat similar approach in addition to WiFi tricks.

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

I think the Vim documentation should've explained the meaning behind the naming of these commands. Just telling you what they do doesn't help you remember the names.

map is the "root" of all recursive mapping commands. The root form applies to "normal", "visual+select", and "operator-pending" modes. (I'm using the term "root" as in linguistics.)

noremap is the "root" of all non-recursive mapping commands. The root form applies to the same modes as map. (Think of the nore prefix to mean "non-recursive".)

(Note that there are also the ! modes like map! that apply to insert & command-line.)

See below for what "recursive" means in this context.

Prepending a mode letter like n modify the modes the mapping works in. It can choose a subset of the list of applicable modes (e.g. only "visual"), or choose other modes that map wouldn't apply to (e.g. "insert").

Use help map-modes will show you a few tables that explain how to control which modes the mapping applies to.

Mode letters:

  • n: normal only
  • v: visual and select
  • o: operator-pending
  • x: visual only
  • s: select only
  • i: insert
  • c: command-line
  • l: insert, command-line, regexp-search (and others. Collectively called "Lang-Arg" pseudo-mode)

"Recursive" means that the mapping is expanded to a result, then the result is expanded to another result, and so on.

The expansion stops when one of these is true:

  1. the result is no longer mapped to anything else.
  2. a non-recursive mapping has been applied (i.e. the "noremap" [or one of its ilk] is the final expansion).

At that point, Vim's default "meaning" of the final result is applied/executed.

"Non-recursive" means the mapping is only expanded once, and that result is applied/executed.

Example:

 nmap K H
 nnoremap H G
 nnoremap G gg

The above causes K to expand to H, then H to expand to G and stop. It stops because of the nnoremap, which expands and stops immediately. The meaning of G will be executed (i.e. "jump to last line"). At most one non-recursive mapping will ever be applied in an expansion chain (it would be the last expansion to happen).

The mapping of G to gg only applies if you press G, but not if you press K. This mapping doesn't affect pressing K regardless of whether G was mapped recursively or not, since it's line 2 that causes the expansion of K to stop, so line 3 wouldn't be used.

Applications are expected to have a root view controller at the end of application launch

Try to connect IBOutlet of tab bar controller to root view in the Interface Builder instead of

self.window.rootViewController = self.tabBarController;

But actually I haven't seen such error before.

How to obtain the query string from the current URL with JavaScript?

For React Native, React, and For Node project, below one is working

yarn add  query-string

import queryString from 'query-string';

const parsed = queryString.parseUrl("https://pokeapi.co/api/v2/pokemon?offset=10&limit=10");

console.log(parsed.offset) will display 10

How can I rotate an HTML <div> 90 degrees?

We can add the following to a particular tag in CSS:

-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);

In case of half rotation change 90 to 45.

Unable to begin a distributed transaction

Apart from the security settings, I had to open some ports on both servers for the transaction to run. I had to open port 59640 but according to the following suggestion, port 135 has to be open. http://support.microsoft.com/kb/839279

What is a singleton in C#?

I know it's very late to answer the question but with Auto-Property you can do something like that:

public static Singleton Instance { get; } = new Singleton();

Where Singleton is you class and can be via, in this case the readonly property Instance.

How do I remove the height style from a DIV using jQuery?

To reset the height of the div, just try

$("#someDiv").height('auto');

android pinch zoom

In honeycomb, API level 11, it is possible, We can use setScalaX and setScaleY with pivot point
I have explained it here
Zooming a view completely
Pinch Zoom to view completely

How to get year and month from a date - PHP

I'm using these function to get year, month, day from the date

you should put them in a class

    public function getYear($pdate) {
        $date = DateTime::createFromFormat("Y-m-d", $pdate);
        return $date->format("Y");
    }

    public function getMonth($pdate) {
        $date = DateTime::createFromFormat("Y-m-d", $pdate);
        return $date->format("m");
    }

    public function getDay($pdate) {
        $date = DateTime::createFromFormat("Y-m-d", $pdate);
        return $date->format("d");
    }

Clearing UIWebview cache

You can disable the caching by doing the following:

NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
[sharedCache release];

ARC:

NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];

Comparing HTTP and FTP for transferring files

Both of them uses TCP as a transport protocol, but HTTP uses a persistent connection, which makes the performance of the TCP better.

How to include SCSS file in HTML

You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...

For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.

Angular EXCEPTION: No provider for Http

import { HttpModule } from '@angular/http'; package in your module.ts file and add it in your imports.

How to get rid of the "No bootable medium found!" error in Virtual Box?

Try this:

Go to virtual box > right click the OS > settings > under one of the many tab that I don't remember(sorry for this, i dont have vbox installed)> locate the VDI (virtual box disk image) file..

and save the settings.. then try to start the OS..

Jenkins - Configure Jenkins to poll changes in SCM

That's an old question, I know. But, according to me, it is missing proper answer.

The actual / optimal workflow here would be to incorporate SVN's post-commit hook so it triggers Jenkins job after the actual commit is issued only, not in any other case. This way you avoid unneeded polls on your SCM system.

You may find the following links interesting:

In case of my setup in the corp's SVN server, I utilize the following (censored) script as a post-commit hook on the subversion server side:

#!/bin/sh

# POST-COMMIT HOOK

REPOS="$1"
REV="$2"
#TXN_NAME="$3"
LOGFILE=/var/log/xxx/svn/xxx.post-commit.log

MSG=$(svnlook pg --revprop $REPOS svn:log -r$REV)
JENK="http://jenkins.xxx.com:8080/job/xxx/job/xxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
JENKtest="http://jenkins.xxx.com:8080/view/all/job/xxx/job/xxxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"

echo post-commit $* >> $LOGFILE 2>&1

# trigger Jenkins job - xxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx/xxx/Source"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx/xxx/Source" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENK >> $LOGFILE 2>&1
        curl -qs $JENK >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE
fi

# trigger Jenkins job - xxxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx_TEST"
if test 0 -eq $? ; then
        echo $(date) - $REPOS - $REV: >> $LOGFILE
        svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx_TEST" >> $LOGFILE 2>&1
        echo logmsg: $MSG >> $LOGFILE 2>&1
        echo curl -qs $JENKtest >> $LOGFILE 2>&1
        curl -qs $JENKtest >> $LOGFILE 2>&1
        echo -------- >> $LOGFILE
fi

exit 0

how to parse json using groovy

Have you tried using JsonSlurper?

Example usage:

def slurper = new JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')

assert result.person.name == "Guillaume"
assert result.person.age == 33
assert result.person.pets.size() == 2
assert result.person.pets[0] == "dog"
assert result.person.pets[1] == "cat"

How do you run multiple programs in parallel from a bash script?

Process Spawning Manager

Sure, technically these are processes, and this program should really be called a process spawning manager, but this is only due to the way that BASH works when it forks using the ampersand, it uses the fork() or perhaps clone() system call which clones into a separate memory space, rather than something like pthread_create() which would share memory. If BASH supported the latter, each "sequence of execution" would operate just the same and could be termed to be traditional threads whilst gaining a more efficient memory footprint. Functionally however it works the same, though a bit more difficult since GLOBAL variables are not available in each worker clone hence the use of the inter-process communication file and the rudimentary flock semaphore to manage critical sections. Forking from BASH of course is the basic answer here but I feel as if people know that but are really looking to manage what is spawned rather than just fork it and forget it. This demonstrates a way to manage up to 200 instances of forked processes all accessing a single resource. Clearly this is overkill but I enjoyed writing it so I kept on. Increase the size of your terminal accordingly. I hope you find this useful.

ME=$(basename $0)
IPC="/tmp/$ME.ipc"      #interprocess communication file (global thread accounting stats)
DBG=/tmp/$ME.log
echo 0 > $IPC           #initalize counter
F1=thread
SPAWNED=0
COMPLETE=0
SPAWN=1000              #number of jobs to process
SPEEDFACTOR=1           #dynamically compensates for execution time
THREADLIMIT=50          #maximum concurrent threads
TPS=1                   #threads per second delay
THREADCOUNT=0           #number of running threads
SCALE="scale=5"         #controls bc's precision
START=$(date +%s)       #whence we began
MAXTHREADDUR=6         #maximum thread life span - demo mode

LOWER=$[$THREADLIMIT*100*90/10000]   #90% worker utilization threshold
UPPER=$[$THREADLIMIT*100*95/10000]   #95% worker utilization threshold
DELTA=10                             #initial percent speed change

threadspeed()        #dynamically adjust spawn rate based on worker utilization
{
   #vaguely assumes thread execution average will be consistent
   THREADCOUNT=$(threadcount)
   if [ $THREADCOUNT -ge $LOWER ] && [ $THREADCOUNT -le $UPPER ] ;then
      echo SPEED HOLD >> $DBG
      return
   elif [ $THREADCOUNT -lt $LOWER ] ;then
      #if maxthread is free speed up
      SPEEDFACTOR=$(echo "$SCALE;$SPEEDFACTOR*(1-($DELTA/100))"|bc)
      echo SPEED UP $DELTA%>> $DBG
   elif [ $THREADCOUNT -gt $UPPER ];then
      #if maxthread is active then slow down
      SPEEDFACTOR=$(echo "$SCALE;$SPEEDFACTOR*(1+($DELTA/100))"|bc)
      DELTA=1                            #begin fine grain control
      echo SLOW DOWN $DELTA%>> $DBG
   fi

   echo SPEEDFACTOR $SPEEDFACTOR >> $DBG

   #average thread duration   (total elapsed time / number of threads completed)
   #if threads completed is zero (less than 100), default to maxdelay/2  maxthreads

   COMPLETE=$(cat $IPC)

   if [ -z $COMPLETE ];then
      echo BAD IPC READ ============================================== >> $DBG
      return
   fi

   #echo Threads COMPLETE $COMPLETE >> $DBG
   if [ $COMPLETE -lt 100 ];then
      AVGTHREAD=$(echo "$SCALE;$MAXTHREADDUR/2"|bc)
   else
      ELAPSED=$[$(date +%s)-$START]
      #echo Elapsed Time $ELAPSED >> $DBG
      AVGTHREAD=$(echo "$SCALE;$ELAPSED/$COMPLETE*$THREADLIMIT"|bc)
   fi
   echo AVGTHREAD Duration is $AVGTHREAD >> $DBG

   #calculate timing to achieve spawning each workers fast enough
   # to utilize threadlimit - average time it takes to complete one thread / max number of threads
   TPS=$(echo "$SCALE;($AVGTHREAD/$THREADLIMIT)*$SPEEDFACTOR"|bc)
   #TPS=$(echo "$SCALE;$AVGTHREAD/$THREADLIMIT"|bc)  # maintains pretty good
   #echo TPS $TPS >> $DBG

}
function plot()
{
   echo -en \\033[${2}\;${1}H

   if [ -n "$3" ];then
         if [[ $4 = "good" ]];then
            echo -en "\\033[1;32m"
         elif [[ $4 = "warn" ]];then
            echo -en "\\033[1;33m"
         elif [[ $4 = "fail" ]];then
            echo -en "\\033[1;31m"
         elif [[ $4 = "crit" ]];then
            echo -en "\\033[1;31;4m"
         fi
   fi
      echo -n "$3"
      echo -en "\\033[0;39m"
}

trackthread()   #displays thread status
{
   WORKERID=$1
   THREADID=$2
   ACTION=$3    #setactive | setfree | update
   AGE=$4

   TS=$(date +%s)

   COL=$[(($WORKERID-1)/50)*40]
   ROW=$[(($WORKERID-1)%50)+1]

   case $ACTION in
      "setactive" )
         touch /tmp/$ME.$F1$WORKERID  #redundant - see main loop
         #echo created file $ME.$F1$WORKERID >> $DBG
         plot $COL $ROW "Worker$WORKERID: ACTIVE-TID:$THREADID INIT    " good
         ;;
      "update" )
         plot $COL $ROW "Worker$WORKERID: ACTIVE-TID:$THREADID AGE:$AGE" warn
         ;;
      "setfree" )
         plot $COL $ROW "Worker$WORKERID: FREE                         " fail
         rm /tmp/$ME.$F1$WORKERID
         ;;
      * )

      ;;
   esac
}

getfreeworkerid()
{
   for i in $(seq 1 $[$THREADLIMIT+1])
   do
      if [ ! -e /tmp/$ME.$F1$i ];then
         #echo "getfreeworkerid returned $i" >> $DBG
         break
      fi
   done
   if [ $i -eq $[$THREADLIMIT+1] ];then
      #echo "no free threads" >> $DBG
      echo 0
      #exit
   else
      echo $i
   fi
}

updateIPC()
{
   COMPLETE=$(cat $IPC)        #read IPC
   COMPLETE=$[$COMPLETE+1]     #increment IPC
   echo $COMPLETE > $IPC       #write back to IPC
}


worker()
{
   WORKERID=$1
   THREADID=$2
   #echo "new worker WORKERID:$WORKERID THREADID:$THREADID" >> $DBG

   #accessing common terminal requires critical blocking section
   (flock -x -w 10 201
      trackthread $WORKERID $THREADID setactive
   )201>/tmp/$ME.lock

   let "RND = $RANDOM % $MAXTHREADDUR +1"

   for s in $(seq 1 $RND)               #simulate random lifespan
   do
      sleep 1;
      (flock -x -w 10 201
         trackthread $WORKERID $THREADID update $s
      )201>/tmp/$ME.lock
   done

   (flock -x -w 10 201
      trackthread $WORKERID $THREADID setfree
   )201>/tmp/$ME.lock

   (flock -x -w 10 201
      updateIPC
   )201>/tmp/$ME.lock
}

threadcount()
{
   TC=$(ls /tmp/$ME.$F1* 2> /dev/null | wc -l)
   #echo threadcount is $TC >> $DBG
   THREADCOUNT=$TC
   echo $TC
}

status()
{
   #summary status line
   COMPLETE=$(cat $IPC)
   plot 1 $[$THREADLIMIT+2] "WORKERS $(threadcount)/$THREADLIMIT  SPAWNED $SPAWNED/$SPAWN  COMPLETE $COMPLETE/$SPAWN SF=$SPEEDFACTOR TIMING=$TPS"
   echo -en '\033[K'                   #clear to end of line
}

function main()
{
   while [ $SPAWNED -lt $SPAWN ]
   do
      while [ $(threadcount) -lt $THREADLIMIT ] && [ $SPAWNED -lt $SPAWN ]
      do
         WID=$(getfreeworkerid)
         worker $WID $SPAWNED &
         touch /tmp/$ME.$F1$WID    #if this loops faster than file creation in the worker thread it steps on itself, thread tracking is best in main loop
         SPAWNED=$[$SPAWNED+1]
         (flock -x -w 10 201
            status
         )201>/tmp/$ME.lock
         sleep $TPS
        if ((! $[$SPAWNED%100]));then
           #rethink thread timing every 100 threads
           threadspeed
        fi
      done
      sleep $TPS
   done

   while [ "$(threadcount)" -gt 0 ]
   do
      (flock -x -w 10 201
         status
      )201>/tmp/$ME.lock
      sleep 1;
   done

   status
}

clear
threadspeed
main
wait
status
echo

Have a variable in images path in Sass?

Adding something to the above correct answers. I am using netbeans IDE and it shows error while using url(#{$assetPath}/site/background.jpg) this method. It was just netbeans error and no error in sass compiling. But this error break code formatting in netbeans and code become ugly. But when I use it inside quotes like below, it show wonder!

url("#{$assetPath}/site/background.jpg")

Saving binary data as file using JavaScript from a browser

To do this task download.js library can be used. Here is an example from library docs:

download("data:image/gif;base64,R0lGODlhRgAVAIcAAOfn5+/v7/f39////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////yH5BAAAAP8ALAAAAABGABUAAAj/AAEIHAgggMGDCAkSRMgwgEKBDRM+LBjRoEKDAjJq1GhxIMaNGzt6DAAypMORJTmeLKhxgMuXKiGSzPgSZsaVMwXUdBmTYsudKjHuBCoAIc2hMBnqRMqz6MGjTJ0KZcrz5EyqA276xJrVKlSkWqdGLQpxKVWyW8+iJcl1LVu1XttafTs2Lla3ZqNavAo37dm9X4eGFQtWKt+6T+8aDkxUqWKjeQUvfvw0MtHJcCtTJiwZsmLMiD9uplvY82jLNW9qzsy58WrWpDu/Lp0YNmPXrVMvRm3T6GneSX3bBt5VeOjDemfLFv1XOW7kncvKdZi7t/S7e2M3LkscLcvH3LF7HwSuVeZtjuPPe2d+GefPrD1RpnS6MGdJkebn4/+oMSAAOw==", "dlDataUrlBin.gif", "image/gif");

Using PropertyInfo to find out the property type

Use PropertyInfo.PropertyType to get the type of the property.

public bool ValidateData(object data)
{
    foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
    {
        if (propertyInfo.PropertyType == typeof(string))
        {
            string value = propertyInfo.GetValue(data, null);

            if value is not OK
            {
                return false;
            }
        }
    }            

    return true;
}

Twitter Bootstrap 3.0 how do I "badge badge-important" now

Bootstrap 3 removed those color options for badges. However, we can add those styles manually. Here's my solution, and here is the JS Bin:

.badge {
  padding: 1px 9px 2px;
  font-size: 12.025px;
  font-weight: bold;
  white-space: nowrap;
  color: #ffffff;
  background-color: #999999;
  -webkit-border-radius: 9px;
  -moz-border-radius: 9px;
  border-radius: 9px;
}
.badge:hover {
  color: #ffffff;
  text-decoration: none;
  cursor: pointer;
}
.badge-error {
  background-color: #b94a48;
}
.badge-error:hover {
  background-color: #953b39;
}
.badge-warning {
  background-color: #f89406;
}
.badge-warning:hover {
  background-color: #c67605;
}
.badge-success {
  background-color: #468847;
}
.badge-success:hover {
  background-color: #356635;
}
.badge-info {
  background-color: #3a87ad;
}
.badge-info:hover {
  background-color: #2d6987;
}
.badge-inverse {
  background-color: #333333;
}
.badge-inverse:hover {
  background-color: #1a1a1a;
}

NameError: name 'datetime' is not defined

It can also be used as below:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)

Is there a CSS selector for text nodes?

You cannot target text nodes with CSS. I'm with you; I wish you could... but you can't :(

If you don't wrap the text node in a <span> like @Jacob suggests, you could instead give the surrounding element padding as opposed to margin:

HTML

<p id="theParagraph">The text node!</p>

CSS

p#theParagraph
{
    border: 1px solid red;
    padding-bottom: 10px;
}

Create code first, many to many, with additional fields in association table

The code provided by this answer is right, but incomplete, I've tested it. There are missing properties in "UserEmail" class:

    public UserTest UserTest { get; set; }
    public EmailTest EmailTest { get; set; }

I post the code I've tested if someone is interested. Regards

using System.Data.Entity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

#region example2
public class UserTest
{
    public int UserTestID { get; set; }
    public string UserTestname { get; set; }
    public string Password { get; set; }

    public ICollection<UserTestEmailTest> UserTestEmailTests { get; set; }

    public static void DoSomeTest(ApplicationDbContext context)
    {

        for (int i = 0; i < 5; i++)
        {
            var user = context.UserTest.Add(new UserTest() { UserTestname = "Test" + i });
            var address = context.EmailTest.Add(new EmailTest() { Address = "address@" + i });
        }
        context.SaveChanges();

        foreach (var user in context.UserTest.Include(t => t.UserTestEmailTests))
        {
            foreach (var address in context.EmailTest)
            {
                user.UserTestEmailTests.Add(new UserTestEmailTest() { UserTest = user, EmailTest = address, n1 = user.UserTestID, n2 = address.EmailTestID });
            }
        }
        context.SaveChanges();
    }
}

public class EmailTest
{
    public int EmailTestID { get; set; }
    public string Address { get; set; }

    public ICollection<UserTestEmailTest> UserTestEmailTests { get; set; }
}

public class UserTestEmailTest
{
    public int UserTestID { get; set; }
    public UserTest UserTest { get; set; }
    public int EmailTestID { get; set; }
    public EmailTest EmailTest { get; set; }
    public int n1 { get; set; }
    public int n2 { get; set; }


    //Call this code from ApplicationDbContext.ConfigureMapping
    //and add this lines as well:
    //public System.Data.Entity.DbSet<yournamespace.UserTest> UserTest { get; set; }
    //public System.Data.Entity.DbSet<yournamespace.EmailTest> EmailTest { get; set; }
    internal static void RelateFluent(System.Data.Entity.DbModelBuilder builder)
    {
        // Primary keys
        builder.Entity<UserTest>().HasKey(q => q.UserTestID);
        builder.Entity<EmailTest>().HasKey(q => q.EmailTestID);

        builder.Entity<UserTestEmailTest>().HasKey(q =>
            new
            {
                q.UserTestID,
                q.EmailTestID
            });

        // Relationships
        builder.Entity<UserTestEmailTest>()
            .HasRequired(t => t.EmailTest)
            .WithMany(t => t.UserTestEmailTests)
            .HasForeignKey(t => t.EmailTestID);

        builder.Entity<UserTestEmailTest>()
            .HasRequired(t => t.UserTest)
            .WithMany(t => t.UserTestEmailTests)
            .HasForeignKey(t => t.UserTestID);
    }
}
#endregion

Fatal error: Call to undefined function sqlsrv_connect()

This helped me get to my answer. There are two php.ini files located, in my case, for wamp. One is under the php folder and the other one is in the C:\wamp\bin\apache\Apachex.x.x\bin folder. When connecting to SQL through sqlsrv_connect function, we are referring to the php.ini file in the apache folder. Add the following (as per your version) to this file:

extension=c:/wamp/bin/php/php5.4.16/ext/php_sqlsrv_53_ts.dll

Zoom in on a point (using scale and translate)

Finally solved it:

_x000D_
_x000D_
var zoomIntensity = 0.2;_x000D_
_x000D_
var canvas = document.getElementById("canvas");_x000D_
var context = canvas.getContext("2d");_x000D_
var width = 600;_x000D_
var height = 200;_x000D_
_x000D_
var scale = 1;_x000D_
var originx = 0;_x000D_
var originy = 0;_x000D_
var visibleWidth = width;_x000D_
var visibleHeight = height;_x000D_
_x000D_
_x000D_
function draw(){_x000D_
    // Clear screen to white._x000D_
    context.fillStyle = "white";_x000D_
    context.fillRect(originx,originy,800/scale,600/scale);_x000D_
    // Draw the black square._x000D_
    context.fillStyle = "black";_x000D_
    context.fillRect(50,50,100,100);_x000D_
}_x000D_
// Draw loop at 60FPS._x000D_
setInterval(draw, 1000/60);_x000D_
_x000D_
canvas.onwheel = function (event){_x000D_
    event.preventDefault();_x000D_
    // Get mouse offset._x000D_
    var mousex = event.clientX - canvas.offsetLeft;_x000D_
    var mousey = event.clientY - canvas.offsetTop;_x000D_
    // Normalize wheel to +1 or -1._x000D_
    var wheel = event.deltaY < 0 ? 1 : -1;_x000D_
_x000D_
    // Compute zoom factor._x000D_
    var zoom = Math.exp(wheel*zoomIntensity);_x000D_
    _x000D_
    // Translate so the visible origin is at the context's origin._x000D_
    context.translate(originx, originy);_x000D_
  _x000D_
    // Compute the new visible origin. Originally the mouse is at a_x000D_
    // distance mouse/scale from the corner, we want the point under_x000D_
    // the mouse to remain in the same place after the zoom, but this_x000D_
    // is at mouse/new_scale away from the corner. Therefore we need to_x000D_
    // shift the origin (coordinates of the corner) to account for this._x000D_
    originx -= mousex/(scale*zoom) - mousex/scale;_x000D_
    originy -= mousey/(scale*zoom) - mousey/scale;_x000D_
    _x000D_
    // Scale it (centered around the origin due to the trasnslate above)._x000D_
    context.scale(zoom, zoom);_x000D_
    // Offset the visible origin to it's proper position._x000D_
    context.translate(-originx, -originy);_x000D_
_x000D_
    // Update scale and others._x000D_
    scale *= zoom;_x000D_
    visibleWidth = width / scale;_x000D_
    visibleHeight = height / scale;_x000D_
}
_x000D_
<canvas id="canvas" width="600" height="200"></canvas>
_x000D_
_x000D_
_x000D_

The key, as @Tatarize pointed out, is to compute the axis position such that the zoom point (mouse pointer) remains in the same place after the zoom.

Originally the mouse is at a distance mouse/scale from the corner, we want the point under the mouse to remain in the same place after the zoom, but this is at mouse/new_scale away from the corner. Therefore we need to shift the origin (coordinates of the corner) to account for this.

originx -= mousex/(scale*zoom) - mousex/scale;
originy -= mousey/(scale*zoom) - mousey/scale;
scale *= zoom

The remaining code then needs to apply the scaling and translate to the draw context so it's origin coincides with the canvas corner.

MySQL: Set user variable from result of query

First lets take a look at how can we define a variable in mysql

To define a varible in mysql it should start with '@' like @{variable_name} and this '{variable_name}', we can replace it with our variable name.

Now, how to assign a value in a variable in mysql. For this we have many ways to do that

  1. Using keyword 'SET'.

Example :-

mysql >  SET @a = 1;
  1. Without using keyword 'SET' and using ':='.

Example:-

mysql > @a:=1;
  1. By using 'SELECT' statement.

Example:-

mysql > select 1 into @a;

Here @a is user defined variable and 1 is going to be assigned in @a.

Now how to get or select the value of @{variable_name}.

we can use select statement like

Example :-

mysql > select @a;

it will show the output and show the value of @a.

Now how to assign a value from a table in a variable.

For this we can use two statement like :-

1.

@a := (select emp_name from employee where emp_id = 1);
select emp_name into @a from employee where emp_id = 1;

Always be careful emp_name must return single value otherwise it will throw you a error in this type statements.

refer this:- http://www.easysolutionweb.com/sql-pl-sql/how-to-assign-a-value-in-a-variable-in-mysql

run a python script in terminal without the python command

You need to use a hashbang. Add it to the first line of your python script.

#! <full path of python interpreter>

Then change the file permissions, and add the executing permission.

chmod +x <filename>

And finally execute it using

./<filename>

If its in the current directory,

JavaScript global event mechanism

How to Catch Unhandled Javascript Errors

Assign the window.onerror event to an event handler like:

<script type="text/javascript">
window.onerror = function(msg, url, line, col, error) {
   // Note that col & error are new to the HTML 5 spec and may not be 
   // supported in every browser.  It worked for me in Chrome.
   var extra = !col ? '' : '\ncolumn: ' + col;
   extra += !error ? '' : '\nerror: ' + error;

   // You can view the information in an alert to see things working like this:
   alert("Error: " + msg + "\nurl: " + url + "\nline: " + line + extra);

   // TODO: Report this error via ajax so you can keep track
   //       of what pages have JS issues

   var suppressErrorAlert = true;
   // If you return true, then error alerts (like in older versions of 
   // Internet Explorer) will be suppressed.
   return suppressErrorAlert;
};
</script>

As commented in the code, if the return value of window.onerror is true then the browser should suppress showing an alert dialog.

When does the window.onerror Event Fire?

In a nutshell, the event is raised when either 1.) there is an uncaught exception or 2.) a compile time error occurs.

uncaught exceptions

  • throw "some messages"
  • call_something_undefined();
  • cross_origin_iframe.contentWindow.document;, a security exception

compile error

  • <script>{</script>
  • <script>for(;)</script>
  • <script>"oops</script>
  • setTimeout("{", 10);, it will attempt to compile the first argument as a script

Browsers supporting window.onerror

  • Chrome 13+
  • Firefox 6.0+
  • Internet Explorer 5.5+
  • Opera 11.60+
  • Safari 5.1+

Screenshot:

Example of the onerror code above in action after adding this to a test page:

<script type="text/javascript">
call_something_undefined();
</script>

Javascript alert showing error information detailed by the window.onerror event

Example for AJAX error reporting

var error_data = {
    url: document.location.href,
};

if(error != null) {
    error_data['name'] = error.name; // e.g. ReferenceError
    error_data['message'] = error.line;
    error_data['stack'] = error.stack;
} else {
    error_data['msg'] = msg;
    error_data['filename'] = filename;
    error_data['line'] = line;
    error_data['col'] = col;
}

var xhr = new XMLHttpRequest();

xhr.open('POST', '/ajax/log_javascript_error');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
    if (xhr.status === 200) {
        console.log('JS error logged');
    } else if (xhr.status !== 200) {
        console.error('Failed to log JS error.');
        console.error(xhr);
        console.error(xhr.status);
        console.error(xhr.responseText);
    }
};
xhr.send(JSON.stringify(error_data));

JSFiddle:

https://jsfiddle.net/nzfvm44d/

References:

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

For Swift 3 and XCode 8, this worked. Follow below steps to achieve this:-

viewDidLoad()
    {
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        var width = UIScreen.main.bounds.width
        layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
    width = width - 10
    layout.itemSize = CGSize(width: width / 2, height: width / 2)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        collectionView!.collectionViewLayout = layout
    }

How do I use a file grep comparison inside a bash if/else statement?

Note that, for PIPE being any command or sequence of commands, then:

if PIPE ; then
  # do one thing if PIPE returned with zero status ($?=0)
else 
  # do another thing if PIPE returned with non-zero status ($?!=0), e.g. error
fi 

For the record, [ expr ] is a shell builtin shorthand for test expr.

Since grep returns with status 0 in case of a match, and non-zero status in case of no matches, you can use:

if grep -lq '^MYSQL_ROLE=master' ; then 
  # do one thing 
else 
  # do another thing
fi 

Note the use of -l which only cares about the file having at least one match (so that grep returns as soon as it finds one match, without needlessly continuing to parse the input file.)

on some platforms [ expr ] is not a builtin, but an actual executable /bin/[ (whose last argument will be ]), which is why [ expr ] should contain blanks around the square brackets, and why it must be followed by one of the command list separators (;, &&, ||, |, &, newline)

How to create a database from shell command?

If you create a new database it's good to create user with permissions only for this database (if anything goes wrong you won't compromise root user login and password). So everything together will look like this:

mysql -u base_user -pbase_user_pass -e "create database new_db; GRANT ALL PRIVILEGES ON new_db.* TO new_db_user@localhost IDENTIFIED BY 'new_db_user_pass'"

Where:
base_user is the name for user with all privileges (probably the root)
base_user_pass it's the password for base_user (lack of space between -p and base_user_pass is important)
new_db is name for newly created database
new_db_user is name for the new user with access only for new_db
new_db_user_pass it's the password for new_db_user

JavaScript: function returning an object

You can simply do it like this with an object literal:

function makeGamePlayer(name,totalScore,gamesPlayed) {
    return {
        name: name,
        totalscore: totalScore,
        gamesPlayed: gamesPlayed
    };
}

How do I watch a file for changes?

If polling is good enough for you, I'd just watch if the "modified time" file stat changes. To read it:

os.stat(filename).st_mtime

(Also note that the Windows native change event solution does not work in all circumstances, e.g. on network drives.)

import os

class Monkey(object):
    def __init__(self):
        self._cached_stamp = 0
        self.filename = '/path/to/file'

    def ook(self):
        stamp = os.stat(self.filename).st_mtime
        if stamp != self._cached_stamp:
            self._cached_stamp = stamp
            # File has changed, so do something...

How to compare strings in Bash

I have to disagree one of the comments in one point:

[ "$x" == "valid" ] && echo "valid" || echo "invalid"

No, that is not a crazy oneliner

It's just it looks like one to, hmm, the uninitiated...

It uses common patterns as a language, in a way;

And after you learned the language.

Actually, it's nice to read

It is a simple logical expression, with one special part: lazy evaluation of the logic operators.

[ "$x" == "valid" ] && echo "valid" || echo "invalid"

Each part is a logical expression; the first may be true or false, the other two are always true.

(
[ "$x" == "valid" ] 
&&
echo "valid"
)
||
echo "invalid"

Now, when it is evaluated, the first is checked. If it is false, than the second operand of the logic and && after it is not relevant. The first is not true, so it can not be the first and the second be true, anyway.
Now, in this case is the the first side of the logic or || false, but it could be true if the other side - the third part - is true.

So the third part will be evaluated - mainly writing the message as a side effect. (It has the result 0 for true, which we do not use here)

The other cases are similar, but simpler - and - I promise! are - can be - easy to read!
(I don't have one, but I think being a UNIX veteran with grey beard helps a lot with this.)

Create an Array of Arraylists

The problem with this situation is by using a arraylist you get a time complexity of o(n) for adding at a specific position. If you use an array you create a memory location by declaring your array therefore it is constant

SQL Query Where Field DOES NOT Contain $x

SELECT * FROM table WHERE field1 NOT LIKE '%$x%'; (Make sure you escape $x properly beforehand to avoid SQL injection)

Edit: NOT IN does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%' can use an index. LIKE '%xxx' or LIKE '%xxx%' can't.

Why use Optional.of over Optional.ofNullable?

In addition, If you know your code should not work if object is null, you can throw exception by using Optional.orElseThrow

String nullName = null;

String name = Optional.ofNullable(nullName)
                      .orElseThrow(NullPointerException::new);
                   // .orElseThrow(CustomException::new);

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

java.lang.IllegalStateException: Fragment not attached to Activity

Sometimes this exception is caused by a bug in the support library implementation. Recently I had to downgrade from 26.1.0 to 25.4.0 to get rid of it.

No restricted globals

For me I had issues with history and location... As the accepted answer using window before history and location (i.e) window.history and window.location solved mine

How to return 2 values from a Java method?

Instead of returning an array that contains the two values or using a generic Pair class, consider creating a class that represents the result that you want to return, and return an instance of that class. Give the class a meaningful name. The benefits of this approach over using an array are type safety and it will make your program much easier to understand.

Note: A generic Pair class, as proposed in some of the other answers here, also gives you type safety, but doesn't convey what the result represents.

Example (which doesn't use really meaningful names):

final class MyResult {
    private final int first;
    private final int second;

    public MyResult(int first, int second) {
        this.first = first;
        this.second = second;
    }

    public int getFirst() {
        return first;
    }

    public int getSecond() {
        return second;
    }
}

// ...

public static MyResult something() {
    int number1 = 1;
    int number2 = 2;

    return new MyResult(number1, number2);
}

public static void main(String[] args) {
    MyResult result = something();
    System.out.println(result.getFirst() + result.getSecond());
}

How do I add a Maven dependency in Eclipse?

I have faced same problem with maven dependencies, eg: unfortunetly your maven dependencies deleted from your buildpath,then you people get lot of exceptions,if you follow below process you can easily resolve this issue.

 Right click on project >> maven >> updateProject >> selectProject >> OK

String is immutable. What exactly is the meaning?

Only the reference is changing. First a was referencing to the string "a", and later you changed it to "ty". The string "a" remains the same.

Tomcat 7: How to set initial heap size correctly?

It works even without using 'export' keyword. This is what i have in my setenv.sh (/usr/share/tomcat7/bin/setenv.sh) and it works.

OS : 14.04.1-Ubuntu Server version: Apache Tomcat/7.0.52 (Ubuntu) Server built: Jun 30 2016 01:59:37 Server number: 7.0.52.0

JAVA_OPTS="-Dorg.apache.catalina.security.SecurityListener.UMASK=`umask` -server -Xms6G -Xmx6G -Xmn1400m -XX:HeapDumpPath=/Some/logs/ -XX:+HeapDumpOnOutOfMemoryError -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -XX:SurvivorRatio=8 -XX:+UseCompressedOops -Dcom.sun.management.jmxremote.port=8181 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"
JAVA_OPTS="$JAVA_OPTS -Dserver.name=$HOSTNAME"

High-precision clock in Python

The standard time.time() function provides sub-second precision, though that precision varies by platform. For Linux and Mac precision is +- 1 microsecond or 0.001 milliseconds. Python on Windows uses +- 16 milliseconds precision due to clock implementation problems due to process interrupts. The timeit module can provide higher resolution if you're measuring execution time.

>>> import time
>>> time.time()        #return seconds from epoch
1261367718.971009      

Python 3.7 introduces new functions to the time module that provide higher resolution:

>>> import time
>>> time.time_ns()
1530228533161016309
>>> time.time_ns() / (10 ** 9) # convert to floating-point seconds
1530228544.0792289

Xamarin.Forms ListView: Set the highlight color of a tapped item

In Android simply edit your styles.xml file under Resources\values adding this:

<resources>
  <style name="MyTheme" parent="android:style/Theme.Material.Light.DarkActionBar">
   <item name="android:colorPressedHighlight">@color/ListViewSelected</item>
   <item name="android:colorLongPressedHighlight">@color/ListViewHighlighted</item>
   <item name="android:colorFocusedHighlight">@color/ListViewSelected</item>
   <item name="android:colorActivatedHighlight">@color/ListViewSelected</item>
   <item name="android:activatedBackgroundIndicator">@color/ListViewSelected</item>
  </style>
<color name="ListViewSelected">#96BCE3</color>
<color name="ListViewHighlighted">#E39696</color>
</resources>

ADB.exe is obsolete and has serious performance problems

For me, update SDK doesn't help. I solve this problem by unchecking the emulator option "Use detected ADB location". Give it a try. use detected ADB location

How can I change NULL to 0 when getting a single value from a SQL function?

SELECT 0+COALESCE(SUM(Price),0) AS TotalPrice
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)

UIDevice uniqueIdentifier deprecated - What to do now?

Create your own UUID and then store it in the Keychain. Thus it persists even when your app gets uninstalled. In many cases it also persists even if the user migrates between devices (e.g. full backup and restore to another device).

Effectively it becomes a unique user identifier as far as you're concerned. (even better than device identifier).

Example:

I am defining a custom method for creating a UUID as :

- (NSString *)createNewUUID 
{
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    return [(NSString *)string autorelease];
}

You can then store it in KEYCHAIN on the very first launch of your app. So that after first launch, we can simply use it from keychain, no need to regenerate it. The main reason for using Keychain to store is: When you set the UUID to the Keychain, it will persist even if the user completely uninstalls the App and then installs it again. . So, this is the permanent way of storing it, which means the key will be unique all the way.

     #import "SSKeychain.h"
     #import <Security/Security.h>

On applictaion launch include the following code :

 // getting the unique key (if present ) from keychain , assuming "your app identifier" as a key
       NSString *retrieveuuid = [SSKeychain passwordForService:@"your app identifier" account:@"user"];
      if (retrieveuuid == nil) { // if this is the first time app lunching , create key for device
        NSString *uuid  = [self createNewUUID];
// save newly created key to Keychain
        [SSKeychain setPassword:uuid forService:@"your app identifier" account:@"user"];
// this is the one time process
}

Download SSKeychain.m and .h file from sskeychain and Drag SSKeychain.m and .h file to your project and add "Security.framework" to your project. To use UUID afterwards simply use :

NSString *retrieveuuid = [SSKeychain passwordForService:@"your app identifier" account:@"user"];

Finding smallest value in an array most efficiently

You need too loop through the array, remembering the smallest value you've seen so far. Like this:

int smallest = INT_MAX;
for (int i = 0; i < array_length; i++) {
    if (array[i] < smallest) {
        smallest = array[i];
    }
}

How to append text to a text file in C++?

I use this code. It makes sure that file gets created if it doesn't exist and also adds bit of error checks.

static void appendLineToFile(string filepath, string line)
{
    std::ofstream file;
    //can't enable exception now because of gcc bug that raises ios_base::failure with useless message
    //file.exceptions(file.exceptions() | std::ios::failbit);
    file.open(filepath, std::ios::out | std::ios::app);
    if (file.fail())
        throw std::ios_base::failure(std::strerror(errno));

    //make sure write fails with exception if something is wrong
    file.exceptions(file.exceptions() | std::ios::failbit | std::ifstream::badbit);

    file << line << std::endl;
}

How do I find out where login scripts live?

In addition from the command prompt run SET.

This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).

Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

What ended up working for me after a few hours of pain..

if you're running brew..

brew install ruby

in the terminal output/log, identify the path where ruby was installed, brew suggests 'You may want to add this to your PATH', so that's what we'll do. For example, mine is

/usr/local/lib/ruby/gems/3.0.0/bin

Add this to your path by running (omitting braces)

echo 'export PATH"{the_path_you_found_above}:$PATH"' >> ~/.bash_profile

then update your environment by running

source ~/.bash_profile

now, try running your install, i.e.,

sudo gem install middleman

Import CSV file into SQL Server

All of the answers here work great if your data is "clean" (no data constraint violations, etc.) and you have access to putting the file on the server. Some of the answers provided here stop at the first error (PK violation, data-loss error, etc.) and give you one error at a time if using SSMS's built in Import Task. If you want to gather all errors at once (in case you want to tell the person that gave you the .csv file to clean up their data), I recommend the following as an answer. This answer also gives you complete flexibility as you are "writing" the SQL yourself.

Note: I'm going to assume you are running a Windows OS and have access to Excel and SSMS. If not, I'm sure you can tweak this answer to fit your needs.

  1. Using Excel, open your .csv file. In an empty column you will write a formula that will build individual INSERTstatements like =CONCATENATE("INSERT INTO dbo.MyTable (FirstName, LastName) VALUES ('", A1, "', '", B1,"')", CHAR(10), "GO") where A1 is a cell that has the first name data and A2 has the last name data for example.

    • CHAR(10) adds a newline character to the final result and GO will allow us to run this INSERT and continue to the next even if there are any errors.
  2. Highlight the cell with your =CONCATENATION() formula

  3. Shift + End to highlight the same column in the rest of your rows

  4. In the ribbon > Home > Editing > Fill > Click Down

    • This applies the formula all the way down the sheet so you don't have to copy-paste, drag, etc. down potentially thousands of rows by hand
  5. Ctrl + C to copy the formulated SQL INSERT statements

  6. Paste into SSMS

  7. You will notice Excel, probably unexpectedly, added double quotes around each of your INSERT and GO commands. This is a "feature" (?) of copying multi-line values out of Excel. You can simply find and replace "INSERT and GO" with INSERT and GO respectively to clean that up.

  8. Finally you are ready to run your import process

  9. After the process completes, check the Messages window for any errors. You can select all the content (Ctrl + A) and copy into Excel and use a column filter to remove any successful messages and you are left with any and all the errors.

This process will definitely take longer than other answers here, but if your data is "dirty" and full of SQL violations, you can at least gather all the errors at one time and send them to the person that gave you the data, if that is your scenario.

Error message "No exports were found that match the constraint contract name"

I experienced a similar problem after some updates released from Microsoft (part of them where about .NET framework 4.5).

On the Internet I got the following link to the Microsoft knowledge base article:

Update for Microsoft Visual Studio 2012 (KB2781514)

It worked for me.

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

If you're using Nedit under Cygwin-X (or any platform for that matter), hold down the Ctrl key while selecting text with the left mouse.

Additionally, you can then drag the selected "box" around in an insert mode using the depressed left-mouse button or in overwrite mode by using Ctrl+left-mouse button.

What causing this "Invalid length for a Base-64 char array"

During initial testing for Membership.ValidateUser with a SqlMembershipProvider, I use a hash (SHA1) algorithm combined with a salt, and, if I changed the salt length to a length not divisible by four, I received this error.

I have not tried any of the fixes above, but if the salt is being altered, this may help someone pinpoint that as the source of this particular error.

Referencing Row Number in R

Perhaps with dataframes one of the most easy and practical solution is:

data = dplyr::mutate(data, rownum=row_number())

How to convert a negative number to positive?

>>> n = -42
>>> -n       # if you know n is negative
42
>>> abs(n)   # for any n
42

Don't forget to check the docs.

Can I change the height of an image in CSS :before/:after pseudo-elements?

Yes, the original question was asked eight years ago, but it's actually relevant today as its always been. Now, I've been going from pillar to post over this issue of ::before, for about a week ::after, and its been driving me round the bend.

From this page, and others on the subject - I've finally put it together and sized an image down in the pseudo tag.

** Running note .colnav is just my container class, that holds an < UL > and < LI > set of tags with a set of < a hrefs inside.

Below is the code (complete)

.colnav li.nexus-button a:hover:before {   
    background-image: url('/images/fleur-de-lis.png');
    background-size: 90px 20px;
    background-repeat: no-repeat;
    width: 130px;
    height: 20px;
    margin-left: -120px;
    margin-top: -3px;
    transform: scale(1.5);
    content: "";
    position: absolute;
}

The image file was (is) 120 x 80, and the picture got reduced right down to 90x 20, where it then fitted quite nicely behind the html href tag, and it all came together with that position: absolute statement at the end.

How to iterate through an ArrayList of Objects of ArrayList of Objects?

for (Bullet bullet : gunList.get(2).getBullet()) System.out.println(bullet);

return value after a promise

Use a pattern along these lines:

function getValue(file) {
  return lookupValue(file);
}

getValue('myFile.txt').then(function(res) {
  // do whatever with res here
});

(although this is a bit redundant, I'm sure your actual code is more complicated)

Excel: the Incredible Shrinking and Expanding Controls

My monitors all appear to be set at native resolutions, which deepens the mystery. However, I have found that doing SOMETHING to the button (moving or resizing) somehow fixes the problem. This routine automates the moving, and then restores the original setting.

The following code seems to address the problem, at least for buttons.

Public Sub StablizeButton(oButton As MSForms.CommandButton)

    With oButton

        ' If True, then temporary distortion is remedied only by clicking somewhere.
        ' If False, then the temporary distortion is remedied merely by moving the mouse pointer away.
        .TakeFocusOnClick = False
        ' For best results:  In the Properties Sheet, initialize to False.

        .Left = .Left + 200             ' Move the button 200 units to the right, ...
        .Left = .Left - 200             ' ... and then move it back.

    End With

End Sub

Invoke it as follows:

Private Sub MyButton_Click()
    StablizeButton MyButton

    ' Remainder of code.
End Sub

How to remove all of the data in a table using Django

You can use the Django-Truncate library to delete all data of a table without destroying the table structure.

Example:

  1. First, install django-turncate using your terminal/command line:
pip install django-truncate
  1. Add "django_truncate" to your INSTALLED_APPS in the settings.py file:
INSTALLED_APPS = [
    ...
    'django_truncate',
]
  1. Use this command in your terminal to delete all data of the table from the app.
python manage.py truncate --apps app_name --models table_name

Add Legend to Seaborn point plot

Old question, but there's an easier way.

sns.pointplot(x=x_col,y=y_col,data=df_1,color='blue')
sns.pointplot(x=x_col,y=y_col,data=df_2,color='green')
sns.pointplot(x=x_col,y=y_col,data=df_3,color='red')
plt.legend(labels=['legendEntry1', 'legendEntry2', 'legendEntry3'])

This lets you add the plots sequentially, and not have to worry about any of the matplotlib crap besides defining the legend items.

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

Eileen: No, it is not var nameVal = form.inputname.val();. It should be either...

in jQuery:

// you can use IDs (easier)

var nameVal =  $(form).find('#id').val();

// or use the [name=Fieldname] to search for the field

var nameVal =  $(form).find('[name=Fieldname]').val();

Or in JavaScript:

var nameVal = this.form.FieldName.value;

Or a combination:

var nameVal = $(this.form.FieldName).val();

With jQuery, you could even loop through all of the inputs in the form:

$(form).find('input, select, textarea').each(function(){

  var name = this.name;
  // OR
  var name = $(this).attr('name');

  var value = this.value;
  // OR
  var value = $(this).val();
  ....
  });

Setting PHP tmp dir - PHP upload not working

The problem described here was solved by me quite a long time ago but I don't really remember what was the main reason that uploads weren't working. There were multiple things that needed fixing so the upload could work. I have created checklist that might help others having similar problems and I will edit it to make it as helpful as possible. As I said before on chat, I was working on embedded system, so some points may be skipped on non-embedded systems.

  • Check upload_tmp_dir in php.ini. This is directory where PHP stores temporary files while uploading.

  • Check open_basedir in php.ini. If defined it limits PHP read/write rights to specified path and its subdirectories. Ensure that upload_tmp_dir is inside this path.

  • Check post_max_size in php.ini. If you want to upload 20 Mbyte files, try something a little bigger, like post_max_size = 21M. This defines largest size of POST message which you are probably using during upload.

  • Check upload_max_filesize in php.ini. This specifies biggest file that can be uploaded.

  • Check memory_limit in php.ini. That's the maximum amount of memory a script may consume. It's quite obvious that it can't be lower than upload size (to be honest I'm not quite sure about it-PHP is probably buffering while copying temporary files).

  • Ensure that you're checking the right php.ini file that is one used by PHP on your webserver. The best solution is to execute script with directive described here http://php.net/manual/en/function.php-ini-loaded-file.php (php_ini_loaded_file function)

  • Check what user php runs as (See here how to do it: How to check what user php is running as? ). I have worked on different distros and servers. Sometimes it is apache, but sometimes it can be root. Anyway, check that this user has rights for reading and writing in the temporary directory and directory that you're uploading into. Check all directories in the path in case you're uploading into subdirectory (for example /dir1/dir2/-check both dir1 and dir2.

  • On embedded platforms you sometimes need to restrict writing to root filesystem because it is stored on flash card and this helps to extend life of this card. If you are using scripts to enable/disable file writes, ensure that you enable writing before uploading.

  • I had serious problems with PHP >5.4 upload monitoring based on sessions (as described here http://phpmaster.com/tracking-upload-progress-with-php-and-javascript/ ) on some platforms. Try something simple at first (like here: http://www.dzone.com/snippets/very-simple-php-file-upload ). If it works, you can try more sophisticated mechanisms.

  • If you make any changes in php.ini remember to restart server so the configuration will be reloaded.

Can attributes be added dynamically in C#?

In Java I used to work around this by using a map and implementing my own take on Key-Value coding.

http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueCoding/KeyValueCoding.html

How to get an absolute file path in Python

Today you can also use the unipath package which was based on path.py: http://sluggo.scrapping.cc/python/unipath/

>>> from unipath import Path
>>> absolute_path = Path('mydir/myfile.txt').absolute()
Path('C:\\example\\cwd\\mydir\\myfile.txt')
>>> str(absolute_path)
C:\\example\\cwd\\mydir\\myfile.txt
>>>

I would recommend using this package as it offers a clean interface to common os.path utilities.

How to implement a secure REST API with node.js

I just finished a sample app that does this in a pretty basic, but clear way. It uses mongoose with mongodb to store users and passport for auth management.

https://github.com/Khelldar/Angular-Express-Train-Seed

In Java, what is the best way to determine the size of an object?

Firstly "the size of an object" isn't a well-defined concept in Java. You could mean the object itself, with just its members, the Object and all objects it refers to (the reference graph). You could mean the size in memory or the size on disk. And the JVM is allowed to optimise things like Strings.

So the only correct way is to ask the JVM, with a good profiler (I use YourKit), which probably isn't what you want.

However, from the description above it sounds like each row will be self-contained, and not have a big dependency tree, so the serialization method will probably be a good approximation on most JVMs. The easiest way to do this is as follows:

 Serializable ser;
 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 ObjectOutputStream oos = new ObjectOutputStream(baos);
 oos.writeObject(ser);
 oos.close();
 return baos.size();

Remember that if you have objects with common references this will not give the correct result, and size of serialization will not always match size in memory, but it is a good approximation. The code will be a bit more efficient if you initialise the ByteArrayOutputStream size to a sensible value.

Relative frequencies / proportions with dplyr

I wrote a small function for this repeating task:

count_pct <- function(df) {
  return(
    df %>%
      tally %>% 
      mutate(n_pct = 100*n/sum(n))
  )
}

I can then use it like:

mtcars %>% 
  group_by(cyl) %>% 
  count_pct

It returns:

# A tibble: 3 x 3
    cyl     n n_pct
  <dbl> <int> <dbl>
1     4    11  34.4
2     6     7  21.9
3     8    14  43.8

How to specify legend position in matplotlib in graph coordinates

The loc parameter specifies in which corner of the bounding box the legend is placed. The default for loc is loc="best" which gives unpredictable results when the bbox_to_anchor argument is used.
Therefore, when specifying bbox_to_anchor, always specify loc as well.

The default for bbox_to_anchor is (0,0,1,1), which is a bounding box over the complete axes. If a different bounding box is specified, is is usually sufficient to use the first two values, which give (x0, y0) of the bounding box.

Below is an example where the bounding box is set to position (0.6,0.5) (green dot) and different loc parameters are tested. Because the legend extents outside the bounding box, the loc parameter may be interpreted as "which corner of the legend shall be placed at position given by the 2-tuple bbox_to_anchor argument".

enter image description here

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = 6, 3
fig, axes = plt.subplots(ncols=3)
locs = ["upper left", "lower left", "center right"]
for l, ax in zip(locs, axes.flatten()):
    ax.set_title(l)
    ax.plot([1,2,3],[2,3,1], "b-", label="blue")
    ax.plot([1,2,3],[1,2,1], "r-", label="red")
    ax.legend(loc=l, bbox_to_anchor=(0.6,0.5))
    ax.scatter((0.6),(0.5), s=81, c="limegreen", transform=ax.transAxes)

plt.tight_layout()    
plt.show()

See especially this answer for a detailed explanation and the question What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib? .


If you want to specify the legend position in other coordinates than axes coordinates, you can do so by using the bbox_transform argument. If may make sense to use figure coordinates

ax.legend(bbox_to_anchor=(1,0), loc="lower right",  bbox_transform=fig.transFigure)

It may not make too much sense to use data coordinates, but since you asked for it this would be done via bbox_transform=ax.transData.

Select the first row by group

A simple ddply option:

ddply(test,.(id),function(x) head(x,1))

If speed is an issue, a similar approach could be taken with data.table:

testd <- data.table(test)
setkey(testd,id)
testd[,.SD[1],by = key(testd)]

or this might be considerably faster:

testd[testd[, .I[1], by = key(testd]$V1]

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

How to detect chrome and safari browser (webkit)

/WebKit/.test(navigator.userAgent) — that's it.

How do I set the colour of a label (coloured text) in Java?

One of the disadvantages of using HTML for labels is when you need to write a localizable program (which should work in several languages). You will have issues to change just the translatable text. Or you will have to put the whole HTML code into your translations which is very awkward, I would even say absurd :)

gui_en.properties:

title.text=<html>Text color: <font color='red'>red</font></html>

gui_fr.properties:

title.text=<html>Couleur du texte: <font color='red'>rouge</font></html>

gui_ru.properties:

title.text=<html>???? ??????: <font color='red'>???????</font></html>

Why doesn't Git ignore my specified file?

.gitignore will only ignore files that you haven't already added to your repository.

If you did a git add ., and the file got added to the index, .gitignore won't help you. You'll need to do git rm sites/default/settings.php to remove it, and then it will be ignored.

Does "\d" in regex mean a digit?

\d matches any single digit in most regex grammar styles, including python. Regex Reference

Delete topic in Kafka 0.8.1.1

Add below line in ${kafka_home}/config/server.properties

delete.topic.enable=true

Restart the kafka server with new config:

${kafka_home}/bin/kafka-server-start.sh ~/kafka/config/server.properties

Delete the topics you wish to:

${kafka_home}/bin/kafka-topics.sh --delete  --zookeeper localhost:2181  --topic daemon12

ImageView in circular through xml

you don't need any third-party library.

you can use the ShapeableImageView in the material.

implementation 'com.google.android.material:material:1.2.0'

style.xml

<style name="ShapeAppearanceOverlay.App.CornerSize">
     <item name="cornerSize">50%</item>
</style>

in layout

<com.google.android.material.imageview.ShapeableImageView
     android:layout_width="100dp"
     android:layout_height="100dp"
     app:srcCompat="@drawable/ic_profile"
     app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.App.CornerSize"
/>

you can see this

https://developer.android.com/reference/com/google/android/material/imageview/ShapeableImageView

or this

https://medium.com/android-beginners/shapeableimageview-material-components-for-android-cac6edac2c0d

Changing default shell in Linux

You can change the passwd file directly for the particular user or use the below command

chsh -s /usr/local/bin/bash username

Then log out and log in

Format ints into string of hex

''.join('%02x'%i for i in input)

Rounded Corners Image in Flutter

This is the code that I have used.

Container(
      width: 200.0,
      height: 200.0,
      decoration: BoxDecoration(
        image: DecorationImage(
         image: NetworkImage('Network_Image_Link')),
        color: Colors.blue,
   borderRadius: BorderRadius.all(Radius.circular(25.0)),
      ),
    ),

Thank you!!!

How to make sure that string is valid JSON using JSON.NET

Through Code:

Your best bet is to use parse inside a try-catch and catch exception in case of failed parsing. (I am not aware of any TryParse method).

(Using JSON.Net)

Simplest way would be to Parse the string using JToken.Parse, and also to check if the string starts with { or [ and ends with } or ] respectively (added from this answer):

private static bool IsValidJson(string strInput)
{
    if (string.IsNullOrWhiteSpace(strInput)) { return false;}
    strInput = strInput.Trim();
    if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
        (strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
    {
        try
        {
            var obj = JToken.Parse(strInput);
            return true;
        }
        catch (JsonReaderException jex)
        {
            //Exception in parsing json
            Console.WriteLine(jex.Message);
            return false;
        }
        catch (Exception ex) //some other exception
        {
            Console.WriteLine(ex.ToString());
            return false;
        }
    }
    else
    {
        return false;
    }
}

The reason to add checks for { or [ etc was based on the fact that JToken.Parse would parse the values such as "1234" or "'a string'" as a valid token. The other option could be to use both JObject.Parse and JArray.Parse in parsing and see if anyone of them succeeds, but I believe checking for {} and [] should be easier. (Thanks @RhinoDevel for pointing it out)

Without JSON.Net

You can utilize .Net framework 4.5 System.Json namespace ,like:

string jsonString = "someString";
try
{
    var tmpObj = JsonValue.Parse(jsonString);
}
catch (FormatException fex)
{
    //Invalid json format
    Console.WriteLine(fex);
}
catch (Exception ex) //some other exception
{
    Console.WriteLine(ex.ToString());
}

(But, you have to install System.Json through Nuget package manager using command: PM> Install-Package System.Json -Version 4.0.20126.16343 on Package Manager Console) (taken from here)

Non-Code way:

Usually, when there is a small json string and you are trying to find a mistake in the json string, then I personally prefer to use available on-line tools. What I usually do is:

Proper way to get page content

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array( 'prev_text' >' Previous','post_type' => 'page', 'posts_per_page' => 5, 'paged' => $paged );
$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post();
//get all pages 
the_ID();
the_title();

//if you want specific page of content then write
if(get_the_ID=='11')//make sure to use get_the_ID instead the_ID
{
echo get_the_ID();
the_title();
the_content();
}

endwhile;

//if you want specific page of content then write in loop

  if(get_the_ID=='11')//make sure to use get_the_ID instead the_ID
    {
    echo get_the_ID();
    the_title();
    the_content();
    }

Getting the last argument passed to a shell script

Here is mine solution:

  • pretty portable (all POSIX sh, bash, ksh, zsh) should work
  • does not shift original arguments (shifts a copy).
  • does not use evil eval
  • does not iterate through the whole list
  • does not use external tools

Code:

ntharg() {
    shift $1
    printf '%s\n' "$1"
}
LAST_ARG=`ntharg $# "$@"`

enable cors in .htaccess

This is what worked for me:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

How to print time in format: 2009-08-10 18:17:54.811

None of the solutions on this page worked for me, I mixed them up and made them working with Windows and Visual Studio 2019, Here's How :

#include <Windows.h>
#include <time.h> 
#include <chrono>

static int gettimeofday(struct timeval* tp, struct timezone* tzp) {
    namespace sc = std::chrono;
    sc::system_clock::duration d = sc::system_clock::now().time_since_epoch();
    sc::seconds s = sc::duration_cast<sc::seconds>(d);
    tp->tv_sec = s.count();
    tp->tv_usec = sc::duration_cast<sc::microseconds>(d - s).count();
    return 0;
}

static char* getFormattedTime() {
    static char buffer[26];

    // For Miliseconds
    int millisec;
    struct tm* tm_info;
    struct timeval tv;

    // For Time
    time_t rawtime;
    struct tm* timeinfo;

    gettimeofday(&tv, NULL);

    millisec = lrint(tv.tv_usec / 1000.0);
    if (millisec >= 1000) 
    {
        millisec -= 1000;
        tv.tv_sec++;
    }

    time(&rawtime);
    timeinfo = localtime(&rawtime);

    strftime(buffer, 26, "%Y:%m:%d %H:%M:%S", timeinfo);
    sprintf_s(buffer, 26, "%s.%03d", buffer, millisec);

    return buffer;
}

Result :

2020:08:02 06:41:59.107

2020:08:02 06:41:59.196

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

BIRT, the Eclipse Business Intelligence and Reporting Tool is open source.

BIRT is an open source Eclipse-based reporting system that integrates with your Java/J2EE application to produce compelling reports. BIRT provides core reporting features such as report layout, data access and scripting.

Refresh DataGridView when updating data source

Observablecollection :Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed. You can enumerate over any collection that implements the IEnumerable interface. However, to set up dynamic bindings so that insertions or deletions in the collection update the UI automatically, the collection must implement the INotifyCollectionChanged interface. This interface exposes the CollectionChanged event, an event that should be raised whenever the underlying collection changes.

Observablecollection<ItemState> itemStates = new Observablecollection<ItemState>();

for (int i = 0; i < 10; i++) { 
    itemStates.Add(new ItemState { Id = i.ToString() });
  }
 dataGridView1.DataSource = itemStates;

T-SQL - function with default parameters

you have to call it like this

SELECT dbo.CheckIfSFExists(23, default)

From Technet:

When a parameter of the function has a default value, the keyword DEFAULT must be specified when the function is called in order to retrieve the default value. This behaviour is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value. An exception to this behaviour is when invoking a scalar function by using the EXECUTE statement. When using EXECUTE, the DEFAULT keyword is not required.

Android: textview hyperlink

I hit on the same problem and finally find the working solution.

  1. in the string.xml file, define:

    <string name="textWithHtml">The URL link is &lt;a href="http://www.google.com">Google&lt;/a></string>
    

Replace the "<" less than character with HTML escaped character.

  1. In Java code:

    String text = v.getContext().getString(R.string.textWithHtml);
    textView.setText(Html.fromHtml(text));
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    

And the TextBox will correctly display the text with clickable anchor link

Does an HTTP Status code of 0 have any meaning?

Since iOS 9, you need to add "App Transport Security Settings" to your info.plist file and allow "Allow Arbitrary Loads" before making request to non-secure HTTP web service. I had this issue in one of my app.

How do I find an element position in std::vector?

Take a look at the answers provided for this question: Invalid value for size_t?. Also you can use std::find_if with std::distance to get the index.

std::vector<type>::iterator iter = std::find_if(vec.begin(), vec.end(), comparisonFunc);
size_t index = std::distance(vec.begin(), iter);
if(index == vec.size()) 
{
    //invalid
}

How to find distinct rows with field in list using JPA and Spring?

@Query("SELECT DISTINCT name FROM people WHERE name NOT IN (:names)")
List<String> findNonReferencedNames(@Param("names") List<String> names);

About catching ANY exception

There are multiple ways to do this in particular with Python 3.0 and above

Approach 1

This is simple approach but not recommended because you would not know exactly which line of code is actually throwing the exception:

def bad_method():
    try:
        sqrt = 0**-1
    except Exception as e:
        print(e)

bad_method()

Approach 2

This approach is recommended because it provides more detail about each exception. It includes:

  • Line number for your code
  • File name
  • The actual error in more verbose way

The only drawback is tracback needs to be imported.

import traceback

def bad_method():
    try:
        sqrt = 0**-1
    except Exception:
        print(traceback.print_exc())

bad_method()

How to post data to specific URL using WebClient in C#

I just found the solution and yea it was easier than I thought :)

so here is the solution:

string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1&param2=value2&param3=value3";

using (WebClient wc = new WebClient())
{
    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    string HtmlResult = wc.UploadString(URI, myParameters);
}

it works like charm :)

PHP: How can I determine if a variable has a value that is between two distinct constant values?

You can do this:

if(in_array($value, range(1, 10)) || in_array($value, range(20, 40))) {
   # enter code here
}

Overriding css style?

You just have to reset the values you don't want to their defaults. No need to get into a mess by using !important.

#zoomTarget .slikezamenjanje img {
    max-height: auto;
    padding-right: 0px;
}

Hatting

I think the key datum you are missing is that CSS comes with default values. If you want to override a value, set it back to its default, which you can look up.

For example, all CSS height and width attributes default to auto.

Use Fieldset Legend with bootstrap

That's because Bootstrap by default sets the width of the legend element to 100%. You can fix this by changing your legend.scheduler-border to also use:

legend.scheduler-border {
    width:inherit; /* Or auto */
    padding:0 10px; /* To give a bit of padding on the left and right */
    border-bottom:none;
}

JSFiddle example.

You'll also need to ensure your custom stylesheet is being added after Bootstrap to prevent Bootstrap overriding your styling - although your styles here should have higher specificity.

You may also want to add margin-bottom:0; to it as well to reduce the gap between the legend and the divider.

Matplotlib transparent line plots

After I plotted all the lines, I was able to set the transparency of all of them as follows:

for l in fig_field.gca().lines:
    l.set_alpha(.7)

EDIT: please see Joe's answer in the comments.

diff to output only the file names

From the diff man page:

-q   Report only whether the files differ, not the details of the differences.
-r   When comparing directories, recursively compare any subdirectories found.

Example command:

diff -qr dir1 dir2

Example output (depends on locale):

$ ls dir1 dir2
dir1:
same-file  different  only-1

dir2:
same-file  different  only-2
$ diff -qr dir1 dir2
Files dir1/different and dir2/different differ
Only in dir1: only-1
Only in dir2: only-2

How to convert timestamps to dates in Bash?

some example:

$ date
Tue Mar 22 16:47:06 CST 2016

$ date -d "Tue Mar 22 16:47:06 CST 2016" "+%s"
1458636426

$ date +%s
1458636453

$ date -d @1458636426
Tue Mar 22 16:47:06 CST 2016

$ date --date='@1458636426'
Tue Mar 22 16:47:06 CST 2016


std::wstring VS std::string

1) As mentioned by Greg, wstring is helpful for internationalization, that's when you will be releasing your product in languages other than english

4) Check this out for wide character http://en.wikipedia.org/wiki/Wide_character

Change Primary Key

Sometimes when we do these steps:

 alter table my_table drop constraint my_pk; 
 alter table my_table add constraint my_pk primary key (city_id, buildtime, time);

The last statement fails with

ORA-00955 "name is already used by an existing object"

Oracle usually creates an unique index with the same name my_pk. In such a case you can drop the unique index or rename it based on whether the constraint is still relevant.

You can combine the dropping of primary key constraint and unique index into a single sql statement:

alter table my_table drop constraint my_pk drop index; 

check this: ORA-00955 "name is already used by an existing object"

CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

If there is other content not being shown inside the outer-div (the green box), why not have that content wrapped inside another div, let's call it "content". Have overflow hidden on this new inner-div, but keep overflow visible on the green box.

The only catch is that you will then have to mess around to make sure that the content div doesn't interfere with the positioning of the red box, but it sounds like you should be able to fix that with little headache.

<div id="1" background: #efe; padding: 5px; width: 125px">
    <div id="content" style="overflow: hidden;">
    </div>
    <div id="2" style="position: relative; background: #fee; padding: 2px; width: 100px; height: 100px">
        <div id="3" style="position: absolute; top: 10px; background: #eef; padding: 2px; width: 75px; height: 150px"/>
    </div>
</div>

c# replace \" characters

Try it like this:

Replace("\\\"","");

This will replace occurrences of \" with empty string.

Ex:

string t = "\\\"the dog is my friend\\\"";
t = t.Replace("\\\"","");

This will result in:

the dog is my friend

An error has occured. Please see log file - eclipse juno

C:\path\to\eclipse\eclipse -clean

Then change the working project directory to something different. It should work after that.

replace special characters in a string python

You need to call replace on z and not on str, since you want to replace characters located in the string variable z

removeSpecialChars = z.replace("!@#$%^&*()[]{};:,./<>?\|`~-=_+", " ")

But this will not work, as replace looks for a substring, you will most likely need to use regular expression module re with the sub function:

import re
removeSpecialChars = re.sub("[!@#$%^&*()[]{};:,./<>?\|`~-=_+]", " ", z)

Don't forget the [], which indicates that this is a set of characters to be replaced.

How to provide password to a command that prompts for one in bash?

Secure commands will not allow this, and rightly so, I'm afraid - it's a security hole you could drive a truck through.

If your command does not allow it using input redirection, or a command-line parameter, or a configuration file, then you're going to have to resort to serious trickery.

Some applications will actually open up /dev/tty to ensure you will have a hard time defeating security. You can get around them by temporarily taking over /dev/tty (creating your own as a pipe, for example) but this requires serious privileges and even it can be defeated.

How do I make a Git commit in the past?

Or just use a fake-git-history to generate it for a specific data range.

How can I pass a parameter to a t-sql script?

Two options save vijay.sql

declare
begin
execute immediate 
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||to_char(sysdate,'YYYYMMDD')||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
       sel.tactical_select_executive_flag,
       sel.agent_name,
       res.DMS_RESIGN_CAMPAIGN_CODE,
       pclub.tactical_select_flag
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'
end;
/

The above will generate table names automatically based on sysdate. If you still need to pass as variable, then save vijay.sql as

declare
begin
execute immediate 
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||&1||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
       sel.tactical_select_executive_flag,
       sel.agent_name,
       res.DMS_RESIGN_CAMPAIGN_CODE,
       pclub.tactical_select_flag
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'
end;
/

and then run as sqlplus -s username/password @vijay.sql '20100101'

numbers not allowed (0-9) - Regex Expression in javascript

It is better to rely on regexps like ^[^0-9]+$ rather than on regexps like [a-zA-Z]+ as your app may one day accept user inputs from users speaking language like Polish, where many more characters should be accepted rather than only [a-zA-Z]+. Using ^[^0-9]+$ easily rules out any such undesired side effects.

How to get ER model of database from server with Workbench

I want to enhance Mr. Kamran Ali's answer with pictorial view.

Pictorial View is given step by step:

  1. Go to "Database" Menu option
  2. Select the "Reverse Engineer" option.

enter image description here

  1. A wizard will come. Select from "Stored Connection" and press "Next" button.

enter image description here

  1. Then "Next"..to.."Finish"

Enjoy :)

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

After setting up SSRS 2016, I RDP'd into the server (Windows Server 2012 R2), navigated to the reports URL (https://reports.fakeserver.net/Reports/browse/) and created a folder title FakeFolder; everything appeared to be working fine. I then disconnected from the server, browsed to the same URL, logged in as the same user, and encountered the error below.

The permissions granted to user 'fakeserver\mitchs' are insufficient for performing this operation.

Confused, I tried pretty much every solution suggested on this page and still could not create the same behavior both locally and externally when navigating to the URL and authenticating. I then clicked the ellipsis of FakeFolder, clicked Manage, clicked Security (on the left hand side of the screen), and added myself as a user with full permissions. After disconnecting from the server, I browsed to https://reports.fakeserver.net/Reports/browse/FakeFolder, and was able to view the folder's contents without encountering the permissions error. However, when I clicked home I received the permissions error.

For my purposes, this was good enough as no on else will ever need to browse to the root URL, so I just made a mental note whenever I need to make changes in SSRS to first connect to the server and then browse to the Reports URL.

JavaScript for...in vs for

The choice should be based on the which idiom is best understood.

An array is iterated using:

for (var i = 0; i < a.length; i++)
   //do stuff with a[i]

An object being used as an associative array is iterated using:

for (var key in o)
  //do stuff with o[key]

Unless you have earth shattering reasons, stick to the established pattern of usage.

Passing multiple parameters to pool.map() function in Python

You could use a map function that allows multiple arguments, as does the fork of multiprocessing found in pathos.

>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> 
>>> def add_and_subtract(x,y):
...   return x+y, x-y
... 
>>> res = Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))
>>> res
[(-5, 5), (-2, 6), (1, 7), (4, 8), (7, 9), (10, 10), (13, 11), (16, 12), (19, 13), (22, 14)]
>>> Pool().map(add_and_subtract, *zip(*res))
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

pathos enables you to easily nest hierarchical parallel maps with multiple inputs, so we can extend our example to demonstrate that.

>>> from pathos.multiprocessing import ThreadingPool as TPool
>>> 
>>> res = TPool().amap(add_and_subtract, *zip(*Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))))
>>> res.get()
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

Even more fun, is to build a nested function that we can pass into the Pool. This is possible because pathos uses dill, which can serialize almost anything in python.

>>> def build_fun_things(f, g):
...   def do_fun_things(x, y):
...     return f(x,y), g(x,y)
...   return do_fun_things
... 
>>> def add(x,y):
...   return x+y
... 
>>> def sub(x,y):
...   return x-y
... 
>>> neato = build_fun_things(add, sub)
>>> 
>>> res = TPool().imap(neato, *zip(*Pool().map(neato, range(0,20,2), range(-5,5,1))))
>>> list(res)
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

If you are not able to go outside of the standard library, however, you will have to do this another way. Your best bet in that case is to use multiprocessing.starmap as seen here: Python multiprocessing pool.map for multiple arguments (noted by @Roberto in the comments on the OP's post)

Get pathos here: https://github.com/uqfoundation

Wait Until File Is Completely Written

So, having glanced quickly through some of these and other similar questions I went on a merry goose chase this afternoon trying to solve a problem with two separate programs using a file as a synchronization (and also file save) method. A bit of an unusual situation, but it definitely highlighted for me the problems with the 'check if the file is locked, then open it if it's not' approach.

The problem is this: the file can become locked between the time that you check it and the time you actually open the file. Its really hard to track down the sporadic Cannot copy the file, because it's used by another process error if you aren't looking for it too.

The basic resolution is to just try to open the file inside a catch block so that if its locked, you can try again. That way there is no elapsed time between the check and the opening, the OS does them at the same time.

The code here uses File.Copy, but it works just as well with any of the static methods of the File class: File.Open, File.ReadAllText, File.WriteAllText, etc.

/// <param name="timeout">how long to keep trying in milliseconds</param>
static void safeCopy(string src, string dst, int timeout)
{
    while (timeout > 0)
    {
        try
        {
            File.Copy(src, dst);

            //don't forget to either return from the function or break out fo the while loop
            break;
        }
        catch (IOException)
        {
            //you could do the sleep in here, but its probably a good idea to exit the error handler as soon as possible
        }
        Thread.Sleep(100);

        //if its a very long wait this will acumulate very small errors. 
        //For most things it's probably fine, but if you need precision over a long time span, consider
        //   using some sort of timer or DateTime.Now as a better alternative
        timeout -= 100;
    }
}

Another small note on parellelism: This is a synchronous method, which will block its thread both while waiting and while working on the thread. This is the simplest approach, but if the file remains locked for a long time your program may become unresponsive. Parellelism is too big a topic to go into in depth here, (and the number of ways you could set up asynchronous read/write is kind of preposterous) but here is one way it could be parellelized.

public class FileEx
{
    public static async void CopyWaitAsync(string src, string dst, int timeout, Action doWhenDone)
    {
        while (timeout > 0)
        {
            try
            {
                File.Copy(src, dst);
                doWhenDone();
                break;
            }
            catch (IOException) { }

            await Task.Delay(100);
            timeout -= 100;
        }
    }

    public static async Task<string> ReadAllTextWaitAsync(string filePath, int timeout)
    {
        while (timeout > 0)
        {
            try {
                return File.ReadAllText(filePath);
            }
            catch (IOException) { }

            await Task.Delay(100);
            timeout -= 100;
        }
        return "";
    }

    public static async void WriteAllTextWaitAsync(string filePath, string contents, int timeout)
    {
        while (timeout > 0)
        {
            try
            {
                File.WriteAllText(filePath, contents);
                return;
            }
            catch (IOException) { }

            await Task.Delay(100);
            timeout -= 100;
        }
    }
}

And here is how it could be used:

public static void Main()
{
    test_FileEx();
    Console.WriteLine("Me First!");
}    

public static async void test_FileEx()
{
    await Task.Delay(1);

    //you can do this, but it gives a compiler warning because it can potentially return immediately without finishing the copy
    //As a side note, if the file is not locked this will not return until the copy operation completes. Async functions run synchronously
    //until the first 'await'. See the documentation for async: https://msdn.microsoft.com/en-us/library/hh156513.aspx
    CopyWaitAsync("file1.txt", "file1.bat", 1000);

    //this is the normal way of using this kind of async function. Execution of the following lines will always occur AFTER the copy finishes
    await CopyWaitAsync("file1.txt", "file1.readme", 1000);
    Console.WriteLine("file1.txt copied to file1.readme");

    //The following line doesn't cause a compiler error, but it doesn't make any sense either.
    ReadAllTextWaitAsync("file1.readme", 1000);

    //To get the return value of the function, you have to use this function with the await keyword
    string text = await ReadAllTextWaitAsync("file1.readme", 1000);
    Console.WriteLine("file1.readme says: " + text);
}

//Output:
//Me First!
//file1.txt copied to file1.readme
//file1.readme says: Text to be duplicated!

hibernate: LazyInitializationException: could not initialize proxy

I think Piko means in his response that there is the hbm file. I have a file called Tax.java. The mapping information are saved in the hbm (=hibernate mapping) file. In the class tag there is a property called lazy. Set that property to true. The following hbm example shows a way to set the lazy property to false.

` id ...'

If you are using Annotations instead look in the hibernate documenation. http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/

I hope that helped.

What are carriage return, linefeed, and form feed?

Carriage return means to return to the beginning of the current line without advancing downward. The name comes from a printer's carriage, as monitors were rare when the name was coined. This is commonly escaped as \r, abbreviated CR, and has ASCII value 13 or 0x0D.

Linefeed means to advance downward to the next line; however, it has been repurposed and renamed. Used as "newline", it terminates lines (commonly confused with separating lines). This is commonly escaped as \n, abbreviated LF or NL, and has ASCII value 10 or 0x0A. CRLF (but not CRNL) is used for the pair \r\n.

Form feed means advance downward to the next "page". It was commonly used as page separators, but now is also used as section separators. (It's uncommonly used in source code to divide logically independent functions or groups of functions.) Text editors can use this character when you "insert a page break". This is commonly escaped as \f, abbreviated FF, and has ASCII value 12 or 0x0C.


As control characters, they may be interpreted in various ways.

The most common difference (and probably the only one worth worrying about) is lines end with CRLF on Windows, NL on Unix-likes, and CR on older Macs (the situation has changed with OS X to be like Unix). Note the shift in meaning from LF to NL, for the exact same character, gives the differences between Windows and Unix. (Windows is, of course, newer than Unix, so it didn't adopt this semantic shift. I don't know the history of Macs using CR.) Many text editors can read files in any of these three formats and convert between them, but not all utilities can.

Form feed is a bit more interesting (even though less commonly used directly), and with the usual definition of page separator, it can only come between lines (e.g. after the newline sequence of NL, CRLF, or CR) or at the start or end of the file.

$(document).ready equivalent without jQuery

This was a good https://stackoverflow.com/a/11810957/185565 poor man's solution. One comment considered a counter to bail out in case of emergency. This is my modification.

function doTheMagic(counter) {
  alert("It worked on " + counter);
}

// wait for document ready then call handler function
var checkLoad = function(counter) {
  counter++;
  if (document.readyState != "complete" && counter<1000) {
    var fn = function() { checkLoad(counter); };
    setTimeout(fn,10);
  } else doTheMagic(counter);
};
checkLoad(0);

How to create a file in a directory in java?

When you write to the file via file output stream, the file will be created automatically. but make sure all necessary directories ( folders) are created.

    String absolutePath = ...
    try{
       File file = new File(absolutePath);
       file.mkdirs() ;
       //all parent folders are created
       //now the file will be created when you start writing to it via FileOutputStream.
      }catch (Exception e){
        System.out.println("Error : "+ e.getmessage());
       }

What is the most efficient way to loop through dataframes with pandas?

Pandas is based on NumPy arrays. The key to speed with NumPy arrays is to perform your operations on the whole array at once, never row-by-row or item-by-item.

For example, if close is a 1-d array, and you want the day-over-day percent change,

pct_change = close[1:]/close[:-1]

This computes the entire array of percent changes as one statement, instead of

pct_change = []
for row in close:
    pct_change.append(...)

So try to avoid the Python loop for i, row in enumerate(...) entirely, and think about how to perform your calculations with operations on the entire array (or dataframe) as a whole, rather than row-by-row.

jQuery Validate Required Select

<select class="design" id="sel" name="subject">
   <option value="0">- Please Select -</option>
   <option value="1"> Example1 </option>
   <option value="2"> Example2 </option>
   <option value="3"> Example3 </option>
   <option value="4"> Example4 </option>
</select>
<label class="error" id="select_error" style="color:#FC2727">
   <b> Warning : You have to Select One Item.</b>
</label>
<input type="submit" name="sub" value="Gönder" class="">

JQuery :

jQuery(function() {  
    jQuery('.error').hide(); // Hide Warning Label. 
    jQuery("input[name=sub]").on("click", function() {
        var returnvalue;
        if(jQuery("select[name=subject]").val() == 0) {
            jQuery("label#select_error").show(); // show Warning 
            jQuery("select#sel").focus();  // Focus the select box      
            returnvalue=false;   
        }
        return returnvalue;
    });
});  // you can change jQuery with $

PHP Function Comments

You must check this: Docblock Comment standards

http://pear.php.net/manual/en/standards.sample.php

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

Could not load file or assembly 'Microsoft.ReportViewer.Webforms' or

Could not load file or assembly 'Microsoft.ReportViewer.Common'

This issue occured for me in Visual studio 2015.

Reason:

the reference for Microsoft.ReportViewer.Webforms dll is missing.

Possible Fix

Step1:

To add "Microsoft.ReportViewer.Webforms.dll" to the solution.

Navigate to Nuget Package Manager Console as

"Tools-->NugetPackageManager-->Package Manager Console".

Then enter the following command in console as below

PM>Install-Package Microsoft.ReportViewer.Runtime.WebForms

Then it will install the Reportviewer.webforms dll in "..\packages\Microsoft.ReportViewer.Runtime.WebForms.12.0.2402.15\lib" (Your project folder path)

and ReportViewer.Runtime.Common dll in "..\packages\Microsoft.ReportViewer.Runtime.Common.12.0.2402.15\lib". (Your project folder path)

Step2:-

Remove the existing reference of "Microsoft.ReportViewer.WebForms". we need to refer these dll files in our Solution as "Right click Solution >References-->Add reference-->browse ". Add both the dll files from the above paths.

Step3:

Change the web.Config File to point out to Visual Studio 2015. comment out both the Microsoft.ReportViewer.WebForms and Microsoft.ReportViewer.Common version 11.0.0.0 and Uncomment both the Microsoft.ReportViewer.WebForms and Microsoft.ReportViewer.Common Version=12.0.0.0. as attached in screenshot.

Microsoft.ReportViewer.Webforms/Microsoft.ReportViewer.Common

Also refer the link below.

Could not load file or assembly 'Microsoft.ReportViewer.WebForms'

VBA - Range.Row.Count

This works for me especially in pivots table filtering when I want the count of cells with data on a filtered column. Reduce k accordingly (k - 1) if you have a header row for filtering:

k = Sheets("Sheet1").Range("$A:$A").SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeConstants).Count

Computing cross-correlation function?

To cross-correlate 1d arrays use numpy.correlate.

For 2d arrays, use scipy.signal.correlate2d.

There is also scipy.stsci.convolve.correlate2d.

There is also matplotlib.pyplot.xcorr which is based on numpy.correlate.

See this post on the SciPy mailing list for some links to different implementations.

Edit: @user333700 added a link to the SciPy ticket for this issue in a comment.

What does "select 1 from" do?

The construction is usually used in "existence" checks

if exists(select 1 from customer_table where customer = 'xxx')

or

if exists(select * from customer_table where customer = 'xxx')

Both constructions are equivalent. In the past people said the select * was better because the query governor would then use the best indexed column. This has been proven not true.

What's the purpose of META-INF?

META-INF in Maven

In Maven the META-INF folder is understood because of the Standard Directory Layout, which by name convention package your project resources within JARs: any directories or files placed within the ${basedir}/src/main/resources directory are packaged into your JAR with the exact same structure starting at the base of the JAR. The Folder ${basedir}/src/main/resources/META-INF usually contains .properties files while in the jar contains a generated MANIFEST.MF, pom.properties, the pom.xml, among other files. Also frameworks like Spring use classpath:/META-INF/resources/ to serve web resources. For more information see How do I add resources to my Maven Project.

SQL Server principal "dbo" does not exist,

another way of doing it

ALTER AUTHORIZATION 
ON DATABASE::[DatabaseName]
TO [A Suitable Login];

Android Studio AVD - Emulator: Process finished with exit code 1

Android make the default avd files in the C:\Users\[USERNAME]\.android directory. Just make sure you copy the avd folder from this directory C:\Users\[USERNAME]\.android to C:\Android\.android. My problem was resolved after doing this.

Can you pass parameters to an AngularJS controller on creation?

I found passing variables from $routeProvider usefull.

For example, you use one controller MyController for multiple screens, passing some very important variable "mySuperConstant" inside.

Use that simple structure:

Router:

$routeProvider
            .when('/this-page', {
                templateUrl: 'common.html',
                controller: MyController,
                mySuperConstant: "123"
            })
            .when('/that-page', {
                templateUrl: 'common.html',
                controller: MyController,
                mySuperConstant: "456"
            })
            .when('/another-page', {
                templateUrl: 'common.html',
                controller: MyController,
                mySuperConstant: "789"
            })

MyController:

    MyController: function ($scope, $route) {
        var mySuperConstant: $route.current.mySuperConstant;
        alert(mySuperConstant);

    }

count (non-blank) lines-of-code in bash

Here's a Bash script that counts the lines of code in a project. It traverses a source tree recursively, and it excludes blank lines and single line comments that use "//".

# $excluded is a regex for paths to exclude from line counting
excluded="spec\|node_modules\|README\|lib\|docs\|csv\|XLS\|json\|png"

countLines(){
  # $total is the total lines of code counted
  total=0
  # -mindepth exclues the current directory (".")
  for file in `find . -mindepth 1 -name "*.*" |grep -v "$excluded"`; do
    # First sed: only count lines of code that are not commented with //
    # Second sed: don't count blank lines
    # $numLines is the lines of code
    numLines=`cat $file | sed '/\/\//d' | sed '/^\s*$/d' | wc -l`

    # To exclude only blank lines and count comment lines, uncomment this:
    #numLines=`cat $file | sed '/^\s*$/d' | wc -l`

    total=$(($total + $numLines))
    echo "  " $numLines $file
  done
  echo "  " $total in total
}

echo Source code files:
countLines
echo Unit tests:
cd spec
countLines

Here's what the output looks like for my project:

Source code files:
   2 ./buildDocs.sh
   24 ./countLines.sh
   15 ./css/dashboard.css
   53 ./data/un_population/provenance/preprocess.js
   19 ./index.html
   5 ./server/server.js
   2 ./server/startServer.sh
   24 ./SpecRunner.html
   34 ./src/computeLayout.js
   60 ./src/configDiff.js
   18 ./src/dashboardMirror.js
   37 ./src/dashboardScaffold.js
   14 ./src/data.js
   68 ./src/dummyVis.js
   27 ./src/layout.js
   28 ./src/links.js
   5 ./src/main.js
   52 ./src/processActions.js
   86 ./src/timeline.js
   73 ./src/udc.js
   18 ./src/wire.js
   664 in total
Unit tests:
   230 ./ComputeLayoutSpec.js
   134 ./ConfigDiffSpec.js
   134 ./ProcessActionsSpec.js
   84 ./UDCSpec.js
   149 ./WireSpec.js
   731 in total

Enjoy! --Curran

Select records from today, this week, this month php mysql

Assuming your date column is an actual MySQL date column:

SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 DAY) ORDER BY score DESC;        
SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 WEEK) ORDER BY score DESC;
SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 MONTH) ORDER BY score DESC;

How can I convert a DateTime to an int?

Do you want an 'int' that looks like 20110425171213? In which case you'd be better off ToString with the appropriate format (something like 'yyyyMMddHHmmss') and then casting the string to an integer (or a long, unsigned int as it will be way more than 32 bits).

If you want an actual numeric value (the number of seconds since the year 0) then that's a very different calculation, e.g.

result = second
result += minute * 60
result += hour * 60 * 60
result += day * 60 * 60 * 24 

etc.

But you'd be better off using Ticks.

Running CMake on Windows

The default generator for Windows seems to be set to NMAKE. Try to use:

cmake -G "MinGW Makefiles"

Or use the GUI, and select MinGW Makefiles when prompted for a generator. Don't forget to cleanup the directory where you tried to run CMake, or delete the cache in the GUI. Otherwise, it will try again with NMAKE.

Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function

The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts

  • Talk to the server developer for more info. You can't get more info directly.
  • Verify your arguments into the call (values). Look for anything you might think could cause a problem for the server process. The process should not die and should return you a better code, but bugs happen there also.
  • Could be intermittent, like if the server database goes down. May be worth trying at another time.

The endpoint reference (EPR) for the Operation not found is

This error is coming because while calling the service, it is not getting the WSDL file of your service.

Just check whether WSDL file of your service is there--> run server and from browser run axis 2 apps on local host and check the deployed services and click on your service, then it shows WSDL file of your service.....or check the service path in your client file.

I hope it may help you to resolve the problem.

Commands out of sync; you can't run this command now

Create two connections, use both separately

$mysqli = new mysqli("localhost", "Admin", "dilhdk", "SMS");

$conn = new mysqli("localhost", "Admin", "dilhdk", "SMS"); 

TypeScript sorting an array

Great answer Sohnee. Would like to add that if you have an array of objects and you wish to sort by key then its almost the same, this is an example of one that can sort by both date(number) or title(string):

    if (sortBy === 'date') {
        return n1.date - n2.date
    } else {
        if (n1.title > n2.title) {
           return 1;
        }
        if (n1.title < n2.title) {
            return -1;
        }
        return 0;
    }

Could also make the values inside as variables n1[field] vs n2[field] if its more dynamic, just keep the diff between strings and numbers.

Android ACTION_IMAGE_CAPTURE Intent

I know this has been answered before but I know a lot of people get tripped up on this, so I'm going to add a comment.

I had this exact same problem happen on my Nexus One. This was from the file not existing on the disk before the camera app started. Therefore, I made sure that the file existing before started the camera app. Here's some sample code that I used:

String storageState = Environment.getExternalStorageState();
        if(storageState.equals(Environment.MEDIA_MOUNTED)) {

            String path = Environment.getExternalStorageDirectory().getName() + File.separatorChar + "Android/data/" + MainActivity.this.getPackageName() + "/files/" + md5(upc) + ".jpg";
            _photoFile = new File(path);
            try {
                if(_photoFile.exists() == false) {
                    _photoFile.getParentFile().mkdirs();
                    _photoFile.createNewFile();
                }

            } catch (IOException e) {
                Log.e(TAG, "Could not create file.", e);
            }
            Log.i(TAG, path);

            _fileUri = Uri.fromFile(_photoFile);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE );
            intent.putExtra( MediaStore.EXTRA_OUTPUT, _fileUri);
            startActivityForResult(intent, TAKE_PICTURE);
        }   else {
            new AlertDialog.Builder(MainActivity.this)
            .setMessage("External Storeage (SD Card) is required.\n\nCurrent state: " + storageState)
            .setCancelable(true).create().show();
        }

I first create a unique (somewhat) file name using an MD5 hash and put it into the appropriate folder. I then check to see if it exists (shouldn't, but its good practice to check anyway). If it does not exist, I get the parent dir (a folder) and create the folder hierarchy up to it (therefore if the folders leading up to the location of the file don't exist, they will after this line. Then after that I create the file. Once the file is created I get the Uri and pass it to the intent and then the OK button works as expected and all is golden.

Now,when the Ok button is pressed on the camera app, the file will be present in the given location. In this example it would be /sdcard/Android/data/com.example.myapp/files/234asdioue23498ad.jpg

There is no need to copy the file in the "onActivityResult" as posted above.

Change width of select tag in Twitter Bootstrap

For me Pawan's css class combined with display: inline-block (so the selects don't stack) works best. And I wrap it in a media-query, so it stays Mobile Friendly:

@media (min-width: $screen-xs) {

    .selectwidthauto {
         width:auto !important;
         display: inline-block;
    }

}

selecting an entire row based on a variable excel vba

You need to add quotes. VBA is translating

Rows(copyToRow & ":" & copyToRow).Select`

into

 Rows(52:52).Select

Try changing

Rows(""" & copyToRow & ":" & copyToRow & """).Select

print spaces with String.format()

int numberOfSpaces = 3;
String space = String.format("%"+ numberOfSpaces +"s", " ");

The simplest possible JavaScript countdown timer?

You can easily create a timer functionality by using setInterval.Below is the code which you can use it to create the timer.

http://jsfiddle.net/ayyadurai/GXzhZ/1/

_x000D_
_x000D_
window.onload = function() {_x000D_
  var minute = 5;_x000D_
  var sec = 60;_x000D_
  setInterval(function() {_x000D_
    document.getElementById("timer").innerHTML = minute + " : " + sec;_x000D_
    sec--;_x000D_
    if (sec == 00) {_x000D_
      minute --;_x000D_
      sec = 60;_x000D_
      if (minute == 0) {_x000D_
        minute = 5;_x000D_
      }_x000D_
    }_x000D_
  }, 1000);_x000D_
}
_x000D_
Registration closes in <span id="timer">05:00<span> minutes!
_x000D_
_x000D_
_x000D_

Adding <script> to WordPress in <head> element

I believe that codex.wordpress.org is your best reference to handle this task very well depends on your needs

check out these two pages on WordPress Codex:

wp_enqueue_script

wp_enqueue_style

How to use WebRequest to POST some data and read response?

Here's an example of posting to a web service using the HttpWebRequest and HttpWebResponse objects.

StringBuilder sb = new StringBuilder();
    string query = "?q=" + latitude + "%2C" + longitude + "&format=xml&key=xxxxxxxxxxxxxxxxxxxxxxxx";
    string weatherservice = "http://api.worldweatheronline.com/free/v1/marine.ashx" + query;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(weatherservice);
    request.Referer = "http://www.yourdomain.com";
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream);
    Char[] readBuffer = new Char[256];
    int count = reader.Read(readBuffer, 0, 256);

    while (count > 0)
    {
        String output = new String(readBuffer, 0, count);
        sb.Append(output);
        count = reader.Read(readBuffer, 0, 256);
    }
    string xml = sb.ToString();

How to set or change the default Java (JDK) version on OS X?

First find out where do you store the environment variables-

  1. emacs
  2. bash_profile
  3. zshrc file

Steps to Set up the environment variable :-

  1. Download the jdk from JAVA

  2. install it by double click

  3. Now set-up environment variables in your file

    a. For emacs.profile you can use this link OR see the screenshot below

enter image description here

b. For ZSH profile setup -

1. export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home

2. source ~/.zshrc - Restart zshrc to reflect the changes.

3. echo $JAVA_HOME - make sure path is set up properly 
   ----> /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home

4. java -version 

   -->  java version "1.8.0_112"  Java(TM) SE Runtime Environment (build 1.8.0_112-b16)Java HotSpot(TM) 64-Bit Server VM (build 25.112-b16, mixed mode)

All set Now you can easily upgrade or degrade the JAVA version..

How do I install Keras and Theano in Anaconda Python on Windows?

install by this command given below conda install -c conda-forge keras

this is error "CondaError: Cannot link a source that does not exist" ive get in win 10. for your error put this command in your command line.

conda update conda

this work for me .

cannot connect to pc-name\SQLEXPRESS

I'm Running Windows 10 and this worked for me:

  1. Open services by searching in the toolbar for Services.
  2. Right click SQL Server (SQLEXPESS)
  3. Go To Properties - Log On
  4. Check Local System Account & Allow service to interact with desktop.
  5. Apply and restart service.
  6. I was then able to connect

How to check if a std::string is set or not?

You can't; at least not the same way you can test whether a pointer is NULL.

A std::string object is always initialized and always contains a string; its contents by default are an empty string ("").

You can test for emptiness (using s.size() == 0 or s.empty()).

Array copy values to keys in PHP

$final_array = array_combine($a, $a);

Reference: http://php.net/array-combine

P.S. Be careful with source array containing duplicated keys like the following:

$a = ['one','two','one'];

Note the duplicated one element.

ln (Natural Log) in Python

Here is the correct implementation using numpy (np.log() is the natural logarithm)

import numpy as np
p = 100
r = 0.06 / 12
FV = 4000

n = np.log(1 + FV * r/ p) / np.log(1 + r)

print ("Number of periods = " + str(n))

Output:

Number of periods = 36.55539635919235

How to consume REST in Java

JAX-RS but you can also use regular DOM that comes with standard Java

Activity has leaked window that was originally added

The issue according to me is you are trying to call a dialog right after an activity is getting finished so according me what you can do is give some delay using Handler and you issue will be solved for eg:

 Handler handler=new Handler();
     handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                     dialog.show();
                     //or
                     dialog.dismiss();

                }
            },100);

What does android:layout_weight mean?

Combining both answers from

Flo & rptwsthi and roetzi,

Do remember to change your layout_width=0dp/px, else the layout_weight behaviour will act reversely with biggest number occupied the smallest space and lowest number occupied the biggest space.

Besides, some weights combination will caused some layout cannot be shown (since it over occupied the space).

Beware of this.

What should be the package name of android app?

Visit https://developers.google.com/mobile/add and try to fill "Android package name". In some cases it can write error: "Invalid Android package name".

In https://developer.android.com/studio/build/application-id.html it is written:

And although the application ID looks like a traditional Java package name, the naming rules for the application ID are a bit more restrictive:

  • It must have at least two segments (one or more dots).
  • Each segment must start with a letter.
  • All characters must be alphanumeric or an underscore [a-zA-Z0-9_].

So, "0com.example.app" and "com.1example.app" are errors.

How to change string into QString?

If compiled with STL compatibility, QString has a static method to convert a std::string to a QString:

std::string str = "abc";
QString qstr = QString::fromStdString(str);

Remove all whitespace from C# string with regex

Fastest and general way to do this (line terminators, tabs will be processed as well). Regex powerful facilities don't really needed to solve this problem, but Regex can decrease performance.

                       new string
                           (stringToRemoveWhiteSpaces
                                .Where
                                (
                                    c => !char.IsWhiteSpace(c)
                                )
                                .ToArray<char>()
                           )

OR

                       new string
                           (stringToReplaceWhiteSpacesWithSpace
                                .Select
                                (
                                    c => char.IsWhiteSpace(c) ? ' ' : c
                                )
                                .ToArray<char>()
                           )

How to close an iframe within iframe itself

"Closing" the current iFrame is not possible but you can tell the parent to manipulate the dom and make it invisible.

In IFrame:

parent.closeIFrame();

In parent:

function closeIFrame(){
     $('#youriframeid').remove();
}

How to use SVG markers in Google Maps API v3

You need to pass optimized: false.

E.g.

var img = { url: 'img/puff.svg', scaledSide: new google.maps.Size(5, 5) };
new google.maps.Marker({position: this.mapOptions.center, map: this.map, icon: img, optimized: false,});

Without passing optimized: false, my svg appeared as a static image.

How to change a Git remote on Heroku

This worked for me:

git remote set-url heroku <repo git>

This replacement old url heroku.

You can check with:

git remote -v

How to iterate for loop in reverse order in swift?

Swift 4.0

for i in stride(from: 5, to: 0, by: -1) {
    print(i) // 5,4,3,2,1
}

If you want to include the to value:

for i in stride(from: 5, through: 0, by: -1) {
    print(i) // 5,4,3,2,1,0
}

Python List vs. Array - when to use?

It's a trade off !

pros of each one :

list

  • flexible
  • can be heterogeneous

array (ex: numpy array)

  • array of uniform values
  • homogeneous
  • compact (in size)
  • efficient (functionality and speed)
  • convenient

VB.NET Inputbox - How to identify when the Cancel Button is pressed?

Try this. I've tried the solution and it works.

Dim ask = InputBox("")
If ask.Length <> 0 Then
   // your code
Else
   // cancel or X Button 
End If

How does one parse XML files?

Use XmlTextReader, XmlReader, XmlNodeReader and the System.Xml.XPath namespace. And (XPathNavigator, XPathDocument, XPathExpression, XPathnodeIterator).

Usually XPath makes reading XML easier, which is what you might be looking for.

jQuery set radio button

In my case, radio button value is fetched from database and then set into the form. Following code works for me.

$("input[name=name_of_radio_button_fields][value=" + saved_value_comes_from_database + "]").prop('checked', true);

align right in a table cell with CSS

Use

text-align: right

The text-align CSS property describes how inline content like text is aligned in its parent block element. text-align does not control the alignment of block elements itself, only their inline content.

See

text-align

<td class='alnright'>text to be aligned to right</td>

<style>
    .alnright { text-align: right; }
</style>

How to split a string by spaces in a Windows batch file?

@echo off

:: read a file line by line
for /F  %%i in ('type data.csv') do (
    echo %%i
    :: and we extract four tokens, ; is the delimiter.
    for /f "tokens=1,2,3,4 delims=;" %%a in ("%%i") do (
        set first=%%a&set second=%%b&set third=%%c&set fourth=%%d
        echo %first% and %second% and %third% and %fourth% 
    )
)

How can I make the computer beep in C#?

I just came across this question while searching for the solution for myself. You might consider calling the system beep function by running some kernel32 stuff.

using System.Runtime.InteropServices;
        [DllImport("kernel32.dll")]
        public static extern bool Beep(int freq, int duration);

        public static void TestBeeps()
        {
            Beep(1000, 1600); //low frequency, longer sound
            Beep(2000, 400); //high frequency, short sound
        }

This is the same as you would run powershell:

[console]::beep(1000, 1600)
[console]::beep(2000, 400)

How to remove "onclick" with JQuery?

Removing onclick property

Suppose you added your click event inline, like this :

<button id="myButton" onclick="alert('test')">Married</button>

Then, you can remove the event like this :

$("#myButton").prop('onclick', null); // Removes 'onclick' property if found

Removing click event listeners

Suppose you added your click event by defining an event listener, like this :

$("button").on("click", function() { alert("clicked!"); });

... or like this:

$("button").click(function() { alert("clicked!"); });

Then, you can remove the event like this :

$("#myButton").off('click');          // Removes other events if found

Removing both

If you're uncertain how your event has been added, you can combine both, like this :

$("#myButton").prop('onclick', null)  // Removes 'onclick' property if found
              .off('click');          // Removes other events if found

An exception of type 'System.NullReferenceException' occurred in myproject.DLL but was not handled in user code

It means you have a null reference somewhere in there. Can you debug the app and stop the debugger when it gets here and investigate? Probably img1 is null or ConfigurationManager.AppSettings.Get("Url") is returning null.

How to use XPath in Python?

You can use the simple soupparser from lxml

Example:

from lxml.html.soupparser import fromstring

tree = fromstring("<a>Find me!</a>")
print tree.xpath("//a/text()")

How to read AppSettings values from a .json file in ASP.NET Core

First off: The assembly name and namespace of Microsoft.Framework.ConfigurationModel has changed to Microsoft.Framework.Configuration. So you should use: e.g.

"Microsoft.Framework.Configuration.Json": "1.0.0-beta7"

as a dependency in project.json. Use beta5 or 6 if you don't have 7 installed. Then you can do something like this in Startup.cs.

public IConfiguration Configuration { get; set; }

public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
     var configurationBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
        .AddJsonFile("config.json")
        .AddEnvironmentVariables();
     Configuration = configurationBuilder.Build();
}

If you then want to retrieve a variable from the config.json you can get it right away using:

public void Configure(IApplicationBuilder app)
{
    // Add .Value to get the token string
    var token = Configuration.GetSection("AppSettings:token");
    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("This is a token with key (" + token.Key + ") " + token.Value);
    });
}

or you can create a class called AppSettings like this:

public class AppSettings
{
    public string token { get; set; }
}

and configure the services like this:

public void ConfigureServices(IServiceCollection services)
{       
    services.AddMvc();

    services.Configure<MvcOptions>(options =>
    {
        //mvc options
    });

    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}

and then access it through e.g. a controller like this:

public class HomeController : Controller
{
    private string _token;

    public HomeController(IOptions<AppSettings> settings)
    {
        _token = settings.Options.token;
    }
}

Get resultset from oracle stored procedure

Hi I know this was asked a while ago but I've just figured this out and it might help someone else. Not sure if this is exactly what you're looking for but this is how I call a stored proc and view the output using SQL Developer.
In SQL Developer when viewing the proc, right click and choose 'Run' or select Ctrl+F11 to bring up the Run PL/SQL window. This creates a template with the input and output params which you need to modify. My proc returns a sys_refcursor. The tricky part for me was declaring a row type that is exactly equivalent to the select stmt / sys_refcursor being returned by the proc:

DECLARE
  P_CAE_SEC_ID_N NUMBER;
  P_FM_SEC_CODE_C VARCHAR2(200);
  P_PAGE_INDEX NUMBER;
  P_PAGE_SIZE NUMBER;
  v_Return sys_refcursor;
  type t_row is record (CAE_SEC_ID NUMBER,FM_SEC_CODE VARCHAR2(7),rownum number, v_total_count number);
  v_rec t_row;

BEGIN
  P_CAE_SEC_ID_N := NULL;
  P_FM_SEC_CODE_C := NULL;
  P_PAGE_INDEX := 0;
  P_PAGE_SIZE := 25;

  CAE_FOF_SECURITY_PKG.GET_LIST_FOF_SECURITY(
    P_CAE_SEC_ID_N => P_CAE_SEC_ID_N,
    P_FM_SEC_CODE_C => P_FM_SEC_CODE_C,
    P_PAGE_INDEX => P_PAGE_INDEX,
    P_PAGE_SIZE => P_PAGE_SIZE,
    P_FOF_SEC_REFCUR => v_Return
  );
  -- Modify the code to output the variable
  -- DBMS_OUTPUT.PUT_LINE('P_FOF_SEC_REFCUR = ');
  loop
    fetch v_Return into v_rec;
    exit when v_Return%notfound;
    DBMS_OUTPUT.PUT_LINE('sec_id = ' || v_rec.CAE_SEC_ID || 'sec code = ' ||v_rec.FM_SEC_CODE);
  end loop;

END;