Programs & Examples On #Io redirection

I/O redirection is used in shell scripting. This feature enables to take the output of a command and redirect it as an input for another command. Or command can take the input from a file instead of the keyboard. The whole process helps connect commands in various ways.

How to redirect both stdout and stderr to a file

The simplest syntax to redirect both is:

command &> logfile

If you want to append to the file instead of overwrite:

command &>> logfile

How do I capture all of my compiler's output to a file?

Assume you want to hilight warning and error from build ouput:

make |& grep -E "warning|error"

How to redirect and append both stdout and stderr to a file with Bash?

There are two ways to do this, depending on your Bash version.

The classic and portable (Bash pre-4) way is:

cmd >> outfile 2>&1

A nonportable way, starting with Bash 4 is

cmd &>> outfile

(analog to &> outfile)

For good coding style, you should

  • decide if portability is a concern (then use classic way)
  • decide if portability even to Bash pre-4 is a concern (then use classic way)
  • no matter which syntax you use, not change it within the same script (confusion!)

If your script already starts with #!/bin/sh (no matter if intended or not), then the Bash 4 solution, and in general any Bash-specific code, is not the way to go.

Also remember that Bash 4 &>> is just shorter syntax — it does not introduce any new functionality or anything like that.

The syntax is (beside other redirection syntax) described here: http://bash-hackers.org/wiki/doku.php/syntax/redirection#appending_redirected_output_and_error_output

Redirect all output to file in Bash

All POSIX operating systems have 3 streams: stdin, stdout, and stderr. stdin is the input, which can accept the stdout or stderr. stdout is the primary output, which is redirected with >, >>, or |. stderr is the error output, which is handled separately so that any exceptions do not get passed to a command or written to a file that it might break; normally, this is sent to a log of some kind, or dumped directly, even when the stdout is redirected. To redirect both to the same place, use:

command &> /some/file

EDIT: thanks to Zack for pointing out that the above solution is not portable--use instead:

*command* > file 2>&1 

If you want to silence the error, do:

*command* 2> /dev/null

Redirect stderr and stdout in Bash

"Easiest" way (bash4 only): ls * 2>&- 1>&-.

How to pass password to scp?

You can script it with a tool like expect (there are handy bindings too, like Pexpect for Python).

Redirect stderr to stdout in C shell

As paxdiablo said you can use >& to redirect both stdout and stderr. However if you want them separated you can use the following:

(command > stdoutfile) >& stderrfile

...as indicated the above will redirect stdout to stdoutfile and stderr to stderrfile.

UTF-8 output from PowerShell

Not an expert on encoding, but after reading these...

... it seems fairly clear that the $OutputEncoding variable only affects data piped to native applications.

If sending to a file from withing PowerShell, the encoding can be controlled by the -encoding parameter on the out-file cmdlet e.g.

write-output "hello" | out-file "enctest.txt" -encoding utf8

Nothing else you can do on the PowerShell front then, but the following post may well help you:.

Redirecting Output from within Batch file

There is a cool little program you can use to redirect the output to a file and the console

some_command  ^|  TEE.BAT  [ -a ]  filename 

_x000D_
_x000D_
@ECHO OFF_x000D_
:: Check Windows version_x000D_
IF NOT "%OS%"=="Windows_NT" GOTO Syntax_x000D_
_x000D_
:: Keep variables local_x000D_
SETLOCAL_x000D_
_x000D_
:: Check command line arguments_x000D_
SET Append=0_x000D_
IF /I [%1]==[-a] (_x000D_
 SET Append=1_x000D_
 SHIFT_x000D_
)_x000D_
IF     [%1]==[] GOTO Syntax_x000D_
IF NOT [%2]==[] GOTO Syntax_x000D_
_x000D_
:: Test for invalid wildcards_x000D_
SET Counter=0_x000D_
FOR /F %%A IN ('DIR /A /B %1 2^>NUL') DO CALL :Count "%%~fA"_x000D_
IF %Counter% GTR 1 (_x000D_
 SET Counter=_x000D_
 GOTO Syntax_x000D_
)_x000D_
_x000D_
:: A valid filename seems to have been specified_x000D_
SET File=%1_x000D_
_x000D_
:: Check if a directory with the specified name exists_x000D_
DIR /AD %File% >NUL 2>NUL_x000D_
IF NOT ERRORLEVEL 1 (_x000D_
 SET File=_x000D_
 GOTO Syntax_x000D_
)_x000D_
_x000D_
:: Specify /Y switch for Windows 2000 / XP COPY command_x000D_
SET Y=_x000D_
VER | FIND "Windows NT" > NUL_x000D_
IF ERRORLEVEL 1 SET Y=/Y_x000D_
_x000D_
:: Flush existing file or create new one if -a wasn't specified_x000D_
IF %Append%==0 (COPY %Y% NUL %File% > NUL 2>&1)_x000D_
_x000D_
:: Actual TEE_x000D_
FOR /F "tokens=1* delims=]" %%A IN ('FIND /N /V ""') DO (_x000D_
 >  CON    ECHO.%%B_x000D_
 >> %File% ECHO.%%B_x000D_
)_x000D_
_x000D_
:: Done_x000D_
ENDLOCAL_x000D_
GOTO:EOF_x000D_
_x000D_
:Count_x000D_
SET /A Counter += 1_x000D_
SET File=%1_x000D_
GOTO:EOF_x000D_
_x000D_
:Syntax_x000D_
ECHO._x000D_
ECHO Tee.bat,  Version 2.11a for Windows NT 4 / 2000 / XP_x000D_
ECHO Display text on screen and redirect it to a file simultaneously_x000D_
ECHO._x000D_
IF NOT "%OS%"=="Windows_NT" ECHO Usage:  some_command  ³  TEE.BAT  [ -a ]  filename_x000D_
IF NOT "%OS%"=="Windows_NT" GOTO Skip_x000D_
ECHO Usage:  some_command  ^|  TEE.BAT  [ -a ]  filename_x000D_
:Skip_x000D_
ECHO._x000D_
ECHO Where:  "some_command" is the command whose output should be redirected_x000D_
ECHO         "filename"     is the file the output should be redirected to_x000D_
ECHO         -a             appends the output of the command to the file,_x000D_
ECHO                        rather than overwriting the file_x000D_
ECHO._x000D_
ECHO Written by Rob van der Woude_x000D_
ECHO http://www.robvanderwoude.com_x000D_
ECHO Modified by Kees Couprie_x000D_
ECHO http://kees.couprie.org_x000D_
ECHO and Andrew Cameron
_x000D_
_x000D_
_x000D_

Find and replace in file and overwrite file doesn't work, it empties the file

And the ed answer:

printf "%s\n" '1,$s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' w q | ed index.html

To reiterate what codaddict answered, the shell handles the redirection first, wiping out the "input.html" file, and then the shell invokes the "sed" command passing it a now empty file.

How do I use sudo to redirect output to a location I don't have permission to write to?

Whenever I have to do something like this I just become root:

# sudo -s
# ls -hal /root/ > /root/test.out
# exit

It's probably not the best way, but it works.

Send string to stdin

Solution

You want to (1) create stdout output in one process (like echo '…') and (2) redirect that output to stdin input of another process but (3) without the use of the bash pipe mechanism. Here's a solution that matches all three conditions:

/my/bash/script < <(echo 'This string will be sent to stdin.')

The < is normal input redirection for stdin. The <(…) is bash process substitution. Roughly it creates a /dev/fd/… file with the output of the substituting command and passes that filename in place of the <(…), resulting here for example in script < /dev/fd/123. For details, see this answer.

Comparison with other solutions

  • A one-line heredoc sent to stdin script <<< 'string' only allows to send static strings, not the output of other commands.

  • Process substitution alone, such as in diff <(ls /bin) <(ls /usr/bin), does not send anything to stdin. Instead, the process output is saved into a file, and its path is passed as a command line argument. For the above example, this is equivalent to diff /dev/fd/10 /dev/fd/11, a command where diff receives no input from stdin.

Use cases

I like that, unlike the pipe mechanism, the < <(…) mechanism allows to put the command first and all input after it, as is the standard for input from command line options.

However, beyond commandline aesthetics, there are some cases where a pipe mechanism cannot be used. For example, when a certain command has to be provided as argument to another command, such as in this example with sshpass.

Bash write to file without echo?

I had the problem not being able to send ">" and ended up with echo!

echo "Hello world" | dd of=test.txt

What is /dev/null 2>&1?

>> /dev/null redirects standard output (stdout) to /dev/null, which discards it.

(The >> seems sort of superfluous, since >> means append while > means truncate and write, and either appending to or writing to /dev/null has the same net effect. I usually just use > for that reason.)

2>&1 redirects standard error (2) to standard output (1), which then discards it as well since standard output has already been redirected.

How to get the difference (only additions) between two files in linux

git diff path/file.css | grep -E "^\+" | grep -v '+++ b/' | cut -c 2-
  • grep -E "^\+" is from previous accepted answer, it is incomplete because leaves non-source stuff
  • grep -v '+++ b' removes non-source line with file name of later version
  • cut -c 2- removes column of + signs, also may use sed 's/^\+//'

comm or sdiff were not an option because of git.

How to View Oracle Stored Procedure using SQLPlus?

check your casing, the name is typically stored in upper case

SELECT * FROM all_source WHERE name = 'DAILY_UPDATE' ORDER BY TYPE, LINE;

Stopping a thread after a certain amount of time

This will work if you are not blocking.

If you are planing on doing sleeps, its absolutely imperative that you use the event to do the sleep. If you leverage the event to sleep, if someone tells you to stop while "sleeping" it will wake up. If you use time.sleep() your thread will only stop after it wakes up.

import threading
import time

duration = 2

def main():
    t1_stop = threading.Event()
    t1 = threading.Thread(target=thread1, args=(1, t1_stop))

    t2_stop = threading.Event()
    t2 = threading.Thread(target=thread2, args=(2, t2_stop))

    time.sleep(duration)
    # stops thread t2
    t2_stop.set()

def thread1(arg1, stop_event):
    while not stop_event.is_set():
        stop_event.wait(timeout=5)

def thread2(arg1, stop_event):
    while not stop_event.is_set():
        stop_event.wait(timeout=5)

What's the difference between an argument and a parameter?

Let's say you're an airline. You build an airplane. You install seats in it. Then, you fill the plane up with passengers and send it somewhere. The passengers (or rather, some spatio-temporally altered version thereof) disembark. Next day, you re-use the same plane, and same seats, but with different passengers this time.

The plane is your function.

The parameters are the seats.

The arguments are the passengers that go in those seats.

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Since I can not add a comment to the marked answer I will just post this here.

In addition to the correct answer you can indeed have this validated. Since this meta tag is only directed for IE all you need to do is add a IE conditional.

<!--[if IE]>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<![endif]-->

Doing this is just like adding any other IE conditional statement and only works for IE and no other browsers will be affected.

Make a DIV fill an entire table cell

If the table cell is the size that you want, just add this css class and assign it to your div:

.block {
   height: -webkit-calc(100vh);
   height: -moz-calc(100vh);
   height: calc(100vh);
   width: 100%;
}

If you want the table cell to fill up the parent too, assign the class to table cell too. I hope it helps.

How to delete a file from SD card?

This worked for me.

String myFile = "/Name Folder/File.jpg";  

String my_Path = Environment.getExternalStorageDirectory()+myFile;  

File f = new File(my_Path);
Boolean deleted = f.delete();

Erase the current printed console line

Some worthwhile subtleties...

\33[2K erases the entire line your cursor is currently on

\033[A moves your cursor up one line, but in the same column i.e. not to the start of the line

\r brings your cursor to the beginning of the line (r is for carriage return N.B. carriage returns do not include a newline so cursor remains on the same line) but does not erase anything

In xterm specifically, I tried the replies mentioned above and the only way I found to erase the line and start again at the beginning is the sequence (from the comment above posted by @Stephan202 as well as @vlp and @mantal) \33[2K\r

On an implementation note, to get it to work properly for example in a countdown scenario since I wasn't using a new line character '\n' at the end of each fprintf(), so I had to fflush() the stream each time (to give you some context, I started xterm using a fork on a linux machine without redirecting stdout, I was just writing to the buffered FILE pointer fdfile with a non-blocking file descriptor I had sitting on the pseudo terminal address which in my case was /dev/pts/21):

fprintf(fdfile, "\33[2K\rT minus %d seconds...", i);
fflush(fdfile);

Note that I used both the \33[2K sequence to erase the line followed by the \r carriage return sequence to reposition the cursor at the beginning of the line. I had to fflush() after each fprintf() because I don't have a new line character at the end '\n'. The same result without needing fflush() would require the additional sequence to go up a line:

fprintf(fdfile, "\033[A\33[2K\rT minus %d seconds...\n", i);

Note that if you have something on the line immediately above the line you want to write on, it will get over-written with the first fprintf(). You would have to leave an extra line above to allow for the first movement up one line:

i = 3;
fprintf(fdfile, "\nText to keep\n");
fprintf(fdfile, "Text to erase****************************\n");
while(i > 0) { // 3 second countdown
    fprintf(fdfile, "\033[A\33[2KT\rT minus %d seconds...\n", i);
    i--;
    sleep(1);
}

How to loop through each and every row, column and cells in a GridView and get its value

As it's said by "Tim Schmelter" this is the best way : just change in it's code the seconde loop ( GridView2.Columns[i].Count by row.Cells.Count ) so it looks seem's that:

foreach(GridViewRow row in GridView2.Rows)
{
    for(int i = 0; i < GridView2.Columns.Count; i++)
    {
        String header = GridView2.Columns[i].HeaderText;
        String cellText = row.Cells[i].Text;
    }
}

thank you.

Convert .class to .java

Invoking javap to read the bytecode

The javap command takes class-names without the .class extension. Try

javap -c ClassName

Converting .class files back to .java files

javap will however not give you the implementations of the methods in java-syntax. It will at most give it to you in JVM bytecode format.

To actually decompile (i.e., do the reverse of javac) you will have to use proper decompiler. See for instance the following related question:

What is (functional) reactive programming?

The paper Simply efficient functional reactivity by Conal Elliott (direct PDF, 233 KB) is a fairly good introduction. The corresponding library also works.

The paper is now superceded by another paper, Push-pull functional reactive programming (direct PDF, 286 KB).

Merge Two Lists in R

Here are two options, the first:

both <- list(first, second)
n <- unique(unlist(lapply(both, names)))
names(n) <- n
lapply(n, function(ni) unlist(lapply(both, `[[`, ni)))

and the second, which works only if they have the same structure:

apply(cbind(first, second),1,function(x) unname(unlist(x)))

Both give the desired result.

Add an object to a python list

while you should show how your code looks like that gives the problem, i think this scenario is very common. See copy/deepcopy

SQL Server format decimal places with commas

without considering this to be a good idea...

select dbo.F_AddThousandSeparators(convert(varchar, convert(decimal(18, 4), 1234.1234567), 1))

Function

-- Author:      bummi
-- Create date: 20121106
CREATE FUNCTION F_AddThousandSeparators(@NumStr varchar(50)) 
RETURNS Varchar(50)
AS
BEGIN
declare @OutStr varchar(50)
declare @i int
declare @run int

Select @i=CHARINDEX('.',@NumStr)
if @i=0 
    begin
    set @i=LEN(@NumStr)
    Set @Outstr=''
    end
else
    begin   
     Set @Outstr=SUBSTRING(@NUmStr,@i,50)
     Set @i=@i -1
    end 


Set @run=0

While @i>0
    begin
      if @Run=3
        begin
          Set @Outstr=','+@Outstr
          Set @run=0
        end
      Set @Outstr=SUBSTRING(@NumStr,@i,1) +@Outstr  
      Set @i=@i-1
      Set @run=@run + 1     
    end

    RETURN @OutStr

END
GO

What methods of ‘clearfix’ can I use?

The new standard, as used by Inuit.css and Bourbon - two very widely used and well-maintained CSS/Sass frameworks:

.btcf:after {
    content:"";
    display:block;
    clear:both;
}

Notes

Keep in mind that clearfixes are essentially a hack for what flexbox layouts can now provide in a much smarter way. CSS floats were originally designed for inline content to flow around - like images in a long textual article - and not for grid layouts and the like. If your target browsers support flexbox, it's worth looking into.

This doesn't support IE7. You shouldn't be supporting IE7. Doing so continues to expose users to unfixed security exploits and makes life harder for all other web developers, as it reduces the pressure on users and organisations to switch to modern browsers.

This clearfix was announced and explained by Thierry Koblentz in July 2012. It sheds unnecessary weight from Nicolas Gallagher's 2011 micro-clearfix. In the process, it frees a pseudo-element for your own use. This has been updated to use display: block rather than display: table (again, credit to Thierry Koblentz).

Error: JAVA_HOME is not defined correctly executing maven

$JAVA_HOME should be the directory where java was installed, not one of its parts:

export JAVA_HOME=/usr/lib/jvm/java-7-oracle

What are the RGB codes for the Conditional Formatting 'Styles' in Excel?

For 'Bad' red:

  • The Font Is: (156,0,6)
  • The Background Is: (255,199,206)

For 'Good' green:

  • The Font Is: (0,97,0)
  • The Background Is: (198,239,206)

For 'Neutral' yellow:

  • The Font Is: (156,101,0)
  • The Background Is: (255,235,156)

How do I make HttpURLConnection use a proxy?

You can also set

-Djava.net.useSystemProxies=true

On Windows and Linux this will use the system settings so you don't need to repeat yourself (DRY)

http://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html#Proxies

sendmail: how to configure sendmail on ubuntu?

When you typed in sudo sendmailconfig, you should have been prompted to configure sendmail.

For reference, the files that are updated during configuration are located at the following (in case you want to update them manually):

/etc/mail/sendmail.conf
/etc/cron.d/sendmail
/etc/mail/sendmail.mc

You can test sendmail to see if it is properly configured and setup by typing the following into the command line:

$ echo "My test email being sent from sendmail" | /usr/sbin/sendmail [email protected]

The following will allow you to add smtp relay to sendmail:

#Change to your mail config directory:
cd /etc/mail

#Make a auth subdirectory
mkdir auth
chmod 700 auth

#Create a file with your auth information to the smtp server
cd auth
touch client-info

#In the file, put the following, matching up to your smtp server:
AuthInfo:your.isp.net "U:root" "I:user" "P:password"

#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..

Add the following lines to sendmail.mc, but before the MAILERDEFINITIONS. Make sure you update your smtp server.

define(`SMART_HOST',`your.isp.net')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash -o /etc/mail/auth/client-info.db')dnl

Invoke creation sendmail.cf (alternatively run make -C /etc/mail):

m4 sendmail.mc > sendmail.cf

Restart the sendmail daemon:

service sendmail restart

How to config Tomcat to serve images from an external folder outside webapps?

You could have a redirect servlet. In you web.xml you'd have:

<servlet>
    <servlet-name>images</servlet-name>
    <servlet-class>com.example.images.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>images</servlet-name>
    <url-pattern>/images/*</url-pattern>
</servlet-mapping>

All your images would be in "/images", which would be intercepted by the servlet. It would then read in the relevant file in whatever folder and serve it right back out. For example, say you have a gif in your images folder, c:\Server_Images\smilie.gif. In the web page would be <img src="http:/example.com/app/images/smilie.gif".... In the servlet, HttpServletRequest.getPathInfo() would yield "/smilie.gif". Which the servlet would find in the folder.

Closing WebSocket correctly (HTML5, Javascript)

According to the protocol spec v76 (which is the version that browser with current support implement):

To close the connection cleanly, a frame consisting of just a 0xFF byte followed by a 0x00 byte is sent from one peer to ask that the other peer close the connection.

If you are writing a server, you should make sure to send a close frame when the server closes a client connection. The normal TCP socket close method can sometimes be slow and cause applications to think the connection is still open even when it's not.

The browser should really do this for you when you close or reload the page. However, you can make sure a close frame is sent by doing capturing the beforeunload event:

window.onbeforeunload = function() {
    websocket.onclose = function () {}; // disable onclose handler first
    websocket.close();
};

I'm not sure how you can be getting an onclose event after the page is refreshed. The websocket object (with the onclose handler) will no longer exist once the page reloads. If you are immediately trying to establish a WebSocket connection on your page as the page loads, then you may be running into an issue where the server is refusing a new connection so soon after the old one has disconnected (or the browser isn't ready to make connections at the point you are trying to connect) and you are getting an onclose event for the new websocket object.

Special characters like @ and & in cURL POST data

I did this

~]$ export A=g

~]$ export B=!

~]$ export C=nger


   curl http://<>USERNAME<>1:$A$B$C@<>URL<>/<>PATH<>/

Center a button in a Linear layout

easy with this

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:visibility="visible" 
        android:gravity="center"
        android:orientation="vertical" >

        <ProgressBar
            android:id="@+id/pbEndTrip"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:text="Gettings" />
    </LinearLayout>

Multiple conditions in WHILE loop

If your code, if the user enters 'X' (for instance), when you reach the while condition evaluation it will determine that 'X' is differente from 'n' (nChar != 'n') which will make your loop condition true and execute the code inside of your loop. The second condition is not even evaluated.

Should I use Java's String.format() if performance is important?

Generally you should use String.Format because it's relatively fast and it supports globalization (assuming you're actually trying to write something that is read by the user). It also makes it easier to globalize if you're trying to translate one string versus 3 or more per statement (especially for languages that have drastically different grammatical structures).

Now if you never plan on translating anything, then either rely on Java's built in conversion of + operators into StringBuilder. Or use Java's StringBuilder explicitly.

How to get ip address of a server on Centos 7 in bash

Actually, when you do not want to use external sources (or cannot), I would recommend:

DEVICE=$(ls -l /sys/class/net | awk '$NF~/pci0/ { print $(NF-2); exit }')
IPADDR=$(ip -br address show dev $DEVICE | awk '{print substr($3,1,index($3,"/")-1);}')

The first line gets the name of the first network device on the PCI bus, the second one gives you its IP address.

BTW ps ... | grep ... | awk ... stinks. awk does not need grep.

How to JSON decode array elements in JavaScript?

Suppose you have an array in PHP as $iniData with 5 fields. If using ajax -

echo json_encode($iniData);

In Javascript, use the following :

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            type: "GET",
            url: "ajaxCalls.php",
            data: "dataType=ini",
            success: function(msg)
            {
                var x = eval('(' + msg + ')');
                $('#allowed').html(x.allowed);              // these are the fields which you can now easily access..
                $('#completed').html(x.completed);
                $('#running').html(x.running);
                $('#expired').html(x.expired);
                $('#balance').html(x.balance);
            }
        });
    });
</script>

Writing a list to a file with Python

In Python3 You Can use this loop

with open('your_file.txt', 'w') as f:
    for item in list:
        f.print("", item)

Wait until boolean value changes it state

Ok maybe this one should solve your problem. Note that each time you make a change you call the change() method that releases the wait.

Integer any = new Integer(0);

public synchronized boolean waitTillChange() {
    any.wait();
    return true;
}

public synchronized void change() {
    any.notify();
}

global variable for all controller and views

In Laravel, 5+ you can create a file in the config folder and create variables in that and use that across the app. For instance, I want to store some information based on the site. I create a file called site_vars.php, which looks like this

<?php
return [
    'supportEmail' => '[email protected]',
    'adminEmail' => '[email protected]'
];

Now in the routes, controller, views you can access it using

Config::get('site_vars.supportEmail')

In the views if I this

{{ Config::get('site_vars.supportEmail') }}

It will give [email protected]

Hope this helps.

EDiT- You can also define vars in .env file and use them here. That is the best way in my opinion as it gives you the flexibility to use values that you want on your local machine.

So, you can do something this in the array

'supportEmail' => env('SUPPORT_EMAIL', '[email protected]')

Important - After you do this, don't forget to do

php artisan config:cache

In case, there's still some problem, then you can do this (usually it would never happen but still if it ever happens)

php artisan cache:clear
php artisan config:cache

How to change facebook login button with my custom image

It is actually possible only using CSS, however, the image you use to replace must be the same size as the original facebook log in button. Fortunately Facebook delivers the button in different sizes.

From facebook:

size - Different sized buttons: small, medium, large, xlarge - the default is medium. https://developers.facebook.com/docs/reference/plugins/login/

Set the login iframe opacity to 0 and show a background image in the parent div

.fb_iframe_widget iframe {
    opacity: 0;
}

.fb_iframe_widget {
  background-image: url(another-button.png);
  background-repeat: no-repeat; 
}

If you use an image that is bigger than the original facebook button, the part of the image that is outside the width and height of the original button will not be clickable.

Code for Greatest Common Divisor in Python

gcd = lambda m,n: m if not n else gcd(n,m%n)

What does "Changes not staged for commit" mean

Suposed you saved a new file changes. (navbar.component.html for example)

Run:

ng status
modified:   src/app/components/shared/navbar/navbar.component.html

If you want to upload those changes for that file you must run:

git add src/app/components/shared/navbar/navbar.component.html

And then:

git commit src/app/components/shared/navbar/navbar.component.html -m "new navbar changes and fixes"

And then:

git push origin [your branch name, usually "master"]

---------------------------------------------------------------

Or if you want to upload all your changes (several/all files):

git commit -a

And them this will appear "Please enter the commit message for your changes."

  • You'll see this message if you git commit without a message (-m)
  • You can get out of it with two steps:
  • 1.a. Type a multi-line message to move foward with the commit.
  • 1.b. Leave blank to abort the commit.
    1. Hit "esc" then type ":wq" and hit enter to save your choice. Viola!

And then:

git push

And Viola!

How to manually include external aar package using new Gradle Android Build System

The standard way to import AAR file in an application is given in https://developer.android.com/studio/projects/android-library.html#AddDependency

Click File > New > New Module. Click Import .JAR/.AAR Package then click Next. Enter the location of the compiled AAR or JAR file then click Finish.

Please refer the link above for next steps.

How to find elements with 'value=x'?

Value exactly equal to 123:

jQuery("#attached_docs[value='123']")

Full reference: http://api.jquery.com/category/selectors/

How to get integer values from a string in Python?

With python 3.6, these two lines return a list (may be empty)

>>[int(x) for x in re.findall('\d+', your_string)]

Similar to

>>list(map(int, re.findall('\d+', your_string))

How can I resolve the error: "The command [...] exited with code 1"?

Check your paths: If you are using a separate build server for TFS (most likely), make sure that all your paths in the .csproj file match the TFS server paths. I got the above error when checking in the *.csproj file when it had references to my development machine paths and not the TFS server paths.

Remove multi-line commands: Also, try and remove multi-line commands into single-line commands in xml as a precaution. I had the following xml in the *.proj that caused issues in TFS:

<Exec Condition="bl.." 
Command=" Blah...
..." </Exec>

Changing the above xml to this worked:

  <Exec Condition="bl.." Command=" Blah..." </Exec>

Executing multiple commands from a Windows cmd script

I don't know the direct answer to your question, but if you do a lot of these scripts, it might be worth learning a more powerful language like perl. Free implementations exist for Windows (e.g. activestate, cygwin). I've found it worth the initial effort for my own tasks.

Edit:

As suggested by @Ferruccio, if you can't install extra software, consider vbscript and/or javascript. They're built into the Windows scripting host.

jQuery: selecting each td in a tr

You don't need a jQuery selector at all. You already have a reference to the cells in each row via the cells property.

$('#tblNewAttendees tr').each(function() {

    $.each(this.cells, function(){
        alert('hi');
    });

});

It is far more efficient to utilize a collection that you already have, than to create a new collection via DOM selection.

Here I've used the jQuery.each()(docs) method which is just a generic method for iteration and enumeration.

Why can't I center with margin: 0 auto?

Why not?

#header {
    text-align: center;
}

#header ul {
    display: inline;
}

Adding default parameter value with type hint in Python

I recently saw this one-liner:

def foo(name: str, opts: dict=None) -> str:
    opts = {} if not opts else opts
    pass

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

Include below dependency in your pom.xml

<dependency>
 <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
   <version>{spring-version}</version>
</dependency>

Recommended way to get hostname in Java

Although this topic has already been answered there's more to say.

First of all: Clearly we need some definitions here. The InetAddress.getLocalHost().getHostName() gives you the name of the host as seen from a network perspective. The problems with this approach are well documented in the other answers: it often requires a DNS lookup, it's ambiguous if the host has multiple network interfaces and it just plain fails sometimes (see below).

But on any OS there's another name as well. A name of the host that gets defined very early in the boot process, long before the network is initialized. Windows refers to this as computername, Linux calls it kernel hostname and Solaris uses the word nodename. I like best the word computername, so I'll use that word from now on.

Finding the computername

  • On Linux/Unix the computername is what you get from the C function gethostname(), or hostname command from shell or HOSTNAME environment variable in Bash-like shells.

  • On Windows the computername is what you get from environment variable COMPUTERNAME or Win32 GetComputerName function.

Java has no way of obtaining what I've defined as 'computername'. Sure, there are workarounds as described in other answers, like for Windows calling System.getenv("COMPUTERNAME"), but on Unix/Linux there's no good workaround without resorting to JNI/JNA or Runtime.exec(). If you don't mind a JNI/JNA solution then there's gethostname4j which is dead simple and very easy to use.

Let's move on with two examples, one from Linux and one from Solaris, which demonstrate how you can easily get into a situation where you cannot obtain the computername using standard Java methods.

Linux example

On a newly created system, where the host during installation has been named as 'chicago', we now change the so-called kernel hostname:

$ hostnamectl --static set-hostname dallas

Now the kernel hostname is 'dallas', as evident from the hostname command:

$ hostname
dallas

But we still have

$ cat /etc/hosts
127.0.0.1   localhost
127.0.0.1   chicago

There's no misconfiguration in this. It just means the host's networked name (or rather the name of the loopback interface) is different from the host's computername.

Now, try executing InetAddress.getLocalHost().getHostName() and it will throw java.net.UnknownHostException. You are basically stuck. There's no way to retrieve neither the value 'dallas' nor the value 'chicago'.

Solaris example

The example below is based on Solaris 11.3.

The host has deliberately been configured so that the loopback name <> nodename.

In other words we have:

$ svccfg -s system/identity:node listprop config
...
...
config/loopback             astring        chicago
config/nodename             astring        dallas

and the contents of /etc/hosts :

:1 chicago localhost
127.0.0.1 chicago localhost loghost

and the result of the hostname command would be:

$ hostname
dallas

Just like in the Linux example a call to InetAddress.getLocalHost().getHostName() will fail with

java.net.UnknownHostException: dallas:  dallas: node name or service name not known

Just like the Linux example you are now stuck. There's no way to retrieve neither the value 'dallas' nor the value 'chicago'.

When will you really struggle with this?

Very often you'll find that InetAddress.getLocalHost().getHostName() will indeed return a value which is equal to the computername. So there's no problem (except for the added overhead of name resolution).

The problem arises typically within PaaS environments where there's a difference between computername and the name of the loopback interface. For example people report problems in Amazon EC2.

Bug/RFE reports

A bit of searching reveals this RFE report : link1, link2. However, judging from the comments on that report the issue seems to have been largely misunderstood by the JDK team, so it is unlikely it will be addressed.

I like the comparison in the RFE to other programming languages.

Word wrapping in phpstorm

If using PhpStorm 2019 and higher

Phpstorm Word Wrapping Settings Screenshot

File > Settings > Editor > General

There is'Soft-warp files' input under the 'Soft Warps' Header.

*.md; *.txt; *.rst; .adoc;

Add the file types to this field in which files you want them to be used.

*.md; *.txt; *.rst; .adoc;.php;*.js

How to fix Terminal not loading ~/.bashrc on OS X Lion

Terminal opens a login shell. This means, ~/.bash_profile will get executed, ~/.bashrc not.

The solution on most systems is to "require" the ~/.bashrc in the ~/.bash_profile: just put this snippet in your ~/.bash_profile:

[[ -s ~/.bashrc ]] && source ~/.bashrc

Qt: How do I handle the event of the user pressing the 'X' (close) button?

also you can reimplement protected member QWidget::closeEvent()

void YourWidgetWithXButton::closeEvent(QCloseEvent *event)
{
    // do what you need here
    // then call parent's procedure
    QWidget::closeEvent(event);
}

ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

Converting an int into a 4 byte char array (C)

The issue with the conversion (the reason it's giving you a ffffff at the end) is because your hex integer (that you are using the & binary operator with) is interpreted as being signed. Cast it to an unsigned integer, and you'll be fine.

Turn off auto formatting in Visual Studio

I was pissed off every time I pasted anything in cshtml file in Visual Studio 2015, 2017. I tried different settings and finally found the proper one: Options => Text Editor => HTML => Advanced => Paste (Format on paste) => False enter image description here

Amazon Linux: apt-get: command not found

Try to install your application by using yum command yum install application_name

"Port 4200 is already in use" when running the ng serve command

For Ubndu 18.04 sudo lsof -t -i tcp:3000 | xargs kill -9

Its happen when port was unsucessfully terminated so this command will terminat it 4200 or 3000 or3300 any

Seeing the console's output in Visual Studio 2010?

Visual Studio is by itself covering the console window, try minimizing Visual Studio window they are drawn over each other.

Count characters in textarea

HTML sample, used wherever I need a counter, notice the relevance of IDs of textarea and second span : id="post" <-> id="rem_post" and the title of the span that holds the desired characters amount of each particular textarea

<textarea class="countit" name="post" id="post"></textarea>
<p>
  <span>characters remaining: <span id="rem_post" title="1000"></span></span>
</p>

JavaScript function, usually placed before </body> in my template file, requires jQuery

$(".countit").keyup(function () {
  var cmax = $("#rem_" + $(this).attr("id")).attr("title");

  if ($(this).val().length >= cmax) {
    $(this).val($(this).val().substr(0, cmax));
  }

  $("#rem_" + $(this).attr("id")).text(cmax - $(this).val().length);

});

What is the best way to trigger onchange event in react js

I know this answer comes a little late but I recently faced a similar problem. I wanted to trigger an event on a nested component. I had a list with radio and check box type widgets (they were divs that behaved like checkboxes and/or radio buttons) and in some other place in the application, if someone closed a toolbox, I needed to uncheck one.

I found a pretty simple solution, not sure if this is best practice but it works.

var event = new MouseEvent('click', {
 'view': window, 
 'bubbles': true, 
 'cancelable': false
});
var node = document.getElementById('nodeMyComponentsEventIsConnectedTo');
node.dispatchEvent(event);

This triggered the click event on the domNode and my handler attached via react was indeed called so it behaves like I would expect if someone clicked on the element. I have not tested onChange but it should work, and not sure how this will fair in really old versions of IE but I believe the MouseEvent is supported in at least IE9 and up.

I eventually moved away from this for my particular use case because my component was very small (only a part of my application used react since i'm still learning it) and I could achieve the same thing another way without getting references to dom nodes.

UPDATE:

As others have stated in the comments, it is better to use this.refs.refname to get a reference to a dom node. In this case, refname is the ref you attached to your component via <MyComponent ref='refname' />.

Using global variables between files?

See Python's document on sharing global variables across modules:

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg).

config.py:

x = 0   # Default value of the 'x' configuration setting

Import the config module in all modules of your application; the module then becomes available as a global name.

main.py:

import config
print (config.x)

or

from config import x
print (x)

In general, don’t use from modulename import *. Doing so clutters the importer’s namespace, and makes it much harder for linters to detect undefined names.

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

You have to add following in header:

<script type="text/javascript">
        function fixform() {
            if (opener.document.getElementById("aspnetForm").target != "_blank") return;

            opener.document.getElementById("aspnetForm").target = "";
            opener.document.getElementById("aspnetForm").action = opener.location.href;
            }
</script>

Then call fixform() in load your page.

Using SELECT result in another SELECT

You are missing table NewScores, so it can't be found. Just join this table.

If you really want to avoid joining it directly you can replace NewScores.NetScore with SELECT NetScore FROM NewScores WHERE {conditions on which they should be matched}

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

No need to promise with $http, i use it just with two returns :

 myApp.service('dataService', function($http) {
   this.getData = function() {
      return $http({
          method: 'GET',
          url: 'https://www.example.com/api/v1/page',
          params: 'limit=10, sort_by=created:desc',
          headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
      }).success(function(data){
        return data;
      }).error(function(){
         alert("error");
         return null ;
      });
   }
 });

In controller

 myApp.controller('AngularJSCtrl', function($scope, dataService) {
     $scope.data = null;
     dataService.getData().then(function(response) {
         $scope.data = response;
     });
 }); 

Basic HTTP authentication with Node and Express 4

TL;DR:

? express.basicAuth is gone
? basic-auth-connect is deprecated
? basic-auth doesn't have any logic
? http-auth is an overkill
? express-basic-auth is what you want

More info:

Since you're using Express then you can use the express-basic-auth middleware.

See the docs:

Example:

const app = require('express')();
const basicAuth = require('express-basic-auth');
 
app.use(basicAuth({
    users: { admin: 'supersecret123' },
    challenge: true // <--- needed to actually show the login dialog!
}));

Add zero-padding to a string

string strvalue="11".PadRight(4, '0');

output= 1100

string strvalue="301".PadRight(4, '0');

output= 3010

string strvalue="11".PadLeft(4, '0');

output= 0011

string strvalue="301".PadLeft(4, '0');

output= 0301

JQuery .on() method with multiple event handlers to one selector

And you can combine same events/functions in this way:

$("table.planning_grid").on({
    mouseenter: function() {
        // Handle mouseenter...
    },
    mouseleave: function() {
        // Handle mouseleave...
    },
    'click blur paste' : function() {
        // Handle click...
    }
}, "input");

CSS vertical-align: text-bottom;

Sometimes you can play with padding and margin top, add line-height, etc.

See fiddle.

Style and text forked from @aspirinemaga

.parent
{
    width:300px;
    line-height:30px;
    border:1px solid red;
    padding-top:20px;
}

How to check Oracle database for long running queries

You can use the v$sql_monitor view to find queries that are running longer than 5 seconds. This may only be available in Enterprise versions of Oracle. For example this query will identify slow running queries from my TEST_APP service:

select to_char(sql_exec_start, 'dd-Mon hh24:mi'), (elapsed_time / 1000000) run_time,
       cpu_time, sql_id, sql_text 
from   v$sql_monitor
where  service_name = 'TEST_APP'
order  by 1 desc;

Note elapsed_time is in microseconds so / 1000000 to get something more readable

MS Access DB Engine (32-bit) with Office 64-bit

Here's a workaround for installing the 64-bit version of the Microsoft Access Database Engine 2010 redistributable on a system with a 32-bit MS Office version installed:

  • Check the 64-bit registry key "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Common\FilesPaths" before installing the 64-bit version of the Microsoft Access Database Engine 2010 redistributable.
  • If it does not contain the "mso.dll" registry value, then you will need to rename or delete the value after installing the 64-bit version of the Microsoft Access Database Engine 2010 redistributable on a system with a 32-bit version of MS Office installed.
  • Use the "/passive" command line parameter to install the redistributable, e.g. "C:\directory path\AccessDatabaseEngine_x64.exe" /passive
  • Delete or rename the "mso.dll" registry value, which contains the path to the 64-bit version of MSO.DLL (and should not be used by 32-bit MS Office versions).

Now you can start a 32-bit MS Office application without the "re-configuring" issue. Note that the "mso.dll" registry value will already be present if a 64-bit version of MS Office is installed. In this case the value should not be deleted or renamed.

Also if you do not want to use the "/passive" command line parameter you can edit the AceRedist.msi file to remove the MS Office architecture check:

You can now use this file to install the Microsoft Access Database Engine 2010 redistributable on a system where a "conflicting" version of MS Office is installed (e.g. 64-bit version on system with 32-bit MS Office version) Make sure that you rename the "mso.dll" registry value as explained above (if needed).

How to find the minimum value in an ArrayList, along with the index number? (Java)

Here's what I do. I find the minimum first then after the minimum is found, it is removed from ArrayList.

ArrayList<Integer> a = new ArrayList<>();
a.add(3);
a.add(6);
a.add(2);
a.add(5);

while (a.size() > 0) {
    int min = 1000;
    for (int b:a) {
        if (b < min)
            min = b;
    }
    System.out.println("minimum: " + min);
    System.out.println("index of min: " + a.indexOf((Integer) min));
    a.remove((Integer) min);
}

Get width in pixels from element with style set with %?

Not a single answer does what was asked in vanilla JS, and I want a vanilla answer so I made it myself.

clientWidth includes padding and offsetWidth includes everything else (jsfiddle link). What you want is to get the computed style (jsfiddle link).

function getInnerWidth(elem) {
    return parseFloat(window.getComputedStyle(elem).width);
}

EDIT: getComputedStyle is non-standard, and can return values in units other than pixels. Some browsers also return a value which takes the scrollbar into account if the element has one (which in turn gives a different value than the width set in CSS). If the element has a scrollbar, you would have to manually calculate the width by removing the margins and paddings from the offsetWidth.

function getInnerWidth(elem) {
    var style = window.getComputedStyle(elem);
    return elem.offsetWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight) - parseFloat(style.borderLeft) - parseFloat(style.borderRight) - parseFloat(style.marginLeft) - parseFloat(style.marginRight);
}

With all that said, this is probably not an answer I would recommend following with my current experience, and I would resort to using methods that don't rely on JavaScript as much.

Transaction isolation levels relation with locks on table

I want to understand the lock each transaction isolation takes on the table

For example, you have 3 concurrent processes A, B and C. A starts a transaction, writes data and commit/rollback (depending on results). B just executes a SELECT statement to read data. C reads and updates data. All these process work on the same table T.

  • READ UNCOMMITTED - no lock on the table. You can read data in the table while writing on it. This means A writes data (uncommitted) and B can read this uncommitted data and use it (for any purpose). If A executes a rollback, B still has read the data and used it. This is the fastest but most insecure way to work with data since can lead to data holes in not physically related tables (yes, two tables can be logically but not physically related in real-world apps =\).
  • READ COMMITTED - lock on committed data. You can read the data that was only committed. This means A writes data and B can't read the data saved by A until A executes a commit. The problem here is that C can update data that was read and used on B and B client won't have the updated data.
  • REPEATABLE READ - lock on a block of SQL(which is selected by using select query). This means B reads the data under some condition i.e. WHERE aField > 10 AND aField < 20, A inserts data where aField value is between 10 and 20, then B reads the data again and get a different result.
  • SERIALIZABLE - lock on a full table(on which Select query is fired). This means, B reads the data and no other transaction can modify the data on the table. This is the most secure but slowest way to work with data. Also, since a simple read operation locks the table, this can lead to heavy problems on production: imagine that T table is an Invoice table, user X wants to know the invoices of the day and user Y wants to create a new invoice, so while X executes the read of the invoices, Y can't add a new invoice (and when it's about money, people get really mad, especially the bosses).

I want to understand where we define these isolation levels: only at JDBC/hibernate level or in DB also

Using JDBC, you define it using Connection#setTransactionIsolation.

Using Hibernate:

<property name="hibernate.connection.isolation">2</property>

Where

  • 1: READ UNCOMMITTED
  • 2: READ COMMITTED
  • 4: REPEATABLE READ
  • 8: SERIALIZABLE

Hibernate configuration is taken from here (sorry, it's in Spanish).

By the way, you can set the isolation level on RDBMS as well:

and on and on...

Redirect with CodeIgniter

If your directory structure is like this,

site
  application
         controller
                folder_1
                   first_controller.php
                   second_controller.php
                folder_2
                   first_controller.php
                   second_controller.php

And when you are going to redirect it in same controller in which you are working then just write the following code.

 $this->load->helper('url');
    if ($some_value === FALSE/TRUE) //You may give 0/1 as well,its up to your logic
    {
         redirect('same_controller/method', 'refresh');
    }

And if you want to redirect to another control then use the following code.

$this->load->helper('url');
if ($some_value === FALSE/TRUE) //You may give 0/1 as well,its up to your logic
{
     redirect('folder_name/any_controller_name/method', 'refresh');
}

How to test if JSON object is empty in Java

Use the following code:

if(json.isNull()!= null){  //returns true only if json is not null

}

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

for example on debian

sudo gpasswd -a svn-admin www-data
sudo chgrp -R www-data svn/
sudo chmod -R g=rwsx svn/

How to add leading zeros?

Expanding on @goodside's repsonse:

In some cases you may want to pad a string with zeros (e.g. fips codes or other numeric-like factors). In OSX/Linux:

> sprintf("%05s", "104")
[1] "00104"

But because sprintf() calls the OS's C sprintf() command, discussed here, in Windows 7 you get a different result:

> sprintf("%05s", "104")
[1] "  104"

So on Windows machines the work around is:

> sprintf("%05d", as.numeric("104"))
[1] "00104"

How do I undo 'git add' before commit?

Undo a file which has already been added is quite easy using Git. For resetting myfile.txt, which have already been added, use:

git reset HEAD myfile.txt

Explanation:

After you staged unwanted file(s), to undo, you can do git reset. Head is head of your file in the local and the last parameter is the name of your file.

I have created the steps in the image below in more details for you, including all steps which may happen in these cases:

git reset HEAD file

private final static attribute vs private final attribute

Furthermore to Jon's answer if you use static final it will behave as a kind-of "definition". Once you compile the class which uses it, it will be in the compiled .class file burnt. Check my thread about it here.

For your main goal: If you don't use the NUMBER differently in the different instances of the class i would advise to use final and static. (You just have to keep in mind to not to copy compiled class files without considering possible troubles like the one my case study describes. Most of the cases this does not occur, don't worry :) )

To show you how to use different values in instances check this code:

public class JustFinalAttr {
  public final int Number;

  public JustFinalAttr(int a){
    Number=a;
  }
}

...System.out.println(new JustFinalAttr(4).Number);

How to disassemble a memory range with GDB?

If all that you want is to see the disassembly with the INTC call, use objdump -d as someone mentioned but use the -static option when compiling. Otherwise the fopen function is not compiled into the elf and is linked at runtime.

Allowing Untrusted SSL Certificates with HttpClient

Most answers here suggest to use the typical pattern:

using (var httpClient = new HttpClient())
{
 // do something
}

because of the IDisposable interface. Please don't!

Microsoft tells you why:

And here you can find a detailed analysis whats going on behind the scenes: You're using HttpClient wrong and it is destabilizing your software

Regarding your SSL question and based on Improper Instantiation antipattern # How to fix the problem

Here is your pattern:

class HttpInterface
{
 // https://docs.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/#how-to-fix-the-problem
 // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient#remarks
 private static readonly HttpClient client;

 // static initialize
 static HttpInterface()
 {
  // choose one of these depending on your framework
  
  // HttpClientHandler is an HttpMessageHandler with a common set of properties
  var handler = new HttpClientHandler()
  {
      ServerCertificateCustomValidationCallback = delegate { return true; },
  };
  // derives from HttpClientHandler but adds properties that generally only are available on full .NET
  var handler = new WebRequestHandler()
  {
      ServerCertificateValidationCallback = delegate { return true; },
      ServerCertificateCustomValidationCallback = delegate { return true; },
  };

  client = new HttpClient(handler);
 }
 
 .....
 
 // in your code use the static client to do your stuff
 var jsonEncoded = new StringContent(someJsonString, Encoding.UTF8, "application/json");

 // here in sync
 using (HttpResponseMessage resultMsg = client.PostAsync(someRequestUrl, jsonEncoded).Result)
 {
  using (HttpContent respContent = resultMsg.Content)
  {
   return respContent.ReadAsStringAsync().Result;
  }
 }
}

Ruby sleep or delay less than a second?

sleep(1.0/24.0)

As to your follow up question if that's the best way: No, you could get not-so-smooth framerates because the rendering of each frame might not take the same amount of time.

You could try one of these solutions:

  • Use a timer which fires 24 times a second with the drawing code.
  • Create as many frames as possible, create the motion based on the time passed, not per frame.

Fixed width buttons with Bootstrap

A block width button could easily become responsive button if the parent container is responsive. I think that using a combination of a fixed width and a more detailed selector path instead of !important because:

1) Its not a hack (setting min-width and max-width the same is however hacky)

2) Does not use the !important tag which is bad practice

3) Uses width so will be very readable and anyone who understands how cascading works in CSS will see whats going on (maybe leave a CSS comment for this?)

4) Combine your selectors that apply to your targeted node for increased accuracy

.parent_element .btn.btn-primary.save-button {
    width: 80px;
}

How can I align YouTube embedded video in the center in bootstrap

You dont have to put <iframe> in a parent div at all. You can target exactly youtube iframe with CSS/3:

iframe[src*="//youtube.com/"], iframe[src*="//www.youtube.com/"] {
   display: block;
   margin: 0 auto;
}

How to get query string parameter from MVC Razor markup?

I think a more elegant solution is to use the controller and the ViewData dictionary:

//Controller:
public ActionResult Action(int IFRAME)
    {
        ViewData["IsIframe"] = IFRAME == 1;
        return View();
    }

//view
@{
    string classToUse = (bool)ViewData["IsIframe"] ? "iframe-page" : "";
   <div id="wrap" class='@classToUse'></div>
 }

How to subtract n days from current date in java?

As @Houcem Berrayana say

If you would like to use n>24 then you can use the code like:

Date dateBefore = new Date((d.getTime() - n * 24 * 3600 * 1000) - n * 24 * 3600 * 1000); 

Suppose you want to find last 30 days date, then you'd use:

Date dateBefore = new Date((d.getTime() - 24 * 24 * 3600 * 1000) - 6 * 24 * 3600 * 1000); 

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

Install any package globally as below:

$ npm install -g replace  // replace is one of the node module.

As this replace module is installed globally so if you see your node modules folder you would not see replace module there and so you can not use this package using require('replace').

because with require you can use only local modules which are present in your node module folder.

Now to use global module you should link it with node module path using below command.

$ npm link replace

Now go back and see your node module folder you could now be able to see replace module there and can use it with require('replace') in your application as it is linked with your local node module.

Pls let me know if any further clarification is needed.

How to find files recursively by file type and copy them to a directory while in ssh?

Try this:

find . -name "*.pdf" -type f -exec cp {} ./pdfsfolder \;

Getting pids from ps -ef |grep keyword

To kill a process by a specific keyword you could create an alias in ~/.bashrc (linux) or ~/.bash_profile (mac).

alias killps="kill -9 `ps -ef | grep '[k]eyword' | awk '{print $2}'`"

git: patch does not apply

This command will apply the patch not resolving it leaving bad files as *.rej:

git apply --reject --whitespace=fix mypath.patch

You just have to resolve them. Once resolved run:

git -am resolved

Hbase quickly count number of rows

U can find sample example here:

/**
     * Used to get the number of rows of the table
     * @param tableName
     * @param familyNames
     * @return the number of rows
     * @throws IOException
     */
    public long countRows(String tableName, String... familyNames) throws IOException {
        long rowCount = 0;
        Configuration configuration = connection.getConfiguration();
        // Increase RPC timeout, in case of a slow computation
        configuration.setLong("hbase.rpc.timeout", 600000);
        // Default is 1, set to a higher value for faster scanner.next(..)
        configuration.setLong("hbase.client.scanner.caching", 1000);

        AggregationClient aggregationClient = new AggregationClient(configuration);
        try {
            Scan scan = new Scan();
            if (familyNames != null && familyNames.length > 0) {
                for (String familyName : familyNames) {
                    scan.addFamily(Bytes.toBytes(familyName));
                }
            }
            rowCount = aggregationClient.rowCount(TableName.valueOf(tableName), new LongColumnInterpreter(), scan);
        } catch (Throwable e) {
            throw new IOException(e);
        }
        return rowCount;
    }

Converting newline formatting from Mac to Windows

The following is a complete script based on the above answers along with sanity checking and works on Mac OS X and should work on other Linux / Unix systems as well (although this has not been tested).

#!/bin/bash

# http://stackoverflow.com/questions/6373888/converting-newline-formatting-from-mac-to-windows

# =============================================================================
# =
# = FIXTEXT.SH by ECJB
# =
# = USAGE:  SCRIPT [ MODE ] FILENAME
# =
# = MODE is one of unix2dos, dos2unix, tounix, todos, tomac
# = FILENAME is modified in-place
# = If SCRIPT is one of the modes (with or without .sh extension), then MODE
# =   can be omitted - it is inferred from the script name.
# = The script does use the file command to test if it is a text file or not,
# =   but this is not a guarantee.
# =
# =============================================================================

clear
script="$0"
modes="unix2dos dos2unix todos tounix tomac"

usage() {
    echo "USAGE:  $script [ mode ] filename"
    echo
    echo "MODE is one of:"
    echo $modes
    echo "NOTE:  The tomac mode is intended for old Mac OS versions and should not be"
    echo "used without good reason."
    echo
    echo "The file is modified in-place so there is no output filename."
    echo "USE AT YOUR OWN RISK."
    echo
    echo "The script does try to check if it's a binary or text file for sanity, but"
    echo "this is not guaranteed."
    echo
    echo "Symbolic links to this script may use the above names and be recognized as"
    echo "mode operators."
    echo
    echo "Press RETURN to exit."
    read answer
    exit
}

# -- Look for the mode as the scriptname
mode="`basename "$0" .sh`"
fname="$1"

# -- If 2 arguments use as mode and filename
if [ ! -z "$2" ] ; then mode="$1"; fname="$2"; fi

# -- Check there are 1 or 2 arguments or print usage.
if [ ! -z "$3" -o -z "$1" ] ; then usage; fi

# -- Check if the mode found is valid.
validmode=no
for checkmode in $modes; do if [ $mode = $checkmode ] ; then validmode=yes; fi; done
# -- If not a valid mode, abort.
if [ $validmode = no ] ; then echo Invalid mode $mode...aborting.; echo; usage; fi

# -- If the file doesn't exist, abort.
if [ ! -e "$fname" ] ; then echo Input file $fname does not exist...aborting.; echo; usage; fi

# -- If the OS thinks it's a binary file, abort, displaying file information.
if [ -z "`file "$fname" | grep text`" ] ; then echo Input file $fname may be a binary file...aborting.; echo; file "$fname"; echo; usage; fi

# -- Do the in-place conversion.
case "$mode" in
#   unix2dos ) # sed does not behave on Mac - replace w/ "todos" and "tounix"
#       # Plus, these variants are more universal and assume less.
#       sed -e 's/$/\r/' -i '' "$fname"             # UNIX to DOS  (adding CRs)
#       ;;
#   dos2unix )
#       sed -e 's/\r$//' -i '' "$fname"             # DOS  to UNIX (removing CRs)
#           ;;
    "unix2dos" | "todos" )
        perl -pi -e 's/\r\n|\n|\r/\r\n/g' "$fname"  # Convert to DOS
        ;;
    "dos2unix" | "tounix" )
        perl -pi -e 's/\r\n|\n|\r/\n/g'   "$fname"  # Convert to UNIX
        ;;
    "tomac" )
        perl -pi -e 's/\r\n|\n|\r/\r/g'   "$fname"  # Convert to old Mac
        ;;
    * ) # -- Not strictly needed since mode is checked first.
        echo Invalid mode $mode...aborting.; echo; usage
        ;;
esac

# -- Display result.
if [ "$?" = "0" ] ; then echo "File $fname updated with mode $mode."; else echo "Conversion failed return code $?."; echo; usage; fi

How to list files and folder in a dir (PHP)

PHP 5 has the RecursiveDirectoryIterator.

The manual has a basic example:

<?php

$directory = '/system/infomation/';

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));

while($it->valid()) {

    if (!$it->isDot()) {

        echo 'SubPathName: ' . $it->getSubPathName() . "\n";
        echo 'SubPath:     ' . $it->getSubPath() . "\n";
        echo 'Key:         ' . $it->key() . "\n\n";
    }

    $it->next();
}

?>

Edit -- Here's a slightly more advanced example (only slightly) which produces output similar to what you want (i.e. folder names then files).

// Create recursive dir iterator which skips dot folders
$dir = new RecursiveDirectoryIterator('./system/information',
    FilesystemIterator::SKIP_DOTS);

// Flatten the recursive iterator, folders come before their files
$it  = new RecursiveIteratorIterator($dir,
    RecursiveIteratorIterator::SELF_FIRST);

// Maximum depth is 1 level deeper than the base folder
$it->setMaxDepth(1);

// Basic loop displaying different messages based on file or folder
foreach ($it as $fileinfo) {
    if ($fileinfo->isDir()) {
        printf("Folder - %s\n", $fileinfo->getFilename());
    } elseif ($fileinfo->isFile()) {
        printf("File From %s - %s\n", $it->getSubPath(), $fileinfo->getFilename());
    }
}

How can I run an external command asynchronously from Python?

If you want to run many processes in parallel and then handle them when they yield results, you can use polling like in the following:

from subprocess import Popen, PIPE
import time

running_procs = [
    Popen(['/usr/bin/my_cmd', '-i %s' % path], stdout=PIPE, stderr=PIPE)
    for path in '/tmp/file0 /tmp/file1 /tmp/file2'.split()]

while running_procs:
    for proc in running_procs:
        retcode = proc.poll()
        if retcode is not None: # Process finished.
            running_procs.remove(proc)
            break
        else: # No process is done, wait a bit and check again.
            time.sleep(.1)
            continue

    # Here, `proc` has finished with return code `retcode`
    if retcode != 0:
        """Error handling."""
    handle_results(proc.stdout)

The control flow there is a little bit convoluted because I'm trying to make it small -- you can refactor to your taste. :-)

This has the advantage of servicing the early-finishing requests first. If you call communicate on the first running process and that turns out to run the longest, the other running processes will have been sitting there idle when you could have been handling their results.

React Native version mismatch

I updated the SDK version in app.json to match with the react native SDK version in package.json to fix this issue

In app.json

"sdkVersion": "37.0.0",

In package.json

"react-native": "https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz",

How do I make my ArrayList Thread-Safe? Another approach to problem in Java?

CopyOnWriteArrayList

Use CopyOnWriteArrayList class. This is the thread safe version of ArrayList.

Ignore parent padding

Another solution:

position: absolute;
top: 0;
left: 0;

just change the top/right/bottom/left to your case.

How to configure postgresql for the first time?

If you're running macOS like I am, you may not have the postgres user.

When trying to run sudo -u postgres psql I was getting the error sudo: unknown user: postgres

Luckily there are executables that postgres provides.

createuser -D /var/postgres/var-10-local --superuser --username=nick
createdb --owner=nick

Then I was able to access psql without issues.

psql
psql (10.2)
Type "help" for help.

nick=#

If you're creating a new postgres instance from scratch, here are the steps I took. I used a non-default port so I could run two instances.

mkdir /var/postgres/var-10-local
pg_ctl init -D /var/postgres/var-10-local

Then I edited /var/postgres/var-10-local/postgresql.conf with my preferred port, 5433.

/Applications/Postgres.app/Contents/Versions/10/bin/postgres -D /Users/nick/Library/Application\ Support/Postgres/var-10-local -p 5433

createuser -D /var/postgres/var-10-local --superuser --username=nick --port=5433
createdb --owner=nick --port=5433

Done!

angular.service vs angular.factory

The factory pattern is more flexible as it can return functions and values as well as objects.

There isn't a lot of point in the service pattern IMHO, as everything it does you can just as easily do with a factory. The exceptions might be:

  • If you care about the declared type of your instantiated service for some reason - if you use the service pattern, your constructor will be the type of the new service.
  • If you already have a constructor function that you're using elsewhere that you also want to use as a service (although probably not much use if you want to inject anything into it!).

Arguably, the service pattern is a slightly nicer way to create a new object from a syntax point of view, but it's also more costly to instantiate. Others have indicated that angular uses "new" to create the service, but this isn't quite true - it isn't able to do that because every service constructor has a different number of parameters. What angular actually does is use the factory pattern internally to wrap your constructor function. Then it does some clever jiggery pokery to simulate javascript's "new" operator, invoking your constructor with a variable number of injectable arguments - but you can leave out this step if you just use the factory pattern directly, thus very slightly increasing the efficiency of your code.

How to add header to a dataset in R?

You can do the following:

Load the data:

test <- read.csv(
          "http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data",
          header=FALSE)

Note that the default value of the header argument for read.csv is TRUE so in order to get all lines you need to set it to FALSE.

Add names to the different columns in the data.frame

names(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

or alternative and faster as I understand (not reloading the entire dataset):

colnames(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

Can two or more people edit an Excel document at the same time?

Yes you can. I've used it with Word and PowerPoint. You will need Office 2010 client apps and SharePoint 2010 foundation at least. You must also allow editing without checking out on the document library.

It's quite cool, you can mark regions as 'locked' so no-one can change them and you can see what other people have changed every time you save your changes to the server. You also get to see who's working on the document from the Office app. The merging happens on SharePoint 2010.

How to parse JSON without JSON.NET library?

You can use the classes found in the System.Json Namespace which were added in .NET 4.5. You need to add a reference to the System.Runtime.Serialization assembly

The JsonValue.Parse() Method parses JSON text and returns a JsonValue:

JsonValue value = JsonValue.Parse(@"{ ""name"":""Prince Charming"", ...");

If you pass a string with a JSON object, you should be able to cast the value to a JsonObject:

using System.Json;


JsonObject result = value as JsonObject;

Console.WriteLine("Name .... {0}", (string)result["name"]);
Console.WriteLine("Artist .. {0}", (string)result["artist"]);
Console.WriteLine("Genre ... {0}", (string)result["genre"]);
Console.WriteLine("Album ... {0}", (string)result["album"]);

The classes are quite similar to those found in the System.Xml.Linq Namespace.

How to Save Console.WriteLine Output to Text File

Using only configuration in your app.config:

    <system.diagnostics> 
        <trace autoflush="true" indentsize="4"> 
              <listeners> 

              <add name="consoleListener" type="System.Diagnostics.ConsoleTraceListener"/>

            <!--
            <add name="logListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="TextWriterOutput.log" /> 
            <add name="EventLogListener" type="System.Diagnostics.EventLogTraceListener" initializeData="MyEventLog"/>
             -->

             <!--
              Remove the Default listener to avoid duplicate messages
              being sent to the debugger for display
             -->
             <remove name="Default" />

             </listeners> 
        </trace> 
  </system.diagnostics>

For testing, you can use DebugView before running the program, then we can easily view all of the log messages.

References:
http://blogs.msdn.com/b/jjameson/archive/2009/06/18/configuring-logging-in-a-console-application.aspx http://www.thejoyofcode.com/from_zero_to_logging_with_system_diagnostics_in_15_minutes.aspx
Redirect Trace output to Console
Problem redirecting debug output to a file using trace listener
https://ukadcdiagnostics.codeplex.com/
http://geekswithblogs.net/theunstablemind/archive/2009/09/09/adventures-in-system.diagnostics.aspx

TypeError: 'NoneType' object has no attribute '__getitem__'

BrenBarn is correct. The error means you tried to do something like None[5]. In the backtrace, it says self.imageDef=self.values[2], which means that your self.values is None.

You should go through all the functions that update self.values and make sure you account for all the corner cases.

How to output JavaScript with PHP

You should escape the JavaScript string delimiters inside the PHP string. You're using double quotes for both PHP and JavaScript strings. Try like this instead:

<html>
<body>
<?php

// Here, we use single quotes for PHP and double quotes for JavaScript
echo '<script type="text/javascript">';
echo 'document.write("Hello World!")';
echo '</script>';

?>
</body>
</html>

You have to escape quotes on both JavaScript and PHP when the string delimiter are the same as the quotes:

echo "\""; // escape is done using a backslash
echo '\'';

Same in JavaScript:

alert("\""); // escape is done using a backslash
alert(echo '\'');

But because it's very hard to read a string with such escape sequences, it is better to combine single with double quotes, as needed:

echo '"';
echo "'";

How to clear the interpreter console?

The perfect cls:

cls = lambda: print("\033c\033[3J", end='')
cls()

Or directly:

print("\033c\033[3J", end='')

How do I type a TAB character in PowerShell?

If it helps you can embed a tab character in a double quoted string:

PS> "`t hello"

The term "Add-Migration" is not recognized

Just try init Microsoft.EntityFrameworkCore.Tools. In PM execute

C:\Users\<username>\.nuget\packages\Microsoft.EntityFrameworkCore.Tools\1.0.0-preview2-final\tools\init.ps1.

It helped me with the same problem. A version of the tools might be different. It`s depended of what you use in your project.

html cellpadding the left side of a cell

I would suggest using inline CSS styling.

<table border="1" style="padding-right: 10px;">
<tr>
<td>Content</td>
</tr>
</table>

or

<table border="1">
<tr style="padding-right: 10px;">
<td>Content</td>
</tr>
</table>

or

<table border="1">
<tr>
<td style="padding-right: 10px;">Content</td>
</tr>
</table>

I don't quite follow what you need, but this is what I would do, assuming I understand you needs.

How does delete[] know it's an array?

One question that the answers given so far don't seem to address: if the runtime libraries (not the OS, really) can keep track of the number of things in the array, then why do we need the delete[] syntax at all? Why can't a single delete form be used to handle all deletes?

The answer to this goes back to C++'s roots as a C-compatible language (which it no longer really strives to be.) Stroustrup's philosophy was that the programmer should not have to pay for any features that they aren't using. If they're not using arrays, then they should not have to carry the cost of object arrays for every allocated chunk of memory.

That is, if your code simply does

Foo* foo = new Foo;

then the memory space that's allocated for foo shouldn't include any extra overhead that would be needed to support arrays of Foo.

Since only array allocations are set up to carry the extra array size information, you then need to tell the runtime libraries to look for that information when you delete the objects. That's why we need to use

delete[] bar;

instead of just

delete bar;

if bar is a pointer to an array.

For most of us (myself included), that fussiness about a few extra bytes of memory seems quaint these days. But there are still some situations where saving a few bytes (from what could be a very high number of memory blocks) can be important.

hibernate could not get next sequence value

I seem to recall having to use @GeneratedValue(strategy = GenerationType.IDENTITY) to get Hibernate to use 'serial' columns on PostgreSQL.

Getting session value in javascript

If you are using VB as code behind, you have to use bracket "()" instead of square bracket "[]".

Example for VB:

<script type="text/javascript">
var accesslevel = '<%= Session("accesslevel").ToString().ToLower() %>';
</script>  

How can I set response header on express.js assets

You can also add a middleware to add CORS headers, something like this would work:

/**
 * Adds CORS headers to the response
 *
 * {@link https://en.wikipedia.org/wiki/Cross-origin_resource_sharing}
 * {@link http://expressjs.com/en/4x/api.html#res.set}
 * @param {object} request the Request object
 * @param {object} response the Response object
 * @param {function} next function to continue execution
 * @returns {void}
 * @example
 * <code>
 * const express = require('express');
 * const corsHeaders = require('./middleware/cors-headers');
 *
 * const app = express();
 * app.use(corsHeaders);
 * </code>
 */
module.exports = (request, response, next) => {
    // http://expressjs.com/en/4x/api.html#res.set
    response.set({
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'DELETE,GET,PATCH,POST,PUT',
        'Access-Control-Allow-Headers': 'Content-Type,Authorization'
    });

    // intercept OPTIONS method
    if(request.method === 'OPTIONS') {
        response.send(200);
    } else {
        next();
    }
};

Override element.style using CSS

element.style comes from the markup.

<li style="display: none;">

Just remove the style attribute from the HTML.

Annotation-specified bean name conflicts with existing, non-compatible bean def

Refresh gradle project on Eclipse solved this problem for me

Removing the remembered login and password list in SQL Server Management Studio

As gluecks pointed out, no more SqlStudio.bin in Microsoft SQL Server Management Studio 18. I also found this UserSettings.xml in C:\Users\userName\AppData\Roaming\Microsoft\SQL Server Management Studio\18.0. But removing the <Element> containing the credential seems not working, it comes right back on the xml file, if I close and re-open it again.

Turns out, you need to close the SQL Server Management Studio first, then edit the UserSettings.xml file in your favorite editor, e.g. Visual Studio Code. I guess it's cached somewhere in SSMS besides this xml file?! And it's not on Control Panel\All Control Panel Items\Credential Manager\Windows Credentials.

Django - "no module named django.core.management"

Are you using a Virtual Environment with Virtual Wrapper? Are you on a Mac?

If so try this:

Enter the following into your command line to start up the virtual environment and then work on it

1.)

source virtualenvwrapper.sh

or

source /usr/local/bin/virtualenvwrapper.sh

2.)

workon [environment name]

Note (from a newbie) - do not put brackets around your environment name

Get file name from a file location in Java

From Apache Commons IO FileNameUtils

String fileName = FilenameUtils.getName(stringNameWithPath);

How to check null objects in jQuery

Calling length property on undefined or a null object will cause IE and webkit browsers to fail!

Instead try this:

if($("#something") !== null){
  // do something
}

or

if($("#something") === null){
  // don't do something
}

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers

I had the same issue, and spent quite a bit of time trying to track down the solution. I had Anonymous Authentication set up at two different levels with two different users. Make sure that you're not overwriting your set up at a lower level.

Draw radius around a point in Google map

Using the Google Maps API V3, create a Circle object, then use bindTo() to tie it to the position of your Marker (since they are both google.maps.MVCObject instances).

// Create marker 
var marker = new google.maps.Marker({
  map: map,
  position: new google.maps.LatLng(53, -2.5),
  title: 'Some location'
});

// Add circle overlay and bind to marker
var circle = new google.maps.Circle({
  map: map,
  radius: 16093,    // 10 miles in metres
  fillColor: '#AA0000'
});
circle.bindTo('center', marker, 'position');

You can make it look just like the Google Latitude circle by changing the fillColor, strokeColor, strokeWeight etc (full API).

See more source code and example screenshots.

How to create a Custom Dialog box in android?

Full Screen Custom Alert Dialog Class in Kotlin

  1. Create XML file, same as you would an activity

  2. Create AlertDialog custom class

    class Your_Class(context:Context) : AlertDialog(context){
    
     init {
      requestWindowFeature(Window.FEATURE_NO_TITLE)
      setCancelable(false)
     }
    
     override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.your_Layout)
      val window = this.window
      window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                         WindowManager.LayoutParams.MATCH_PARENT)
    
      //continue custom code here
      //call dismiss() to close
     }
    }
    
  3. Call the dialog within the activity

    val dialog = Your_Class(this)
    //can set some dialog options here
    dialog.show()
    

Note**: If you do not want your dialog to be full screen, delete the following lines

      val window = this.window
      window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                         WindowManager.LayoutParams.MATCH_PARENT)

Then edit the layout_width & layout_height of your top layout within your XML file to be either wrap_content or a fixed DP value.

I generally do not recommend using fixed DP as you would likely want your app to be adaptable to multiple screen sizes, however if you keep your size values small enough you should be fine

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

When hosting your application on another service (like Heroku, Nodejitsu, and AWS), your host may independently configure the process.env.PORT variable for you; after all, your script runs in their environment.

Amazon's Elastic Beanstalk does this. If you try to set a static port value like 3000 instead of process.env.PORT || 3000 where 3000 is your static setting, then your application will result in a 500 gateway error because Amazon is configuring the port for you.

This is a minimal Express application that will deploy on Amazon's Elastic Beanstalk:

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

// use port 3000 unless there exists a preconfigured port
var port = process.env.PORT || 3000;

app.listen(port);

Render a string in HTML and preserve spaces and linebreaks

Just style the content with white-space: pre-wrap;.

_x000D_
_x000D_
div {_x000D_
    white-space: pre-wrap;_x000D_
}
_x000D_
<div>_x000D_
This is some text   with some extra spacing    and a_x000D_
few newlines along with some trailing spaces        _x000D_
     and five leading spaces thrown in_x000D_
for                                              good_x000D_
measure                                              _x000D_
</div>
_x000D_
_x000D_
_x000D_

How to use PHP string in mySQL LIKE query?

DO it like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");

Do not forget the % at the end

Capture iframe load complete event

You can also capture jquery ready event this way:

$('#iframeid').ready(function () {
//Everything you need.
});

Here is a working example:

http://jsfiddle.net/ZrFzF/

Uninstall Node.JS using Linux command line?

If you have yum you could do:

yum remove nodesource-release* nodejs

yum clean all

And after that check if its deleted:

rpm -qa 'node|npm'

jQuery .live() vs .on() method for adding a click event after loading dynamic html

Try this:

$('#parent').on('click', '#child', function() {
    // Code
});

From the $.on() documentation:

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

Your #child element doesn't exist when you call $.on() on it, so the event isn't bound (unlike $.live()). #parent, however, does exist, so binding the event to that is fine.

The second argument in my code above acts as a 'filter' to only trigger if the event bubbled up to #parent from #child.

"Expected an indented block" error?

I also experienced that for example:

This code doesnt work and get the intended block error.

class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()

def __unicode__(self):
return self.title

However, when i press tab before typing return self.title statement, the code works.

class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()

def __unicode__(self):
    return self.title

Hope, this will help others.

passing argument to DialogFragment

as a general way of working with Fragments, as JafarKhQ noted, you should not pass the params in the constructor but with a Bundle.

the built-in method for that in the Fragment class is setArguments(Bundle) and getArguments().

basically, what you do is set up a bundle with all your Parcelable items and send them on.
in turn, your Fragment will get those items in it's onCreate and do it's magic to them.

the way shown in the DialogFragment link was one way of doing this in a multi appearing fragment with one specific type of data and works fine most of the time, but you can also do this manually.

Converting Java objects to JSON with Jackson

To convert your object in JSON with Jackson:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);

Oracle: SQL query to find all the triggers belonging to the tables?

Another table that is useful is:

SELECT * FROM user_objects WHERE object_type='TRIGGER';

You can also use this to query views, indexes etc etc

JUnit Testing private variables?

First of all, you are in a bad position now - having the task of writing tests for the code you did not originally create and without any changes - nightmare! Talk to your boss and explain, it is not possible to test the code without making it "testable". To make code testable you usually do some important changes;

Regarding private variables. You actually never should do that. Aiming to test private variables is the first sign that something wrong with the current design. Private variables are part of the implementation, tests should focus on behavior rather of implementation details.

Sometimes, private field are exposed to public access with some getter. I do that, but try to avoid as much as possible (mark in comments, like 'used for testing').

Since you have no possibility to change the code, I don't see possibility (I mean real possibility, not like Reflection hacks etc.) to check private variable.

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

I'm using this one in VB.NET 2003 and it works well...

Private Function GetExcelColumnName(ByVal aiColNumber As Integer) As String
    Dim BaseValue As Integer = Convert.ToInt32(("A").Chars(0)) - 1
    Dim lsReturn As String = String.Empty

    If (aiColNumber > 26) Then
        lsReturn = GetExcelColumnName(Convert.ToInt32((Format(aiColNumber / 26, "0.0").Split("."))(0)))
    End If

    GetExcelColumnName = lsReturn + Convert.ToChar(BaseValue + (aiColNumber Mod 26))
End Function

Javascript Drag and drop for touch devices

I had the same solution as gregpress answer, but my draggable items used a class instead of an id. It seems to work.

var $target = $(event.target);  
if( $target.hasClass('draggable') ) {  
    event.preventDefault();  
}

How to use Oracle ORDER BY and ROWNUM correctly?

The where statement gets executed before the order by. So, your desired query is saying "take the first row and then order it by t_stamp desc". And that is not what you intend.

The subquery method is the proper method for doing this in Oracle.

If you want a version that works in both servers, you can use:

select ril.*
from (select ril.*, row_number() over (order by t_stamp desc) as seqnum
      from raceway_input_labo ril
     ) ril
where seqnum = 1

The outer * will return "1" in the last column. You would need to list the columns individually to avoid this.

How do I update Homebrew?

Alternatively you could update brew by installing it again. (Think I did this as El Capitan changed something)

Note: this is a heavy handed approach that will remove all applications installed via brew!

Try to install brew a fresh and it will tell how to uninstall.

At original time of writing to uninstall:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"

Edit: As of 2020 to uninstall:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"

Cookie blocked/not saved in IFRAME in Internet Explorer

A better solution would be to make an Ajax call inside the iframe to the page that would get/set cookies...

run program in Python shell

If you want to avoid writing all of this everytime, you can define a function :

def run(filename):
    exec(open(filename).read())

and then call it

run('filename.py')

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

The justify-self and justify-items properties are not implemented in flexbox. This is due to the one-dimensional nature of flexbox, and that there may be multiple items along the axis, making it impossible to justify a single item. To align items along the main, inline axis in flexbox you use the justify-content property.

Reference: Box alignment in CSS Grid Layout

How to flip background image using CSS?

You can flip both vertical and horizontal at the same time

    -moz-transform: scaleX(-1) scaleY(-1);
    -o-transform: scaleX(-1) scaleY(-1);
    -webkit-transform: scaleX(-1) scaleY(-1);
    transform: scaleX(-1) scaleY(-1);

And with the transition property you can get a cool flip

    -webkit-transition: transform .4s ease-out 0ms;
    -moz-transition: transform .4s ease-out 0ms;
    -o-transition: transform .4s ease-out 0ms;
    transition: transform .4s ease-out 0ms;
    transition-property: transform;
    transition-duration: .4s;
    transition-timing-function: ease-out;
    transition-delay: 0ms;

Actually it flips the whole element, not just the background-image

SNIPPET

_x000D_
_x000D_
function flip(){_x000D_
 var myDiv = document.getElementById('myDiv');_x000D_
 if (myDiv.className == 'myFlipedDiv'){_x000D_
  myDiv.className = '';_x000D_
 }else{_x000D_
  myDiv.className = 'myFlipedDiv';_x000D_
 }_x000D_
}
_x000D_
#myDiv{_x000D_
  display:inline-block;_x000D_
  width:200px;_x000D_
  height:20px;_x000D_
  padding:90px;_x000D_
  background-color:red;_x000D_
  text-align:center;_x000D_
  -webkit-transition:transform .4s ease-out 0ms;_x000D_
  -moz-transition:transform .4s ease-out 0ms;_x000D_
  -o-transition:transform .4s ease-out 0ms;_x000D_
  transition:transform .4s ease-out 0ms;_x000D_
  transition-property:transform;_x000D_
  transition-duration:.4s;_x000D_
  transition-timing-function:ease-out;_x000D_
  transition-delay:0ms;_x000D_
}_x000D_
.myFlipedDiv{_x000D_
  -moz-transform:scaleX(-1) scaleY(-1);_x000D_
  -o-transform:scaleX(-1) scaleY(-1);_x000D_
  -webkit-transform:scaleX(-1) scaleY(-1);_x000D_
  transform:scaleX(-1) scaleY(-1);_x000D_
}
_x000D_
<div id="myDiv">Some content here</div>_x000D_
_x000D_
<button onclick="flip()">Click to flip</button>
_x000D_
_x000D_
_x000D_

What is the difference between Normalize.css and Reset CSS?

The major difference is that:

  • CSS resets aim to remove all built-in browser styling. Standard elements like H1-6, p, strong, em, et cetera end up looking exactly alike, having no decoration at all. You're then supposed to add all decoration yourself.

  • Normalize CSS aims to make built-in browser styling consistent across browsers. Elements like H1-6 will appear bold, larger et cetera in a consistent way across browsers. You're then supposed to add only the difference in decoration your design needs.

If your design a) follows common conventions for typography et cetera, and b) Normalize.css works for your target audience, then using Normalize.CSS instead of a CSS reset will make your own CSS smaller and faster to write.

Auto refresh page every 30 seconds

Just a simple line of code in the head section can refresh the page

<meta http-equiv="refresh" content="30">

although its not a javascript function, its the simplest way to accomplish the above task hopefully.

How to redirect Valgrind's output to a file?

valgrind --log-file="filename"

How to disable keypad popup when on edittext?

In a Android app I was building, I had three EditTexts in a LinearLayout arranged horizontally. I had to prevent the soft keyboard from appearing when the fragment loaded. In addition to setting focusable and focusableInTouchMode to true on the LinearLayout, I had to set descendantFocusability to blocksDescendants. In onCreate, I called requestFocus on the LinearLayout. This prevented the keyboard from appearing when the fragment is created.

Layout -

    <LinearLayout
       android:id="@+id/text_selector_container"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:weightSum="3"
       android:orientation="horizontal"
       android:focusable="true"
       android:focusableInTouchMode="true"
       android:descendantFocusability="blocksDescendants"
       android:background="@color/black">

       <!-- EditText widgets -->

    </LinearLayout>

In onCreate - mTextSelectorContainer.requestFocus();

UIView's frame, bounds, center, origin, when to use what?

They are related values, and kept consistent by the property setter/getter methods (and using the fact that frame is a purely synthesized value, not backed by an actual instance variable).

The main equations are:

frame.origin = center - bounds.size / 2

(which is the same as)

center = frame.origin + bounds.size / 2

(and there’s also)

frame.size = bounds.size

That's not code, just equations to express the invariant between the three properties. These equations also assume your view's transform is the identity, which it is by default. If it's not, then bounds and center keep the same meaning, but frame can change. Unless you're doing non-right-angle rotations, the frame will always be the transformed view in terms of the superview's coordinates.

This stuff is all explained in more detail with a useful mini-library here:

http://bynomial.com/blog/?p=24

org.hibernate.MappingException: Unknown entity

You can enable entity scan by adding below annotation on Application .java @EntityScan(basePackageClasses=YourEntityClassName.class)

Or you can set the packageToScan in your session factory. sessionFactory.setPackagesToScan(“com.all.entity”);

How to insert array of data into mysql using php

First of all you should stop using mysql_*. MySQL supports multiple inserting like

INSERT INTO example
VALUES
  (100, 'Name 1', 'Value 1', 'Other 1'),
  (101, 'Name 2', 'Value 2', 'Other 2'),
  (102, 'Name 3', 'Value 3', 'Other 3'),
  (103, 'Name 4', 'Value 4', 'Other 4');

You just have to build one string in your foreach loop which looks like that

$values = "(100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1')";

and then insert it after the loop

$sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) VALUES ".$values;

Another way would be Prepared Statements, which are even more suited for your situation.

Delete specific line from a text file?

I cared about the file's original end line characters ("\n" or "\r\n") and wanted to maintain them in the output file (not overwrite them with what ever the current environment's char(s) are like the other answers appear to do). So I wrote my own method to read a line without removing the end line chars then used it in my DeleteLines method (I wanted the option to delete multiple lines, hence the use of a collection of line numbers to delete).

DeleteLines was implemented as a FileInfo extension and ReadLineKeepNewLineChars a StreamReader extension (but obviously you don't have to keep it that way).

public static class FileInfoExtensions
{
    public static FileInfo DeleteLines(this FileInfo source, ICollection<int> lineNumbers, string targetFilePath)
    {
        var lineCount = 1;

        using (var streamReader = new StreamReader(source.FullName))
        {
            using (var streamWriter = new StreamWriter(targetFilePath))
            {
                string line;

                while ((line = streamReader.ReadLineKeepNewLineChars()) != null)
                {
                    if (!lineNumbers.Contains(lineCount))
                    {
                        streamWriter.Write(line);
                    }

                    lineCount++;
                }
            }
        }

        return new FileInfo(targetFilePath);
    }
}

public static class StreamReaderExtensions
{
    private const char EndOfFile = '\uffff';

    /// <summary>
    /// Reads a line, similar to ReadLine method, but keeps any
    /// new line characters (e.g. "\r\n" or "\n").
    /// </summary>
    public static string ReadLineKeepNewLineChars(this StreamReader source)
    {
        if (source == null)
            throw new ArgumentNullException(nameof(source));

        char ch = (char)source.Read();

        if (ch == EndOfFile)
            return null;

        var sb = new StringBuilder();

        while (ch !=  EndOfFile)
        {
            sb.Append(ch);

            if (ch == '\n')
                break;

            ch = (char) source.Read();
        }

        return sb.ToString();
    }
}

How to refresh the data in a jqGrid?

$('#grid').trigger( 'reloadGrid' );

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

For me, I accidentally included my local database name inside the SQL query, hence the access denied issue came up when I deployed.

I removed the database name from the SQL query and it got fixed.

How many bits or bytes are there in a character?

It depends what is the character and what encoding it is in:

  • An ASCII character in 8-bit ASCII encoding is 8 bits (1 byte), though it can fit in 7 bits.

  • An ISO-8895-1 character in ISO-8859-1 encoding is 8 bits (1 byte).

  • A Unicode character in UTF-8 encoding is between 8 bits (1 byte) and 32 bits (4 bytes).

  • A Unicode character in UTF-16 encoding is between 16 (2 bytes) and 32 bits (4 bytes), though most of the common characters take 16 bits. This is the encoding used by Windows internally.

  • A Unicode character in UTF-32 encoding is always 32 bits (4 bytes).

  • An ASCII character in UTF-8 is 8 bits (1 byte), and in UTF-16 - 16 bits.

  • The additional (non-ASCII) characters in ISO-8895-1 (0xA0-0xFF) would take 16 bits in UTF-8 and UTF-16.

That would mean that there are between 0.03125 and 0.125 characters in a bit.

IntelliJ does not show project folders

When importing your project/module be sure to check these two boxes:

enter image description here

Remove a file from the list that will be committed

Use stash; like this:

git add .
git reset Files/I/Want/To/Keep
git stash --keep-index
git commit -a -m "Done!"
git stash pop

If you accidentally commit a file, and want to rewrite your git history, use:

git reset HEAD~1 path/to/file
git commit -a -m "rollback"
git rebase -i HEAD~2

and squash to the two leading commits. You can write a helper script to do either of these if you have a known set of files you prefer not to automatically commit.

How do I display Ruby on Rails form validation error messages one at a time?

After experimenting for a few hours I figured it out.

<% if @user.errors.full_messages.any? %>
  <% @user.errors.full_messages.each do |error_message| %>
    <%= error_message if @user.errors.full_messages.first == error_message %> <br />
  <% end %>
<% end %>

Even better:

<%= @user.errors.full_messages.first if @user.errors.any? %>

How do you create a yes/no boolean field in SQL server?

bit will be the simplest and also takes up the least space. Not very verbose compared to "Y/N" but I am fine with it.

How to implement a Navbar Dropdown Hover in Bootstrap v4?

I couldn't find here the full solution. So, it's my one which works with Bootstrap v4.4.1 and has the next benefits:

  • A click on the dropdown-toggle works as a normal nav link.

  • Supports any nesting level of dropdown menus.

  • Bootstrap 4 {show/shown/hide/hidden}.bs.dropdown events work well.

     // Toggles a B4 dropdown-menu to a given state.
     const toggleDropdownElement = ($dropdown, shouldOpen = false) => {
       const $dropdownToggle = $dropdown.children('[data-toggle="dropdown"], a');
       const $dropdownMenu = $dropdown.children('.dropdown-menu');
    
       // Change the dropdown menu. It's similar to B4 Dropdown.show()/.hide(), see /bootstrap/js/src/dropdown.js.
       if (shouldOpen) {
         $dropdown.trigger('show.bs.dropdown');
         $dropdownToggle.attr('aria-expanded', true).focus();
         $dropdownMenu.addClass('show');
         $dropdown.addClass('show').trigger($.Event('shown.bs.dropdown', $dropdownMenu[0]));
       } else {
         $dropdown.trigger('hide.bs.dropdown');
         $dropdownToggle.attr('aria-expanded', false);
         $dropdownMenu.removeClass('show');
         $dropdown.removeClass('show').trigger($.Event('hidden.bs.dropdown', $dropdownMenu[0]));
       }
     };
    
     // Toggles a B4 dropdown-menu with any nesting level.
     const toggleDropdown = (event) => {
       const $dropdown = $(event.target).closest('.dropdown');
       const $parentDropdownMenu = $dropdown.closest('.dropdown-menu');
       const shouldOpen = event.type !== 'click' && $dropdown.is(':hover');
    
       // If the dropdown was closed already, break the 'mouseleave' event cascade.
       if (!shouldOpen && !$dropdown.hasClass('show')) return;
    
       // Change the current dropdown menu (last nested).
       toggleDropdownElement($dropdown, shouldOpen);
    
       // We have to close the dropdown menu tree if it was a click or the menu was leave at all.
       if (event.type === 'click' || $parentDropdownMenu.length && !$parentDropdownMenu.is(':hover')) {
         $dropdown.parents('.dropdown').each((index, element) => {
           toggleDropdownElement($(element), false);
         });
       }
     };
    
     if (viewport && viewport.is('>=xl')) {
       $('body')
         .on('mouseenter mouseleave', '.dropdown', toggleDropdown)
         .on('click', '.dropdown-menu a', toggleDropdown);
    
       // Disable the default B4's click. Other words, change a dropdown-toggle to a normal nav link.
       $(document).off('click.bs.dropdown', '[data-toggle="dropdown"]');
       $(document).off('click.bs.dropdown.data-api', '[data-toggle="dropdown"]'); // Not sure about it.
     }
    

If you don't use ES6 just change arrow functions to the old function style.

Thanks, @tao for your example, it was helpful for me.

Code related links: B4 Dropdown Events, viewport (Responsive Bootstrap Toolkit), WP Bootstrap Navwalker.

Automate scp file transfer using a shell script

The command scp can be used like a traditional UNIX cp. SO if you do :

scp -r myDirectory/ mylogin@host:TargetDirectory

will work

Retrieve the position (X,Y) of an HTML element relative to the browser window

HTML elements on most browsers will have:-

offsetLeft
offsetTop

These specifiy the position of the element relative its nearest parent that has layout. This parent can often be accessed bif the offsetParent property.

IE and FF3 have

clientLeft
clientTop

These properties are less common, they specify an elements position with its parents client area (padded area is part of the client area but border and margin is not).

jQuery click event not working after adding class

I Know this is an old topic...but none of the above helped me. And after searching a lot and trying everything...I came up with this.

First remove the click code out of the $(document).ready part and put it in a separate section. then put your click code in an $(function(){......}); code.

Like this:

<script>
  $(function(){
    //your click code
    $("a.tabclick").on('click',function() {
      //do something
    });
  });
</script>

Powershell equivalent of bash ampersand (&) for forking/running background processes

Seems that the script block passed to Start-Job is not executed with the same current directory as the Start-Job command, so make sure to specify fully qualified path if needed.

For example:

Start-Job { C:\absolute\path\to\command.exe --afileparameter C:\absolute\path\to\file.txt }

Remove multiple objects with rm()

An other solution rm(list=ls(pattern="temp")), remove all objects matching the pattern.

Pass multiple arguments into std::thread

You literally just pass them in std::thread(func1,a,b,c,d); that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminate is called. You could std::join or std::detach it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach .

This is how it should be done.

std::thread t(func1,a,b,c,d);
t.join();  

You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.

How does numpy.histogram() work?

import numpy as np    
hist, bin_edges = np.histogram([1, 1, 2, 2, 2, 2, 3], bins = range(5))

Below, hist indicates that there are 0 items in bin #0, 2 in bin #1, 4 in bin #3, 1 in bin #4.

print(hist)
# array([0, 2, 4, 1])   

bin_edges indicates that bin #0 is the interval [0,1), bin #1 is [1,2), ..., bin #3 is [3,4).

print (bin_edges)
# array([0, 1, 2, 3, 4]))  

Play with the above code, change the input to np.histogram and see how it works.


But a picture is worth a thousand words:

import matplotlib.pyplot as plt
plt.bar(bin_edges[:-1], hist, width = 1)
plt.xlim(min(bin_edges), max(bin_edges))
plt.show()   

enter image description here

How to compare timestamp dates with date-only parameter in MySQL?

As I was researching this I thought it would be nice to modify the BETWEEN solution to show an example for a particular non-static/string date, but rather a variable date, or today's such as CURRENT_DATE(). This WILL use the index on the log_timestamp column.

SELECT *
FROM some_table
WHERE
    log_timestamp
    BETWEEN 
        timestamp(CURRENT_DATE()) 
    AND # Adds 23.9999999 HRS of seconds to the current date
        timestamp(DATE_ADD(CURRENT_DATE(), INTERVAL '86399.999999' SECOND_MICROSECOND));

I did the seconds/microseconds to avoid the 12AM case on the next day. However, you could also do `INTERVAL '1 DAY' via comparison operators for a more reader-friendly non-BETWEEN approach:

SELECT *
FROM some_table
WHERE
    log_timestamp >= timestamp(CURRENT_DATE()) AND
    log_timestamp < timestamp(DATE_ADD(CURRENT_DATE(), INTERVAL 1 DAY));

Both of these approaches will use the index and should perform MUCH faster. Both seem to be equally as fast.

Insert a new row into DataTable

@William You can use NewRow method of the datatable to get a blank datarow and with the schema as that of the datatable. You can populate this datarow and then add the row to the datatable using .Rows.Add(DataRow) OR .Rows.InsertAt(DataRow, Position). The following is a stub code which you can modify as per your convenience.

//Creating dummy datatable for testing
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("col1", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col2", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col3", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col4", typeof(String));
dt.Columns.Add(dc);

DataRow dr = dt.NewRow();

dr[0] = "coldata1";
dr[1] = "coldata2";
dr[2] = "coldata3";
dr[3] = "coldata4";

dt.Rows.Add(dr);//this will add the row at the end of the datatable
//OR
int yourPosition = 0;
dt.Rows.InsertAt(dr, yourPosition);

How to get only numeric column values?

Use This [Tested]

To get numeric

SELECT column1
FROM table
WHERE Isnumeric(column1) = 1; // will return Numeric values

To get non-numeric

SELECT column1
FROM table
WHERE Isnumeric(column1) = 0; // will return non-numeric values

Check date with todays date

tl;dr

LocalDate
.parse( "2021-01-23" )
.isBefore(
    LocalDate.now(
        ZoneId.of( "Africa/Tunis" ) 
    )
)

… or:

try 
{
    org.threeten.extra.LocalDateRange range =         
        LocalDateRange.of( 
            LocalDate.of( "2021-01-23" ) ,
            LocalDate.of( "2021-02-21" )
        )
    ;
    if( range.isAfter( 
        LocalDate.now( ZoneId.of( "Africa/Tunis" ) )
    ) { … }
    else { … handle today being within or after the range. }
} catch ( java.time.DateTimeException e ) {
    // Handle error where end is before start.
}

Details

The other answers ignore the crucial issue of time zone.

The other answers use outmoded classes.

Avoid old date-time classes

The old date-time classes bundled with the earliest versions of Java are poorly designed, confusing, and troublesome. Avoid java.util.Date/.Calendar and related classes.

java.time

LocalDate

For date-only values, without time-of-day and without time zone, use the LocalDate class.

LocalDate start = LocalDate.of( 2016 , 1 , 1 );
LocalDate stop = start.plusWeeks( 1 );

Time Zone

Be aware that while LocalDate does not store a time zone, determining a date such as “today” requires a time zone. For any given moment, the date may vary around the world by time zone. For example, a new day dawns earlier in Paris than in Montréal. A moment after midnight in Paris is still “yesterday” in Montréal.

If all you have is an offset-from-UTC, use ZoneOffset. If you have a full time zone (continent/region), then use ZoneId. If you want UTC, use the handy constant ZoneOffset.UTC.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );

Comparing is easy with isEqual, isBefore, and isAfter methods.

boolean invalidInterval = stop.isBefore( start );

We can check to see if today is contained within this date range. In my logic shown here I use the Half-Open approach where the beginning is inclusive while the ending is exclusive. This approach is common in date-time work. So, for example, a week runs from a Monday going up to but not including the following Monday.

// Is today equal or after start (not before) AND today is before stop.
boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ) ;

LocalDateRange

If working extensively with such spans of time, consider adding the ThreeTen-Extra library to your project. This library extends the java.time framework, and is the proving ground for possible additions to java.time.

ThreeTen-Extra includes an LocalDateRange class with handy methods such as abuts, contains, encloses, overlaps, and so on.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Changing Placeholder Text Color with Swift

Swift 4 :

txtControl.attributedPlaceholder = NSAttributedString(string: "Placeholder String...",attributes: [NSAttributedStringKey.foregroundColor: UIColor.gray])

Objective-C :

UIColor *color = [UIColor grayColor];
txtControl.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Placeholder String..." attributes:@{NSForegroundColorAttributeName: color}];

CUDA incompatible with my gcc version

On most distributions you have the possibility to install another gcc and g++ version beside a most recent compiler like gcc-4.7. In addition most build systems are aware of the CC and CXX environment variables, which let specify you other C and C++ compilers respectively. SO I suggest something like:

CC=gcc-4.4 CXX=g++-4.4 cmake path/to/your/CMakeLists.txt

For Makefiles there should be a similar way. I do not recommend setting custom symlinks within /usr/local unless you know what you are doing.

pandas groupby sort within groups

If you don't need to sum a column, then use @tvashtar's answer. If you do need to sum, then you can use @joris' answer or this one which is very similar to it.

df.groupby(['job']).apply(lambda x: (x.groupby('source')
                                      .sum()
                                      .sort_values('count', ascending=False))
                                     .head(3))

Excel select a value from a cell having row number calculated

You could use the INDIRECT function. This takes a string and converts it into a range

More info here

=INDIRECT("K"&A2)

But it's preferable to use INDEX as it is less volatile.

=INDEX(K:K,A2)

This returns a value or the reference to a value from within a table or range

More info here

Put either function into cell B2 and fill down.

How to create Select List for Country and States/province in MVC

So many ways to do this... for #NetCore use Lib..

    using System;
    using System.Collections.Generic;
    using System.Linq; // only required when .AsEnumerable() is used
    using System.ComponentModel.DataAnnotations;
    using Microsoft.AspNetCore.Mvc.Rendering;

Model...

namespace MyProject.Models
{
  public class MyModel
  {
    [Required]
    [Display(Name = "State")]
    public string StatePick { get; set; }
    public string state { get; set; }
    [StringLength(35, ErrorMessage = "State cannot be longer than 35 characters.")]
    public SelectList StateList { get; set; }
  }
}

Controller...

namespace MyProject.Controllers
{
    /// <summary>
    /// create SelectListItem from strings
    /// </summary>
    /// <param name="isValue">defaultValue is SelectListItem.Value is true, SelectListItem.Text if false</param>
    /// <returns></returns>
    private SelectListItem newItem(string value, string text, string defaultValue = "", bool isValue = false)
    {
        SelectListItem ss = new SelectListItem();
        ss.Text = text;
        ss.Value = value;

        // select default by Value or Text
        if (isValue && ss.Value == defaultValue || !isValue && ss.Text == defaultValue)
        {
            ss.Selected = true;
        }

        return ss;
    }

    /// <summary>
    /// this pulls the state name from _context and sets it as the default for the selectList
    /// </summary>
    /// <param name="myState">sets default value for list of states</param>
    /// <returns></returns>
    private SelectList getStateList(string myState = "")
    {
        List<SelectListItem> states = new List<SelectListItem>();
        SelectListItem chosen = new SelectListItem();

        // set default selected state to OHIO
        string defaultValue = "OH";
        if (!string.IsNullOrEmpty(myState))
        {
            defaultValue = myState;
        }

        try
        {
            states.Add(newItem("AL", "Alabama", defaultValue, true));
            states.Add(newItem("AK", "Alaska", defaultValue, true));
            states.Add(newItem("AZ", "Arizona", defaultValue, true));
            states.Add(newItem("AR", "Arkansas", defaultValue, true));
            states.Add(newItem("CA", "California", defaultValue, true));
            states.Add(newItem("CO", "Colorado", defaultValue, true));
            states.Add(newItem("CT", "Connecticut", defaultValue, true));
            states.Add(newItem("DE", "Delaware", defaultValue, true));
            states.Add(newItem("DC", "District of Columbia", defaultValue, true));
            states.Add(newItem("FL", "Florida", defaultValue, true));
            states.Add(newItem("GA", "Georgia", defaultValue, true));
            states.Add(newItem("HI", "Hawaii", defaultValue, true));
            states.Add(newItem("ID", "Idaho", defaultValue, true));
            states.Add(newItem("IL", "Illinois", defaultValue, true));
            states.Add(newItem("IN", "Indiana", defaultValue, true));
            states.Add(newItem("IA", "Iowa", defaultValue, true));
            states.Add(newItem("KS", "Kansas", defaultValue, true));
            states.Add(newItem("KY", "Kentucky", defaultValue, true));
            states.Add(newItem("LA", "Louisiana", defaultValue, true));
            states.Add(newItem("ME", "Maine", defaultValue, true));
            states.Add(newItem("MD", "Maryland", defaultValue, true));
            states.Add(newItem("MA", "Massachusetts", defaultValue, true));
            states.Add(newItem("MI", "Michigan", defaultValue, true));
            states.Add(newItem("MN", "Minnesota", defaultValue, true));
            states.Add(newItem("MS", "Mississippi", defaultValue, true));
            states.Add(newItem("MO", "Missouri", defaultValue, true));
            states.Add(newItem("MT", "Montana", defaultValue, true));
            states.Add(newItem("NE", "Nebraska", defaultValue, true));
            states.Add(newItem("NV", "Nevada", defaultValue, true));
            states.Add(newItem("NH", "New Hampshire", defaultValue, true));
            states.Add(newItem("NJ", "New Jersey", defaultValue, true));
            states.Add(newItem("NM", "New Mexico", defaultValue, true));
            states.Add(newItem("NY", "New York", defaultValue, true));
            states.Add(newItem("NC", "North Carolina", defaultValue, true));
            states.Add(newItem("ND", "North Dakota", defaultValue, true));
            states.Add(newItem("OH", "Ohio", defaultValue, true));
            states.Add(newItem("OK", "Oklahoma", defaultValue, true));
            states.Add(newItem("OR", "Oregon", defaultValue, true));
            states.Add(newItem("PA", "Pennsylvania", defaultValue, true));
            states.Add(newItem("RI", "Rhode Island", defaultValue, true));
            states.Add(newItem("SC", "South Carolina", defaultValue, true));
            states.Add(newItem("SD", "South Dakota", defaultValue, true));
            states.Add(newItem("TN", "Tennessee", defaultValue, true));
            states.Add(newItem("TX", "Texas", defaultValue, true));
            states.Add(newItem("UT", "Utah", defaultValue, true));
            states.Add(newItem("VT", "Vermont", defaultValue, true));
            states.Add(newItem("VA", "Virginia", defaultValue, true));
            states.Add(newItem("WA", "Washington", defaultValue, true));
            states.Add(newItem("WV", "West Virginia", defaultValue, true));
            states.Add(newItem("WI", "Wisconsin", defaultValue, true));
            states.Add(newItem("WY", "Wyoming", defaultValue, true));

            foreach (SelectListItem state in states)
            {
                if (state.Selected)
                {
                    chosen = state;
                    break;
                }
            }
        }
        catch (Exception err)
        {
            string ss = "ERR!   " + err.Source + "   " + err.GetType().ToString() + "\r\n" + err.Message.Replace("\r\n", "   ");
            ss = this.sendError("Online getStateList Request", ss, _errPassword);
            // return error
        }

        // .AsEnumerable() is not required in the pass.. it is an extension of Linq
        SelectList myList = new SelectList(states.AsEnumerable(), "Value", "Text", chosen);

        object val = myList.SelectedValue;

        return myList;
    }

    public ActionResult pickState(MyModel pData)
    {
        if (pData.StateList == null)
        {
            if (String.IsNullOrEmpty(pData.StatePick)) // state abbrev, value collected onchange
            {
                pData.StateList = getStateList();
            }
            else
            {
                pData.StateList = getStateList(pData.StatePick);
            }

            // assign values to state list items
            try
            {
                SelectListItem si = (SelectListItem)pData.StateList.SelectedValue;
                pData.state = si.Value;
                pData.StatePick = si.Value;
            }
            catch { }
        } 
    return View(pData);
    }
}

pickState.cshtml...

@model MyProject.Models.MyModel

@{
ViewBag.Title = "United States of America";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>@ViewBag.Title - Where are you...</h2>

@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>

    <div class="editor-label">
        @Html.DisplayNameFor(model => model.state)
    </div>
    <div class="display-field">            
        @Html.DropDownListFor(m => m.StatePick, Model.StateList, new { OnChange = "state.value = this.value;" })
        @Html.EditorFor(model => model.state)
        @Html.ValidationMessageFor(model => model.StateList)
    </div>         
</fieldset>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

Mongoose (mongodb) batch insert?

You can perform bulk insert using mongoDB shell using inserting the values in an array.

db.collection.insert([{values},{values},{values},{values}]);

How can I have linebreaks in my long LaTeX equations?

multline is best to use. Instead, you can use dmath, split as well.

Here is an example:

\begin{multline}
  {\text {\bf \emph {T(u)}}} ={  \alpha *}{\frac{\sum_{i=1}^{\text{\bf \emph {I(u)}}}{{\text{\bf \emph {S(u,i)}}}* {\text {\bf \emph {Cr(P(u,i))}}} * {\text {\bf \emph {TF(u,i)}}}}}{\text {\bf \emph {I(u)}}}}  \\
   +{  \beta *}{\frac{\sum_{i=1}^{\text{\bf \emph {$I_h$(u)}}}{{\text{\bf \emph {S(u,i)}}}* {\text {\bf \emph {Cr(P(u,i))}}} * {\text {\bf \emph {TF(u,i)}}}}}{\text {\bf \emph {$I_h$(u)}}}}
\end{multline}

Best way to split string into lines

  • If it looks ugly, just remove the unnecessary ToCharArray call.

  • If you want to split by either \n or \r, you've got two options:

    • Use an array literal – but this will give you empty lines for Windows-style line endings \r\n:

      var result = text.Split(new [] { '\r', '\n' });
      
    • Use a regular expression, as indicated by Bart:

      var result = Regex.Split(text, "\r\n|\r|\n");
      
  • If you want to preserve empty lines, why do you explicitly tell C# to throw them away? (StringSplitOptions parameter) – use StringSplitOptions.None instead.

How to change owner of PostgreSql database?

Frank Heikens answer will only update database ownership. Often, you also want to update ownership of contained objects (including tables). Starting with Postgres 8.2, REASSIGN OWNED is available to simplify this task.

IMPORTANT EDIT!

Never use REASSIGN OWNED when the original role is postgres, this could damage your entire DB instance. The command will update all objects with a new owner, including system resources (postgres0, postgres1, etc.)


First, connect to admin database and update DB ownership:

psql
postgres=# REASSIGN OWNED BY old_name TO new_name;

This is a global equivalent of ALTER DATABASE command provided in Frank's answer, but instead of updating a particular DB, it change ownership of all DBs owned by 'old_name'.

The next step is to update tables ownership for each database:

psql old_name_db
old_name_db=# REASSIGN OWNED BY old_name TO new_name;

This must be performed on each DB owned by 'old_name'. The command will update ownership of all tables in the DB.

Quick-and-dirty way to ensure only one instance of a shell script is running at a time

Here is a more elegant, fail-safe, quick & dirty method, combining the answers provided above.

Usage

  1. include sh_lock_functions.sh
  2. init using sh_lock_init
  3. lock using sh_acquire_lock
  4. check lock using sh_check_lock
  5. unlock using sh_remove_lock

Script File

sh_lock_functions.sh

#!/bin/bash

function sh_lock_init {
    sh_lock_scriptName=$(basename $0)
    sh_lock_dir="/tmp/${sh_lock_scriptName}.lock" #lock directory
    sh_lock_file="${sh_lock_dir}/lockPid.txt" #lock file
}

function sh_acquire_lock {
    if mkdir $sh_lock_dir 2>/dev/null; then #check for lock
        echo "$sh_lock_scriptName lock acquired successfully.">&2
        touch $sh_lock_file
        echo $$ > $sh_lock_file # set current pid in lockFile
        return 0
    else
        touch $sh_lock_file
        read sh_lock_lastPID < $sh_lock_file
        if [ ! -z "$sh_lock_lastPID" -a -d /proc/$sh_lock_lastPID ]; then # if lastPID is not null and a process with that pid exists
            echo "$sh_lock_scriptName is already running.">&2
            return 1
        else
            echo "$sh_lock_scriptName stopped during execution, reacquiring lock.">&2
            echo $$ > $sh_lock_file # set current pid in lockFile
            return 2
        fi
    fi
    return 0
}

function sh_check_lock {
    [[ ! -f $sh_lock_file ]] && echo "$sh_lock_scriptName lock file removed.">&2 && return 1
    read sh_lock_lastPID < $sh_lock_file
    [[ $sh_lock_lastPID -ne $$ ]] && echo "$sh_lock_scriptName lock file pid has changed.">&2  && return 2
    echo "$sh_lock_scriptName lock still in place.">&2
    return 0
}

function sh_remove_lock {
    rm -r $sh_lock_dir
}

Usage example

sh_lock_usage_example.sh

#!/bin/bash
. /path/to/sh_lock_functions.sh # load sh lock functions

sh_lock_init || exit $?

sh_acquire_lock
lockStatus=$?
[[ $lockStatus -eq 1 ]] && exit $lockStatus
[[ $lockStatus -eq 2 ]] && echo "lock is set, do some resume from crash procedures";

#monitoring example
cnt=0
while sh_check_lock # loop while lock is in place
do
    echo "$sh_scriptName running (pid $$)"
    sleep 1
    let cnt++
    [[ $cnt -gt 5 ]] && break
done

#remove lock when process finished
sh_remove_lock || exit $?

exit 0

Features

  • Uses a combination of file, directory and process id to lock to make sure that the process is not already running
  • You can detect if the script stopped before lock removal (eg. process kill, shutdown, error etc.)
  • You can check the lock file, and use it to trigger a process shutdown when the lock is missing
  • Verbose, outputs error messages for easier debug

Hash string in c#

I don't really understand the full scope of your question, but if all you need is a hash of the string, then it's very easy to get that.

Just use the GetHashCode method.

Like this:

string hash = username.GetHashCode();

Writing new lines to a text file in PowerShell

It's also possible to assign newline and carriage return to variables and then append them to texts inside PowerShell scripts:

$OFS = "`r`n"
$msg = "This is First Line" + $OFS + "This is Second Line" + $OFS
Write-Host $msg

How can I pretty-print JSON using node.js?

what about this?

console.table(object)

sample

Write to text file without overwriting in Java

Here is a simple example of how it works, best practice to put a try\catch into it but for basic use this should do the trick. For this you have a string and file path and apply thus to the FileWriter and the BufferedWriter. This will write "Hello World"(Data variable) and then make a new line. each time this is run it will add the Data variable to the next line.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;


String Data = "Hello World";
File file = new File("C:/Users/stuff.txt");
FileWriter fw = new FileWriter(file,true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(Data);
bw.newLine();
bw.close();

How to make inline functions in C#

C# 7 adds support for local functions

Here is the previous example using a local function

void Method()
{
    string localFunction(string source)
    {
        // add your functionality here
        return source ;
    };

   // call the inline function
   localFunction("prefix");
}

Sending and receiving data over a network using TcpClient

I have had luck using the socket object directly (rather than the TCP client). I create a Server object that looks something like this (I've edited some stuff such as exception handling out for brevity, but I hope that the idea comes across.)...

public class Server()
{
    private Socket sock;
    // You'll probably want to initialize the port and address in the
    // constructor, or via accessors, but to start your server listening
    // on port 8080 and on any IP address available on the machine...
    private int port = 8080;
    private IPAddress addr = IPAddress.Any;

    // This is the method that starts the server listening.
    public void Start()
    {
        // Create the new socket on which we'll be listening.
        this.sock = new Socket(
            addr.AddressFamily,
            SocketType.Stream,
            ProtocolType.Tcp);
        // Bind the socket to the address and port.
        sock.Bind(new IPEndPoint(this.addr, this.port));
        // Start listening.
        this.sock.Listen(this.backlog);
        // Set up the callback to be notified when somebody requests
        // a new connection.
        this.sock.BeginAccept(this.OnConnectRequest, sock);
    }

    // This is the method that is called when the socket recives a request
    // for a new connection.
    private void OnConnectRequest(IAsyncResult result)
    {
        // Get the socket (which should be this listener's socket) from
        // the argument.
        Socket sock = (Socket)result.AsyncState;
        // Create a new client connection, using the primary socket to
        // spawn a new socket.
        Connection newConn = new Connection(sock.EndAccept(result));
        // Tell the listener socket to start listening again.
        sock.BeginAccept(this.OnConnectRequest, sock);
    }
}

Then, I use a separate Connection class to manage the individual connection with the remote host. That looks something like this...

public class Connection()
{
    private Socket sock;
    // Pick whatever encoding works best for you.  Just make sure the remote 
    // host is using the same encoding.
    private Encoding encoding = Encoding.UTF8;

    public Connection(Socket s)
    {
        this.sock = s;
        // Start listening for incoming data.  (If you want a multi-
        // threaded service, you can start this method up in a separate
        // thread.)
        this.BeginReceive();
    }

    // Call this method to set this connection's socket up to receive data.
    private void BeginReceive()
    {
        this.sock.BeginReceive(
                this.dataRcvBuf, 0,
                this.dataRcvBuf.Length,
                SocketFlags.None,
                new AsyncCallback(this.OnBytesReceived),
                this);
    }

    // This is the method that is called whenever the socket receives
    // incoming bytes.
    protected void OnBytesReceived(IAsyncResult result)
    {
        // End the data receiving that the socket has done and get
        // the number of bytes read.
        int nBytesRec = this.sock.EndReceive(result);
        // If no bytes were received, the connection is closed (at
        // least as far as we're concerned).
        if (nBytesRec <= 0)
        {
            this.sock.Close();
            return;
        }
        // Convert the data we have to a string.
        string strReceived = this.encoding.GetString(
            this.dataRcvBuf, 0, nBytesRec);

        // ...Now, do whatever works best with the string data.
        // You could, for example, look at each character in the string
        // one-at-a-time and check for characters like the "end of text"
        // character ('\u0003') from a client indicating that they've finished
        // sending the current message.  It's totally up to you how you want
        // the protocol to work.

        // Whenever you decide the connection should be closed, call 
        // sock.Close() and don't call sock.BeginReceive() again.  But as long 
        // as you want to keep processing incoming data...

        // Set up again to get the next chunk of data.
        this.sock.BeginReceive(
            this.dataRcvBuf, 0,
            this.dataRcvBuf.Length,
            SocketFlags.None,
            new AsyncCallback(this.OnBytesReceived),
            this);

    }
}

You can use your Connection object to send data by calling its Socket directly, like so...

this.sock.Send(this.encoding.GetBytes("Hello to you, remote host."));

As I said, I've tried to edit the code here for posting, so I apologize if there are any errors in it.

Python find elements in one list that are not in the other

Not sure why the above explanations are so complicated when you have native methods available:

main_list = list(set(list_2)-set(list_1))

How to update attributes without validation

All the validation from model are skipped when we use validate: false

user = User.new(....)
user.save(validate: false)

VB.NET - Remove a characters from a String

The String class has a Replace method that will do that.

Dim clean as String
clean = myString.Replace(",", "")

Effective way to find any file's Encoding

It may be useful

string path = @"address/to/the/file.extension";

using (StreamReader sr = new StreamReader(path))
{ 
    Console.WriteLine(sr.CurrentEncoding);                        
}

How to use linux command line ftp with a @ sign in my username?

I've never seen the -u parameter. But if you want to use an "@", how about stating it as "\@"?

That way it should be interpreted as you intend. You know something like

ftp -u user\@[email protected]

jQuery deferreds and promises - .then() vs .done()

.done() terminates the promise chain, making sure nothing else can attach further steps. This means that the jQuery promise implementation can throw any unhandled exception, since no one can possible handle it using .fail().

In practical terms, if you do not plan to attach more steps to a promise, you should use .done(). For more details see why promises need to be done

Get characters after last / in url

$str = basename($url);

SVN change username

for Win10 you should remove this folder and close/open your IDE

C:\Users\User\AppData\Roaming\Subversion\auth

, also in my projects no ".subversion" folders, only ".svn"

jQuery validation: change default error message

$(function() {

$("#username_error_message").hide();
$("#password_error_message").hide();
$("#retype_password_error_message").hide();
$("#email_error_message").hide();

var error_username = false;
var error_password = false;
var error_retype_password = false;
var error_email = false;

$("#form_username").focusout(function() {

    check_username();
    
});

$("#form_password").focusout(function() {

    check_password();
    
});

$("#form_retype_password").focusout(function() {

    check_retype_password();
    
});

$("#form_email").focusout(function() {

    check_email();
    
});

function check_username() {

    var username_length = $("#form_username").val().length;
    
    if(username_length < 5 || username_length > 20) {
        $("#username_error_message").html("Should be between 5-20 characters");
        $("#username_error_message").show();
        error_username = true;
    } else {
        $("#username_error_message").hide();
    }

}

function check_password() {

    var password_length = $("#form_password").val().length;
    
    if(password_length < 8) {
        $("#password_error_message").html("At least 8 characters");
        $("#password_error_message").show();
        error_password = true;
    } else {
        $("#password_error_message").hide();
    }

}

function check_retype_password() {

    var password = $("#form_password").val();
    var retype_password = $("#form_retype_password").val();
    
    if(password !=  retype_password) {
        $("#retype_password_error_message").html("Passwords don't match");
        $("#retype_password_error_message").show();
        error_retype_password = true;
    } else {
        $("#retype_password_error_message").hide();
    }

}

function check_email() {

    var pattern = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);

    if(pattern.test($("#form_email").val())) {
        $("#email_error_message").hide();
    } else {
        $("#email_error_message").html("Invalid email address");
        $("#email_error_message").show();
        error_email = true;
    }

}

$("#registration_form").submit(function() {
                                        
    error_username = false;
    error_password = false;
    error_retype_password = false;
    error_email = false;
                                        
    check_username();
    check_password();
    check_retype_password();
    check_email();
    
    if(error_username == false && error_password == false && error_retype_password == false && error_email == false) {
        return true;
    } else {
        return false;   
    }

});

});

How to implement a custom AlertDialog View

The android documents have been edited to correct the errors.

The view inside the AlertDialog is called android.R.id.custom

http://developer.android.com/reference/android/app/AlertDialog.html

Microsoft.ReportViewer.Common Version=12.0.0.0

Version 12 of the ReportViewer bits is referred to as Microsoft Report Viewer 2015 Runtime and can downloaded for installation from the following link:

https://www.microsoft.com/en-us/download/details.aspx?id=45496

UPDATE:

The ReportViewer bits are also available as a NUGET package: https://www.nuget.org/packages/Microsoft.ReportViewer.Runtime.Common/12.0.2402.15

Install-Package Microsoft.ReportViewer.Runtime.Common

Sorting by date & time in descending order?

This is one of the simplest ways to sort record by Date:

SELECT  `Article_Id` ,  `Title` ,  `Source_Link` ,  `Content` ,  `Source` , `Reg_Date`, UNIX_TIMESTAMP(  `Reg_Date` ) AS DATE
FROM article
ORDER BY DATE DESC 

How to deal with certificates using Selenium?

WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--ignore-certificate-errors");
driver = new ChromeDriver(options);

I have used it for Java with Chrome browser it is working nice

Getting View's coordinates relative to the root layout

This is one solution, though since APIs change over time and there may be other ways of doing it, make sure to check the other answers. One claims to be faster, and another claims to be easier.

private int getRelativeLeft(View myView) {
    if (myView.getParent() == myView.getRootView())
        return myView.getLeft();
    else
        return myView.getLeft() + getRelativeLeft((View) myView.getParent());
}

private int getRelativeTop(View myView) {
    if (myView.getParent() == myView.getRootView())
        return myView.getTop();
    else
        return myView.getTop() + getRelativeTop((View) myView.getParent());
}

Let me know if that works.

It should recursively just add the top and left positions from each parent container. You could also implement it with a Point if you wanted.

How to read the output from git diff?

@@ -1,2 +3,4 @@ part of the diff

This part took me a while to understand, so I've created a minimal example.

The format is basically the same the diff -u unified diff.

For instance:

diff -u <(seq 16) <(seq 16 | grep -Ev '^(2|3|14|15)$')

Here we removed lines 2, 3, 14 and 15. Output:

@@ -1,6 +1,4 @@
 1
-2
-3
 4
 5
 6
@@ -11,6 +9,4 @@
 11
 12
 13
-14
-15
 16

@@ -1,6 +1,4 @@ means:

  • -1,6 means that this piece of the first file starts at line 1 and shows a total of 6 lines. Therefore it shows lines 1 to 6.

    1
    2
    3
    4
    5
    6
    

    - means "old", as we usually invoke it as diff -u old new.

  • +1,4 means that this piece of the second file starts at line 1 and shows a total of 4 lines. Therefore it shows lines 1 to 4.

    + means "new".

    We only have 4 lines instead of 6 because 2 lines were removed! The new hunk is just:

    1
    4
    5
    6
    

@@ -11,6 +9,4 @@ for the second hunk is analogous:

  • on the old file, we have 6 lines, starting at line 11 of the old file:

    11
    12
    13
    14
    15
    16
    
  • on the new file, we have 4 lines, starting at line 9 of the new file:

    11
    12
    13
    16
    

    Note that line 11 is the 9th line of the new file because we have already removed 2 lines on the previous hunk: 2 and 3.

Hunk header

Depending on your git version and configuration, you can also get a code line next to the @@ line, e.g. the func1() { in:

@@ -4,7 +4,6 @@ func1() {

This can also be obtained with the -p flag of plain diff.

Example: old file:

func1() {
    1;
    2;
    3;
    4;
    5;
    6;
    7;
    8;
    9;
}

If we remove line 6, the diff shows:

@@ -4,7 +4,6 @@ func1() {
     3;
     4;
     5;
-    6;
     7;
     8;
     9;

Note that this is not the correct line for func1: it skipped lines 1 and 2.

This awesome feature often tells exactly to which function or class each hunk belongs, which is very useful to interpret the diff.

How the algorithm to choose the header works exactly is discussed at: Where does the excerpt in the git diff hunk header come from?

Automatically start forever (node) on system restart

An alternative crontab method inspired by this answer and this blog post.

1. Create a bash script file (change bob to desired user).

vi /home/bob/node_server_init.sh

2. Copy and paste this inside the file you've just created.

#!/bin/sh

export NODE_ENV=production
export PATH=/usr/local/bin:$PATH
forever start /node/server/path/server.js > /dev/null

Make sure to edit the paths above according to your config!

3. Make sure the bash script can be executed.

chmod 700 /home/bob/node_server_init.sh

4. Test the bash script.

sh /home/bob/node_server_init.sh

5. Replace "bob" with the runtime user for node.

crontab -u bob -e

6. Copy and paste (change bob to desired user).

@reboot /bin/sh /home/bob/node_server_init.sh

Save the crontab.

You've made it to the end, your prize is a reboot (to test) :)

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

You can force update your master branch as follows:

git checkout upstreambranch  
git branch master upstreambranch -f    
git checkout master  
git push origin master -f

For the ones who have problem to merge into main branch (Which is the new default one in Github) you can use the following:

git checkout master  
git branch main master -f    
git checkout main  
git push origin main -f

The following command will force both branches to have the same history:

git branch [Branch1] [Branch2] -f 

Can you remove elements from a std::list while iterating through it?

I think you have a bug there, I code this way:

for (std::list<CAudioChannel *>::iterator itAudioChannel = audioChannels.begin();
             itAudioChannel != audioChannels.end(); )
{
    CAudioChannel *audioChannel = *itAudioChannel;
    std::list<CAudioChannel *>::iterator itCurrentAudioChannel = itAudioChannel;
    itAudioChannel++;

    if (audioChannel->destroyMe)
    {
        audioChannels.erase(itCurrentAudioChannel);
        delete audioChannel;
        continue;
    }
    audioChannel->Mix(outBuffer, numSamples);
}

Apache won't follow symlinks (403 Forbidden)

Related to this question, I just figured out why my vhost was giving me that 403.

I had tested ALL possibilities on this question and others without luck. It almost drives me mad.

I am setting up a server with releases deployment similar to Capistrano way through symlinks and when I tried to access the DocRoot folder (which is now a symlink to current release folder) it gave me the 403.

My vhost is:

DocumentRoot /var/www/site.com/html
<Directory /var/www/site.com/html>
        AllowOverride All
        Options +FollowSymLinks
        Require all granted
</Directory>

and my main httpd.conf file was (default Apache 2.4 install):

DocumentRoot "/var/www"
<Directory "/var/www">
    Options -Indexes -FollowSymLinks -Includes
(...)

It turns out that the main Options definition was taking precedence over my vhosts fiel (for me that is counter intuitive). So I've changed it to:

DocumentRoot "/var/www"
<Directory "/var/www">
    Options -Indexes +FollowSymLinks -Includes
(...)

and Eureka! (note the plus sign before FollowSymLinks in MAIN httpd.conf file. Hope this help some other lost soul.

How do you specify a debugger program in Code::Blocks 12.11?

Download codeblocks-13.12mingw-setup.exe instead of codeblocks-13.12setup.exe from the official site. Here 13.12 is the latest version so far.