Programs & Examples On #Dup2

dup2() is a c system call that duplicates a file descriptor

How to duplicate sys.stdout to a log file?

another solution using logging module:

import logging
import sys

log = logging.getLogger('stdxxx')

class StreamLogger(object):

    def __init__(self, stream, prefix=''):
        self.stream = stream
        self.prefix = prefix
        self.data = ''

    def write(self, data):
        self.stream.write(data)
        self.stream.flush()

        self.data += data
        tmp = str(self.data)
        if '\x0a' in tmp or '\x0d' in tmp:
            tmp = tmp.rstrip('\x0a\x0d')
            log.info('%s%s' % (self.prefix, tmp))
            self.data = ''


logging.basicConfig(level=logging.INFO,
                    filename='text.log',
                    filemode='a')

sys.stdout = StreamLogger(sys.stdout, '[stdout] ')

print 'test for stdout'

Spring Boot and multiple external configuration files

I had the same problem. I wanted to have the ability to overwrite an internal configuration file at startup with an external file, similar to the Spring Boot application.properties detection. In my case it's a user.properties file where my applications users are stored.

My requirements:

Load the file from the following locations (in this order)

  1. The classpath
  2. A /config subdir of the current directory.
  3. The current directory
  4. From directory or a file location given by a command line parameter at startup

I came up with the following solution:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.util.Properties;

import static java.util.Arrays.stream;

@Configuration
public class PropertiesConfig {

    private static final Logger LOG = LoggerFactory.getLogger(PropertiesConfig.class);

    private final static String PROPERTIES_FILENAME = "user.properties";

    @Value("${properties.location:}")
    private String propertiesLocation;

    @Bean
    Properties userProperties() throws IOException {
        final Resource[] possiblePropertiesResources = {
                new ClassPathResource(PROPERTIES_FILENAME),
                new PathResource("config/" + PROPERTIES_FILENAME),
                new PathResource(PROPERTIES_FILENAME),
                new PathResource(getCustomPath())
        };
        // Find the last existing properties location to emulate spring boot application.properties discovery
        final Resource propertiesResource = stream(possiblePropertiesResources)
                .filter(Resource::exists)
                .reduce((previous, current) -> current)
                .get();
        final Properties userProperties = new Properties();

        userProperties.load(propertiesResource.getInputStream());

        LOG.info("Using {} as user resource", propertiesResource);

        return userProperties;
    }

    private String getCustomPath() {
        return propertiesLocation.endsWith(".properties") ? propertiesLocation : propertiesLocation + PROPERTIES_FILENAME;
    }

}

Now the application uses the classpath resource, but checks for a resource at the other given locations too. The last resource which exists will be picked and used. I'm able to start my app with java -jar myapp.jar --properties.location=/directory/myproperties.properties to use an properties location which floats my boat.

An important detail here: Use an empty String as default value for the properties.location in the @Value annotation to avoid errors when the property is not set.

The convention for a properties.location is: Use a directory or a path to a properties file as properties.location.

If you want to override only specific properties, a PropertiesFactoryBean with setIgnoreResourceNotFound(true) can be used with the resource array set as locations.

I'm sure that this solution can be extended to handle multiple files...

EDIT

Here my solution for multiple files :) Like before, this can be combined with a PropertiesFactoryBean.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;

import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toMap;

@Configuration
class PropertiesConfig {

    private final static Logger LOG = LoggerFactory.getLogger(PropertiesConfig.class);
    private final static String[] PROPERTIES_FILENAMES = {"job1.properties", "job2.properties", "job3.properties"};

    @Value("${properties.location:}")
    private String propertiesLocation;

    @Bean
    Map<String, Properties> myProperties() {
        return stream(PROPERTIES_FILENAMES)
                .collect(toMap(filename -> filename, this::loadProperties));
    }

    private Properties loadProperties(final String filename) {
        final Resource[] possiblePropertiesResources = {
                new ClassPathResource(filename),
                new PathResource("config/" + filename),
                new PathResource(filename),
                new PathResource(getCustomPath(filename))
        };
        final Resource resource = stream(possiblePropertiesResources)
                .filter(Resource::exists)
                .reduce((previous, current) -> current)
                .get();
        final Properties properties = new Properties();

        try {
            properties.load(resource.getInputStream());
        } catch(final IOException exception) {
            throw new RuntimeException(exception);
        }

        LOG.info("Using {} as user resource", resource);

        return properties;
    }

    private String getCustomPath(final String filename) {
        return propertiesLocation.endsWith(".properties") ? propertiesLocation : propertiesLocation + filename;
    }

}

Command to get latest Git commit hash from a branch

git log -n 1 [branch_name]

branch_name (may be remote or local branch) is optional. Without branch_name, it will show the latest commit on the current branch.

For example:

git log -n 1
git log -n 1 origin/master
git log -n 1 some_local_branch

git log -n 1 --pretty=format:"%H"  #To get only hash value of commit

How to set the title text color of UIButton?

Example in setting button title color

btnDone.setTitleColor(.black, for: .normal)

Use space as a delimiter with cut command

I just discovered that you can also use "-d ":

cut "-d "

Test

$ cat a
hello how are you
I am fine
$ cut "-d " -f2 a
how
am

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

I faced the same issue, It got fixed after keeping issuer subject value in the certificate as it is as subject of issuer certificate.

so please check "issuer subject value in the certificate(cert.pem) == subject of issuer (CA.pem)"

openssl verify -CAfile CA.pem cert.pem
cert.pem: OK

Conda command not found

For those experiencing issues after upgrading to MacOS Catalina.

Short version:

# 1a) Use tool: conda-prefix-replacement - 
# Restores: Desktop -> Relocated Items -> Security -> anaconda3
curl -L https://repo.anaconda.com/pkgs/misc/cpr-exec/cpr-0.1.1-osx-64.exe -o cpr && chmod +x cpr
./cpr rehome ~/anaconda3
# or if fails
#./cpr rehome ~/anaconda3 --old-prefix /Anaconda3
source ~/anaconda3/bin/activate

# 1b) Alternatively - reintall anaconda - 
# brew cask install anaconda

# 2) conda init
conda init zsh
# or
# conda init    

Further reading - Anaconda blog post and Github discussion.

What is the difference between dim and set in vba

Dim simply declares the value and the type.

Set assigns a value to the variable.

Easy way to export multiple data.frame to multiple Excel worksheets

There's a new library in town, from rOpenSci: writexl

Portable, light-weight data frame to xlsx exporter based on libxlsxwriter. No Java or Excel required

I found it better and faster than the above suggestions (working with the dev version):

library(writexl)
sheets <- list("sheet1Name" = sheet1, "sheet2Name" = sheet2) #assume sheet1 and sheet2 are data frames
write_xlsx(sheets, "path/to/location")

How to detect Adblock on my website?

Despite the age of this question, I recently found it very useful and therefore can only assume there are others still viewing it. After looking here and elsewhere I surmised that the main three client side checks for indirectly detecting an ad blocker were to check for blocked div/img, blocked iframes and blocked resources (javascript files).

Maybe it's over the top or paranoid but it covers for ad blocking systems that block only one or two out of the selection and therefore may not have been covered had you only done the one check.

On the page your are running the checks add: (I am using jQuery)

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="advertisement.js"></script>
<script type="text/javascript" src="abds.js"></script>

and add the following anywhere else on the page:

<div id="myTestAd"><img src="http://placehold.it/300x250/000000/ffffff.png&text=Advert" /></div>

I used a div with a bait name as well as an externally hosted image with the text "Advert" and in dimensions used by AdSense (thanks to placehold.it!).

In advertisement.js you should append something to the document which we can check for later. Although it seems like you're doing the same as before, you are actually checking for the file (advertisement.js) itself being loaded, not the output.

$(document).ready(
{

    $("body").append("<div id=\"myTestAd2\">check</div>");

});

And then the ad blocker detection script which combines everything

$(document).ready(function()
{
    var ifr = '<iframe id="adServer" src="http://ads.google.com/adserver/adlogger_tracker.php" width="300" height="300"></iframe>';
    $("body").append(ifr);
});

$(window).on("load",function()
{

    var atb = $("#myTestAd");
    var atb2= $("#myTestAd2");
    var ifr = $("#adServer");

    setTimeout(function()
    {

        if( (atb.height()==0) ||
            (atb.filter(":visible").length==0) ||
            (atb.filter(":hidden").length>0) ||
            (atb.is("hidden")) ||
            (atb.css("visibility")=="hidden") ||
            (atb.css("display")=="none") ||
            (atb2.html()!="check") ||
            (ifr.height()!=300) ||
            (ifr.width()!=300) )
        {
            alert("You're using ad blocker you normal person, you!");
        }

    },500);

});

When the document is ready, i.e. the markup is loaded, we add the iframe to the document also. Then, when the window is loaded, i.e. the content incl. images etc. is loaded, we check:

  • The dimensions and visibility of the first test div.
  • That the content of the second test div is "check", as it would have been if the advertimsent.js was not blocked.
  • The dimensions (and I guess visibility, as a hidden object has no height or width?) of the iframe

And the styles:

div#myTestAd, iframe#adServer
{
    display: block;
    position: absolute;
    left: -9999px;
    top: -9999px;
}

div#myTestAd2
{
    display: none;
}

Hope this helps

Difference between object and class in Scala

The formal difference -

  1. you can not provide constructor parameters for Objects
  2. Object is not a type - you may not create an instance with new operator. But it can have fields, methods, extend a superclass and mix in traits.

The difference in usage:

  • Scala doesn't have static methods or fields. Instead you should use object. You can use it with or without related class. In 1st case it's called a companion object. You have to:
    1. use the same name for both class and object
    2. put them in the same source file.
  • To create a program you should use main method in object, not in class.

    object Hello {
      def main(args: Array[String]) {
        println("Hello, World!")
      }
    }
    
  • You also may use it as you use singleton object in java.

      
        
      

"No backupset selected to be restored" SQL Server 2012

If you want to replace the existing database completely use the WITH REPLACE option:

RESTORE DATABASE <YourDatabase> 
FROM DISK='<the path to your backup file>\<YourDatabase>.bak'
WITH REPLACE

Trigger a button click with JavaScript on the Enter key in a text box

Figured this out:

<input type="text" id="txtSearch" onkeypress="return searchKeyPress(event);" />
<input type="button" id="btnSearch" Value="Search" onclick="doSomething();" />

<script>
function searchKeyPress(e)
{
    // look for window.event in case event isn't passed in
    e = e || window.event;
    if (e.keyCode == 13)
    {
        document.getElementById('btnSearch').click();
        return false;
    }
    return true;
}
</script>

git ignore exception

Git ignores folders if you write:

/js

but it can't add exceptions if you do: !/js/jquery or !/js/jquery/ or !/js/jquery/*

You must write:

/js/* 

and only then you can except subfolders like this

!/js/jquery

Insert into C# with SQLCommand

Use AddWithValue(), but be aware of the possibility of the wrong implicit type conversion.
like this:

cmd.Parameters.AddWithValue("@param1", klantId);
    cmd.Parameters.AddWithValue("@param2", klantNaam);
    cmd.Parameters.AddWithValue("@param3", klantVoornaam);

How can I list all cookies for the current page with Javascript?

var x = document.cookie; 
window.alert(x);

This displays every cookie the current site has access to. If you for example have created two cookies "username=Frankenstein" and "username=Dracula", these two lines of code will display "username=Frankenstein; username=Dracula". However, information such as expiry date will not be shown.

How can I wrap text in a label using WPF?

I used the following code.

    <Label>
        <Label.Content>
            <AccessText TextWrapping="Wrap" Text="xxxxx"/>
        </Label.Content>
    </Label>

When should I use Kruskal as opposed to Prim (and vice versa)?

Kruskal time complexity worst case is O(E log E),this because we need to sort the edges. Prim time complexity worst case is O(E log V) with priority queue or even better, O(E+V log V) with Fibonacci Heap. We should use Kruskal when the graph is sparse, i.e.small number of edges,like E=O(V),when the edges are already sorted or if we can sort them in linear time. We should use Prim when the graph is dense, i.e number of edges is high ,like E=O(V²).

Install Qt on Ubuntu

In Ubuntu 18.04 the QtCreator examples and API docs missing, This is my way to solve this problem, should apply to almost every Ubuntu release.

For QtCreator and Examples and API Docs:

sudo apt install `apt-cache search 5-examples | grep qt | grep example | awk '{print $1 }' | xargs `

sudo apt install `apt-cache search 5-doc | grep "Qt 5 " | awk '{print $1}' | xargs`

sudo apt-get install build-essential qtcreator qt5-default

If something is also missing, then:

sudo apt install `apt-cache search qt | grep 5- | grep ^qt | awk '{print $1}' | xargs `

Hope to be helpful.

Also posted in Ask Ubuntu: https://askubuntu.com/questions/450983/ubuntu-14-04-qtcreator-qt5-examples-missing

C++ Error 'nullptr was not declared in this scope' in Eclipse IDE

You are using g++ 4.6 version you must invoke the flag -std=c++0x to compile

g++ -std=c++0x *.cpp -o output

Cannot connect to SQL Server named instance from another SQL Server

Not sure if this is the answer you were looking for, but it worked for me. After spinning my wheels in Windows Firewall, I went back into SQL Server Configuration Manager, checked SQL Server Network Configuration, in the protocols for the instance I was working with look at TCP/IP. By default it seems mine was set to disabled, which allowed for instance connections on the local machine but not using SSMS on another machine. Enabling TCP/IP did the trick for me.

http://technet.microsoft.com/en-us/library/hh231672.aspx

What is a MIME type?

A MIME type is a label used to identify a type of data. It is used so software can know how to handle the data. It serves the same purpose on the Internet that file extensions do on Microsoft Windows.

So if a server says "This is text/html" the client can go "Ah, this is an HTML document, I can render that internally", while if the server says "This is application/pdf" the client can go "Ah, I need to launch the FoxIt PDF Reader plugin that the user has installed and that has registered itself as the application/pdf handler."

You'll most commonly find them in the headers of HTTP messages (to describe the content that an HTTP server is responding with or the formatting of the data that is being POSTed in a request) and in email headers (to describe the message format and attachments).

How to detect pressing Enter on keyboard using jQuery?

There's a keypress() event method. The Enter key's ascii number is 13 and is not dependent on which browser is being used.

Difference between Static and final?

Easy Difference,

Final : means that the Value of the variable is Final and it will not change anywhere. If you say that final x = 5 it means x can not be changed its value is final for everyone.

Static : means that it has only one object. lets suppose you have x = 5, in memory there is x = 5 and its present inside a class. if you create an object or instance of the class which means there a specific box that represents that class and its variables and methods. and if you create an other object or instance of that class it means there are two boxes of that same class which has different x inside them in the memory. and if you call both x in different positions and change their value then their value will be different. box 1 has x which has x =5 and box 2 has x = 6. but if you make the x static it means it can not be created again. you can create object of class but that object will not have different x in them. if x is static then box 1 and box 2 both will have the same x which has the value of 5. Yes i can change the value of static any where as its not final. so if i say box 1 has x and i change its value to x =5 and after that i make another box which is box2 and i change the value of box2 x to x=6. then as X is static both boxes has the same x. and both boxes will give the value of box as 6 because box2 overwrites the value of 5 to 6.

Both final and static are totally different. Final which is final can not be changed. static which will remain as one but can be changed.

"This is an example. remember static variable are always called by their class name. because they are only one for all of the objects of that class. so Class A has x =5, i can call and change it by A.x=6; "

PopupWindow $BadTokenException: Unable to add window -- token null is not valid

Following many hours of search and testing i found following solution(by implementing different SO solutions) here it what didn't failed in any case i was getting crash.

     Runnable runnable = new Runnable() {
            @Override
            public void run() {

          //displayPopup,progress dialog or what ever action. example

                ProgressDialogBox.setProgressBar(Constants.LOADING,youractivityName.this);
            }};

Where logcat is indicating the crash is happening.. start a runnable .in my case at receiving broadcast.

runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(!isFinishing()) {
                    new Handler().postAtTime(runnable,2000);
                }
            }
        });

How to check if a windows form is already open, and close it if it is?

This worked form me:

public void DetectOpenedForm()
{
    FormCollection AllForms = Application.OpenForms;
    Boolean FormOpen = false;
    Form OpenedForm = new Form();
    foreach (Form form in AllForms)
    {
        if (form.Name == "YourFormName")
        {
            OpenedForm = form;
            FormOpen = true;
        }
    }
    if (FormOpen == true)
    {
        OpenedForm.Close();
    }
}

What is the meaning of Bus: error 10 in C

Your code attempts to overwrite a string literal. This is undefined behaviour.

There are several ways to fix this:

  1. use malloc() then strcpy() then free();
  2. turn str into an array and use strcpy();
  3. use strdup().

How to change bower's default components folder?

Something worth mentioning...

As noted above by other contributors, using a .bowerrc file with the JSON

{ "directory": "some/path" }

is necessary -- HOWEVER, you may run into an issue on Windows while creating that file. If Windows gives you a message imploring you to add a "file name", simply use a text editor / IDE such as Notepad++.

Add the JSON to an unnamed file, save it as .bowerrc -- you're good to go!

Probably an easy assumption, but I hope this save others the unnecessary headache :)

how can get index & count in vuejs

In case, your data is in the following structure, you get string as an index

items = {
   am:"Amharic",
   ar:"Arabic",
   az:"Azerbaijani",
   ba:"Bashkir",
   be:"Belarusian"
}

In this case, you can use extra variable to get the index in number:

<ul>
  <li v-for="(item, key, index) in items">
    {{ item }} - {{ key }} - {{ index }}
  </li>
</ul>

Source: https://alligator.io/vuejs/iterating-v-for/

React "after render" code?

In my experience window.requestAnimationFrame wasn't enough to ensure that the DOM had been fully rendered / reflow-complete from componentDidMount. I have code running that accesses the DOM immediately after a componentDidMount call and using solely window.requestAnimationFrame would result in the element being present in the DOM; however, updates to the element's dimensions aren't reflected yet since a reflow hasn't yet occurred.

The only truly reliable way for this to work was to wrap my method in a setTimeout and a window.requestAnimationFrame to ensure React's current call stack gets cleared before registering for the next frame's render.

function onNextFrame(callback) {
    setTimeout(function () {
        requestAnimationFrame(callback)
    })
}

If I had to speculate on why this is occurring / necessary I could see React batching DOM updates and not actually applying the changes to the DOM until after the current stack is complete.

Ultimately, if you're using DOM measurements in the code you're firing after the React callbacks you'll probably want to use this method.

Count rows with not empty value

As far as I can see, most of the solutions here count the number of non empty cells, and not the number of rows with non empty cell inside.

One possible solution for the range B3:E29 is for example

=SUM(ArrayFormula(IF(B3:B29&C3:C29&D3:D29&E3:E29="";0;1)))

Here ArrayFormula(IF(B3:B29&C3:C29&D3:D29&E3:E29="";0;1)) returns a column of 0 (if the row is empty) and 1 (else).

Another one is given in consideRatio's answer.

Java: How can I compile an entire directory structure of code ?

Windows solution: Assuming all files contained in sub-directory 'src', and you want to compile them to 'bin'.

for /r src %i in (*.java) do javac %i -sourcepath src -d bin

If src contains a .java file immediately below it then this is faster

javac src\\*.java -d bin

Java naming convention for static final variables

These variables are constants, i.e. private static final whether they're named in all caps or not. The all-caps convention simply makes it more obvious that these variables are meant to be constants, but it isn't required. I've seen

private static final Logger log = Logger.getLogger(MyClass.class);

in lowercase before, and I'm fine with it because I know to only use the logger to log messages, but it does violate the convention. You could argue that naming it log is a sub-convention, I suppose. But in general, naming constants in uppercase isn't the One Right Way, but it is The Best Way.

Using two values for one switch case statement

The brackets are unnecessary. Just do

case text1:
case text4:
  doSomethingHere();
  break;
case text2:
  doSomethingElse()
  break;

If anyone is curious, this is called a case fallthrough. The ability to do this is the reason why break; is necessary to end case statements. For more information, see the wikipedia article http://en.wikipedia.org/wiki/Switch_statement.

Mysql - How to quit/exit from stored procedure

MainLabel:BEGIN

IF (<condition>) IS NOT NULL THEN
    LEAVE MainLabel;
END IF; 

....code

i.e.
IF (@skipMe) IS NOT NULL THEN /* @skipMe returns Null if never set or set to NULL */
     LEAVE MainLabel;
END IF;

Method Call Chaining; returning a pointer vs a reference?

It's canonical to use references for this; precedence: ostream::operator<<. Pointers and references here are, for all ordinary purposes, the same speed/size/safety.

Android Text over image

You want to use a FrameLayout or a Merge layout to achieve this. Android dev guide has a great example of this here: Android Layout Tricks #3: Optimize by merging.

Drawing an SVG file on a HTML5 canvas

You can easily draw simple svgs onto a canvas by:

  1. Assigning the source of the svg to an image in base64 format
  2. Drawing the image onto a canvas

Note: The only drawback of the method is that it cannot draw images embedded in the svg. (see demo)

Demonstration:

(Note that the embedded image is only visible in the svg)

_x000D_
_x000D_
var svg = document.querySelector('svg');_x000D_
var img = document.querySelector('img');_x000D_
var canvas = document.querySelector('canvas');_x000D_
_x000D_
// get svg data_x000D_
var xml = new XMLSerializer().serializeToString(svg);_x000D_
_x000D_
// make it base64_x000D_
var svg64 = btoa(xml);_x000D_
var b64Start = 'data:image/svg+xml;base64,';_x000D_
_x000D_
// prepend a "header"_x000D_
var image64 = b64Start + svg64;_x000D_
_x000D_
// set it as the source of the img element_x000D_
img.src = image64;_x000D_
_x000D_
// draw the image onto the canvas_x000D_
canvas.getContext('2d').drawImage(img, 0, 0);
_x000D_
svg, img, canvas {_x000D_
  display: block;_x000D_
}
_x000D_
SVG_x000D_
_x000D_
<svg height="40">_x000D_
  <rect width="40" height="40" style="fill:rgb(255,0,255);" />_x000D_
  <image xlink:href="https://en.gravatar.com/userimage/16084558/1a38852cf33713b48da096c8dc72c338.png?size=20" height="20px" width="20px" x="10" y="10"></image>_x000D_
</svg>_x000D_
<hr/><br/>_x000D_
_x000D_
IMAGE_x000D_
<img/>_x000D_
<hr/><br/>_x000D_
   _x000D_
CANVAS_x000D_
<canvas></canvas>_x000D_
<hr/><br/>
_x000D_
_x000D_
_x000D_

How to get bean using application context in spring boot

You can use ServiceLocatorFactoryBean. First you need to create an interface for your class

public interface YourClassFactory {
    YourClass getClassByName(String name);
}

Then you have to create a config file for ServiceLocatorBean

@Configuration
@Component
public class ServiceLocatorFactoryBeanConfig {

    @Bean
    public ServiceLocatorFactoryBean serviceLocatorBean(){
        ServiceLocatorFactoryBean bean = new ServiceLocatorFactoryBean();
        bean.setServiceLocatorInterface(YourClassFactory.class);
        return bean;
    }
}

Now you can find your class by name like that

@Autowired
private YourClassfactory factory;

YourClass getYourClass(String name){
    return factory.getClassByName(name);
}

In bash, how to store a return value in a variable?

Something like this could be used, and still maintaining meanings of return (to return control signals) and echo (to return information) and logging statements (to print debug/info messages).

v_verbose=1
v_verbose_f=""         # verbose file name
FLAG_BGPID=""

e_verbose() {
        if [[ $v_verbose -ge 0 ]]; then
                v_verbose_f=$(tempfile)
                tail -f $v_verbose_f &
                FLAG_BGPID="$!"
        fi
}

d_verbose() {
        if [[ x"$FLAG_BGPID" != "x" ]]; then
                kill $FLAG_BGPID > /dev/null
                FLAG_BGPID=""
                rm -f $v_verbose_f > /dev/null
        fi
}

init() {
        e_verbose

        trap cleanup SIGINT SIGQUIT SIGKILL SIGSTOP SIGTERM SIGHUP SIGTSTP
}

cleanup() {
        d_verbose
}

init

fun1() {
    echo "got $1" >> $v_verbose_f
    echo "got $2" >> $v_verbose_f
    echo "$(( $1 + $2 ))"
    return 0
}

a=$(fun1 10 20)
if [[ $? -eq 0 ]]; then
    echo ">>sum: $a"
else
    echo "error: $?"
fi
cleanup

In here, I'm redirecting debug messages to separate file, that is watched by tail, and if there is any changes then printing the change, trap is used to make sure that background process always ends.

This behavior can also be achieved using redirection to /dev/stderr, But difference can be seen at the time of piping output of one command to input of other command.

How do you generate dynamic (parameterized) unit tests in Python?

I came across ParamUnittest the other day when looking at the source code for radon (example usage on the GitHub repository). It should work with other frameworks that extend TestCase (like Nose).

Here is an example:

import unittest
import paramunittest


@paramunittest.parametrized(
    ('1', '2'),
    #(4, 3),    <---- Uncomment to have a failing test
    ('2', '3'),
    (('4', ), {'b': '5'}),
    ((), {'a': 5, 'b': 6}),
    {'a': 5, 'b': 6},
)
class TestBar(TestCase):
    def setParameters(self, a, b):
        self.a = a
        self.b = b

    def testLess(self):
        self.assertLess(self.a, self.b)

Delete an element in a JSON object

Let's assume you want to overwrite the same file:

import json

with open('data.json', 'r') as data_file:
    data = json.load(data_file)

for element in data:
    element.pop('hours', None)

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

dict.pop(<key>, not_found=None) is probably what you where looking for, if I understood your requirements. Because it will remove the hours key if present and will not fail if not present.

However I am not sure I understand why it makes a difference to you whether the hours key contains some days or not, because you just want to get rid of the whole key / value pair, right?

Now, if you really want to use del instead of pop, here is how you could make your code work:

import json

with open('data.json') as data_file:
    data = json.load(data_file)

for element in data:
    if 'hours' in element:
        del element['hours']

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

EDIT So, as you can see, I added the code to write the data back to the file. If you want to write it to another file, just change the filename in the second open statement.

I had to change the indentation, as you might have noticed, so that the file has been closed during the data cleanup phase and can be overwritten at the end.

with is what is called a context manager, whatever it provides (here the data_file file descriptor) is available ONLY within that context. It means that as soon as the indentation of the with block ends, the file gets closed and the context ends, along with the file descriptor which becomes invalid / obsolete.

Without doing this, you wouldn't be able to open the file in write mode and get a new file descriptor to write into.

I hope it's clear enough...

SECOND EDIT

This time, it seems clear that you need to do this:

with open('dest_file.json', 'w') as dest_file:
    with open('source_file.json', 'r') as source_file:
        for line in source_file:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            dest_file.write(json.dumps(element))

Modifying a subset of rows in a pandas dataframe

To replace multiples columns convert to numpy array using .values:

df.loc[df.A==0, ['B', 'C']] = df.loc[df.A==0, ['B', 'C']].values / 2

Fastest way to check if a string matches a regexp in ruby?

To complete Wiktor Stribizew and Dougui answers I would say that /regex/.match?("string") about as fast as "string".match?(/regex/).

Ruby 2.4.0 (10 000 000 ~2 sec)

2.4.0 > require 'benchmark'
 => true 
2.4.0 > Benchmark.measure{ 10000000.times { /^CVE-[0-9]{4}-[0-9]{4,}$/.match?("CVE-2018-1589") } }
 => #<Benchmark::Tms:0x005563da1b1c80 @label="", @real=2.2060338060000504, @cstime=0.0, @cutime=0.0, @stime=0.04000000000000001, @utime=2.17, @total=2.21> 
2.4.0 > Benchmark.measure{ 10000000.times { "CVE-2018-1589".match?(/^CVE-[0-9]{4}-[0-9]{4,}$/) } }
 => #<Benchmark::Tms:0x005563da139eb0 @label="", @real=2.260814556000696, @cstime=0.0, @cutime=0.0, @stime=0.010000000000000009, @utime=2.2500000000000004, @total=2.2600000000000007> 

Ruby 2.6.2 (100 000 000 ~20 sec)

irb(main):001:0> require 'benchmark'
=> true
irb(main):005:0> Benchmark.measure{ 100000000.times { /^CVE-[0-9]{4}-[0-9]{4,}$/.match?("CVE-2018-1589") } }
=> #<Benchmark::Tms:0x0000562bc83e3768 @label="", @real=24.60139879199778, @cstime=0.0, @cutime=0.0, @stime=0.010000999999999996, @utime=24.565644999999996, @total=24.575645999999995>
irb(main):004:0> Benchmark.measure{ 100000000.times { "CVE-2018-1589".match?(/^CVE-[0-9]{4}-[0-9]{4,}$/) } }
=> #<Benchmark::Tms:0x0000562bc846aee8 @label="", @real=24.634255946999474, @cstime=0.0, @cutime=0.0, @stime=0.010046, @utime=24.598276, @total=24.608321999999998>

Note: times varies, sometimes /regex/.match?("string") is faster and sometimes "string".match?(/regex/), the differences maybe only due to the machine activity.

How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

You can specify JsonSerializerSettings for each JsonConvert, and you can set a global default.

Single JsonConvert with an overload:

// Option #1.
JsonSerializerSettings config = new JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore };
this.json = JsonConvert.SerializeObject(YourObject, Formatting.Indented, config);

// Option #2 (inline).
JsonConvert.SerializeObject(YourObject, Formatting.Indented,
    new JsonSerializerSettings() {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    }
);

Global Setting with code in Application_Start() in Global.asax.cs:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
     Formatting = Newtonsoft.Json.Formatting.Indented,
     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};

Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78

Copying formula to the next row when inserting a new row

You need to insert the new row and then copy from the source row to the newly inserted row. Excel allows you to paste special just formulas. So in Excel:

  • Insert the new row
  • Copy the source row
  • Select the newly created target row, right click and paste special
  • Paste as formulas

VBA if required with Rows("1:1") being source and Rows("2:2") being target:

Rows("2:2").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("2:2").Clear

Rows("1:1").Copy
Rows("2:2").PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone

Groovy write to file (newline)

Might be cleaner to use PrintWriter and its method println.
Just make sure you close the writer when you're done

How to set a value of a variable inside a template code?

Use the with statement.

{% with total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}

I can't imply the code in first paragraph in this answer. Maybe the template language had deprecated the old format.

Get selected text from a drop-down list (select box) using jQuery

the following worked for me:

$.trim($('#dropdownId option:selected').html())

Do subclasses inherit private fields?

No. They don't inherit it.

The fact some other class may use it indirectly says nothing about inheritance, but about encapsulation.

For instance:

class Some { 
   private int count; 
   public void increment() { 
      count++;
   }
   public String toString() { 
       return Integer.toString( count );
   }
}

class UseIt { 
    void useIt() { 
        Some s = new Some();
        s.increment();
        s.increment();
        s.increment();
        int v = Integer.parseInt( s.toString() );
        // hey, can you say you inherit it?
     }
}

You can also get the value of count inside UseIt via reflection. It doesn't means, you inherit it.

UPDATE

Even though the value is there, it is not inherited by the subclass.

For instance a subclass defined as:

class SomeOther extends Some { 
    private int count = 1000;
    @Override
    public void increment() { 
        super.increment();
        count *= 10000;
    }
}

class UseIt { 
    public static void main( String ... args ) { 
        s = new SomeOther();
        s.increment();
        s.increment();
        s.increment();
        v = Integer.parseInt( s.toString() );
        // what is the value of v?           
     }
}

This is exactly the same situation as the first example. The attribute count is hidden and not inherited by the subclass at all. Still, as DigitalRoss points out, the value is there, but not by means on inheritance.

Put it this way. If your father is wealthy and gives you a credit card, you can still buy thing with his money, but doesn't mean you have inherited all that money, does it?

Other update

It is very interesting though, to know why the attribute is there.

I frankly don't have the exact term to describe it, but it's the JVM and the way it works that loads also the "not inherited" parent definition.

We could actually change the parent and the subclass will still work.

For instance:

//A.java
class A {
   private int i;
   public String toString() { return ""+ i; }
}
// B.java
class B extends A {}
// Main.java
class Main {
   public static void main( String [] args ) {
      System.out.println( new B().toString() );
    }
}
// Compile all the files
javac A.java B.java Main.java
// Run Main
java Main
// Outout is 0 as expected as B is using the A 'toString' definition
0

// Change A.java
class A {
   public String toString() {
      return "Nothing here";
   }
}
// Recompile ONLY A.java
javac A.java
java Main
// B wasn't modified and yet it shows a different behaviour, this is not due to 
// inheritance but the way Java loads the class
Output: Nothing here

I guess the exact term could be found here: The JavaTM Virtual Machine Specification

wildcard * in CSS for classes

Yes you can do this.

*[id^='term-']{
    [css here]
}

This will select all ids that start with 'term-'.

As for the reason for not doing this, I see where it would be preferable to select this way; as for style, I wouldn't do it myself, but it's possible.

How do I extract value from Json

    //import java.util.ArrayList;
    //import org.bson.Document;

    Document root = Document.parse("{\n"
            + "  \"name\": \"Json\",\n"
            + "  \"detail\": {\n"
            + "    \"first_name\": \"Json\",\n"
            + "    \"last_name\": \"Scott\",\n"
            + "    \"age\": \"23\"\n"
            + "  },\n"
            + "  \"status\": \"success\"\n"
            + "}");

    System.out.println(((String) root.get("name")));
    System.out.println(((String) ((Document) root.get("detail")).get("first_name")));
    System.out.println(((String) ((Document) root.get("detail")).get("last_name")));
    System.out.println(((String) ((Document) root.get("detail")).get("age")));
    System.out.println(((String) root.get("status")));

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

It says already we are running the services with port no 4200 please use another port instead of 4200. Below command is to solve the problem

ng serve --port 4300

Should I use <i> tag for icons instead of <span>?

Why are they using <i> tag to display icons ?

Because it is:

  • Short
  • i stands for icon (although not in HTML)

Is it not a bad practice ?

Awful practice. It is a triumph of performance over semantics.

What are the differences between LDAP and Active Directory?

Active directory is a directory service provider, where you can add new user to a directory, remove or modify, specify privilages, assign policy etc. Its just like a phone directory where every person have a unique contact number. Every thing in AD(Active Directory) are considered as Objects and every object is given a Unique ID.(similar to a unique contact number in a phone directory.

Ldap is a protocol specially designed for directory service providers. Windows server OS uses AD as a directory server, AIX which is a UNIX version by IBM uses Tivoli directory server. Both of them uses LDAP protocol for interacting with directory.

Apart from protocol there are LDAP servers, LDAP browsers too.

ASP.NET MVC Return Json Result?

It should be :

public async Task<ActionResult> GetSomeJsonData()
{
    var model = // ... get data or build model etc.

    return Json(new { Data = model }, JsonRequestBehavior.AllowGet); 
}

or more simply:

return Json(model, JsonRequestBehavior.AllowGet); 

I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...

read file from assets

public String ReadFromfile(String fileName, Context context) {
    StringBuilder returnString = new StringBuilder();
    InputStream fIn = null;
    InputStreamReader isr = null;
    BufferedReader input = null;
    try {
        fIn = context.getResources().getAssets()
                .open(fileName, Context.MODE_WORLD_READABLE);
        isr = new InputStreamReader(fIn);
        input = new BufferedReader(isr);
        String line = "";
        while ((line = input.readLine()) != null) {
            returnString.append(line);
        }
    } catch (Exception e) {
        e.getMessage();
    } finally {
        try {
            if (isr != null)
                isr.close();
            if (fIn != null)
                fIn.close();
            if (input != null)
                input.close();
        } catch (Exception e2) {
            e2.getMessage();
        }
    }
    return returnString.toString();
}

Copy data from another Workbook through VBA

There's very little reason not to open multiple workbooks in Excel. Key lines of code are:

Application.EnableEvents = False
Application.ScreenUpdating = False

...then you won't see anything whilst the code runs, and no code will run that is associated with the opening of the second workbook. Then there are...

Application.DisplayAlerts = False
Application.Calculation = xlManual

...so as to stop you getting pop-up messages associated with the content of the second file, and to avoid any slow re-calculations. Ensure you set back to True/xlAutomatic at end of your programming

If opening the second workbook is not going to cause performance issues, you may as well do it. In fact, having the second workbook open will make it very beneficial when attempting to debug your code if some of the secondary files do not conform to the expected format

Here is some expert guidance on using multiple Excel files that gives an overview of the different methods available for referencing data

An extension question would be how to cycle through multiple files contained in the same folder. You can use the Windows folder picker using:

With Application.FileDialog(msoFileDialogFolderPicker)
.Show
     If .Selected.Items.Count = 1 the InputFolder = .SelectedItems(1)
End With

FName = VBA.Dir(InputFolder)

Do While FName <> ""
'''Do function here
FName = VBA.Dir()
Loop

Hopefully some of the above will be of use

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

I had this problem and its because I wasnt using the latest version of C# (C# 7.3 as of writing this) and I had to change the below internal access modifier to public.

internal class Program
 {
    public static void Main(string[] args)
    {
        //My Code
    }
  }

or ammend the .csproj to use the latest version of C# (this way meant I could still keep the above class as internal):

<PropertyGroup>
    <LangVersion>latest</LangVersion>
    <NoWin32Manifest>true</NoWin32Manifest>
</PropertyGroup>

Git workflow and rebase vs merge questions

I only use rebase workflow, because it is visually clearer(not only in GitKraken, but also in Intellij and in gitk, but I recommend the first one most): you have a branch, it originates from the master, and it goes back to master. When the diagram is clean and beautiful, you will know that nothing goes to hell, ever.

enter image description here

My workflow is almost the same from yours, but with only one small difference: I squash commits into one in my local branch before rebase my branch onto the latest changes on master, because:

rebase works on basis of each commit

which means, if you have 15 commits changing the same line as master does, you have to check 15 times if you don't squash, but what matters is the final result, right?

So, the whole workflow is:

  1. Checkout to master and pull to ensure that you have the latest version

  2. From there, create a new branch

  3. Do your work there, you can freely commit several times, and push to remote, no worries, because it is your branch.

  4. If someone tells you, "hey, my PR/MR is approved, now it is merged to master", you can fetch them/pull them. You can do it anytime, or in step 6.

  5. After doing all your work, commit them, and if you have several commits, squash them(they are all your work, and how many times you change a line of code does not matter; the only important thing is the final version). Push it or not, it doesn't matter.

  6. Checkout to master, pull again to ensure you have the latest master in local. Your diagram should be similar to this:

enter image description here

As you can see, you are on your local branch, which originates from an outdated status on master, while master(both local and remote) has moved forward with changes of your colleague.

  1. Checkout back to your branch, and rebase to master. You will now have one commit only, so you solve the conflicts only once.(And in GitKraken, you only have to drag your branch on to master and choose "Rebase"; another reason why I like it.) After that, you will be like:

enter image description here

  1. So now, you have all the changes on the latest master, combined with changes on your branch. You can now push to your remote, and, if you have pushed before, you will have to force push; Git will tell you that you cannot simply fast forward. That's normal, because of the rebase, you have changed the start point of your branch. But you should not fear: wisely use the force, but without fear. In the end, the remote is also your branch so you do not affect master even if you do something wrong.

  2. Create PR/MR and wait until it is approved, so master will have your contribution. Congrats! So you can now checkout to master, pull your changes, and delete your local branch in order to clean up the diagram. The remote branch should be deleted too, if this is not done when you merge it into master.

The final diagram is clean and clear again:

enter image description here

Benefits of using the conditional ?: (ternary) operator

With C# 7, you can use the new ref locals feature to simplify the conditional assignment of ref-compatible variables. So now, not only can you do:

int i = 0;

T b = default(T), c = default(T);

// initialization of C#7 'ref-local' variable using a conditional r-value?¹?

ref T a = ref (i == 0 ? ref b : ref c);

...but also the extremely wonderful:

// assignment of l-value?²? conditioned by C#7 'ref-locals'

(i == 0 ? ref b : ref c) = a;

That line of code assigns the value of a to either b or c, depending on the value of i.



Notes
1. r-value is the right-hand side of an assignment, the value that gets assigned.
2. l-value is the left-hand side of an assignment, the variable that receives the assigned value.

Is there a Google Voice API?

I looked for a C/C++ API for Google Voice for quite a while and never found anything close (the closest was a C# API). Since I really needed it, I decided to just write one myself:

http://github.com/mastermind202/GoogleVoice

I hope others find it useful. Feedback and suggestions welcome.

Remove values from select list based on condition

if(frm.product.value=="F"){
    var select = document.getElementsByName('val')[0];
    select.remove(0);
    select.remove(1);
}

R data formats: RData, Rda, Rds etc

Rda is just a short name for RData. You can just save(), load(), attach(), etc. just like you do with RData.

Rds stores a single R object. Yet, beyond that simple explanation, there are several differences from a "standard" storage. Probably this R-manual Link to readRDS() function clarifies such distinctions sufficiently.

So, answering your questions:

  • The difference is not about the compression, but serialization (See this page)
  • Like shown in the manual page, you may wanna use it to restore a certain object with a different name, for instance.
  • You may readRDS() and save(), or load() and saveRDS() selectively.

Gradients on UIView and UILabels On iPhone

I realize this is an older thread, but for future reference:

As of iPhone SDK 3.0, custom gradients can be implemented very easily, without subclassing or images, by using the new CAGradientLayer:

 UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)] autorelease];
 CAGradientLayer *gradient = [CAGradientLayer layer];
 gradient.frame = view.bounds;
 gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
 [view.layer insertSublayer:gradient atIndex:0];

Take a look at the CAGradientLayer docs. You can optionally specify start and end points (in case you don't want a linear gradient that goes straight from the top to the bottom), or even specific locations that map to each of the colors.

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

I would store the timespan.TotalSeconds in a float and then retrieve it using Timespan.FromSeconds(totalSeconds).

Depending on the resolution you need you could use TotalMilliseconds, TotalMinutes, TotalDays.

You could also adjust the precision of your float in the database.

It's not an exact value... but the nice thing about this is that it's easy to read and calculate in simple queries.

Is there any JSON Web Token (JWT) example in C#?

After all these months have passed after the original question, it's now worth pointing out that Microsoft has devised a solution of their own. See http://blogs.msdn.com/b/vbertocci/archive/2012/11/20/introducing-the-developer-preview-of-the-json-web-token-handler-for-the-microsoft-net-framework-4-5.aspx for details.

Make hibernate ignore class variables that are not mapped

Placing @Transient on getter with private field worked for me.

private String name;

    @Transient
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

Laravel 5.2 not reading env file

Same thing happens when :port is in your local .env

again the double quotes does the trick

APP_URL="http://localhost:8000"

and then

php artisan config:clear

How can I run an EXE program from a Windows Service using C#?

System.Diagnostics.Process.Start("Exe Name");

How to printf long long

    // acos(0.0) will return value of pi/2, inverse of cos(0) is pi/2 
    double pi = 2 * acos(0.0);
    int n; // upto 6 digit
    scanf("%d",&n); //precision with which you want the value of pi
    printf("%.*lf\n",n,pi); // * will get replaced by n which is the required precision

How do I analyze a program's core dump file with GDB when it has command-line parameters?

You can analyze the core dump file using the "gdb" command.

 gdb - The GNU Debugger

 syntax:

 # gdb executable-file core-file

 example: # gdb out.txt core.xxx 

use a javascript array to fill up a drop down select box

This is a part from a REST-Service I´ve written recently.

var select = $("#productSelect")
for (var prop in data) {
    var option = document.createElement('option');
    option.innerHTML = data[prop].ProduktName
    option.value = data[prop].ProduktName;
    select.append(option)
}

The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.

HTTP Headers for File Downloads

Acoording to RFC 2046 (Multipurpose Internet Mail Extensions):

The recommended action for an implementation that receives an
"application/octet-stream" entity is to simply offer to put the data in a file

So I'd go for that one.

C compile : collect2: error: ld returned 1 exit status

  1. Go to Advanced System Settings in the computer properties
  2. Click on Advanced
  3. Click for the environment variable
  4. Choose the path option
  5. Change the path option to bin folder of dev c
  6. Apply and save it
  7. Now resave the code in the bin folder in developer c

How do I get the day month and year from a Windows cmd.exe script?

A variant of script that works locale-independently. Put it in a text file with .cmd extension and run.

::: Begin set date

for /f "tokens=1-4 delims=/-. " %%i in ('date /t') do (call :set_date %%i %%j %%k %%l)
goto :end_set_date

:set_date
if "%1:~0,1%" gtr "9" shift
for /f "skip=1 tokens=2-4 delims=(-)" %%m in ('echo,^|date') do (set %%m=%1&set %%n=%2&set %%o=%3)
goto :eof

:end_set_date
::: End set date

echo day in 'DD' format is %dd%; month in 'MM' format is %mm%; year in 'YYYY' format is %yy%

The variables %dd%, %mm% and %yy% will keep the day('DD' format), the month('MM' format) and the year('YYYY' format) respectively.

What is the height of iPhone's onscreen keyboard?

I created this table which contains both the heights of iPhone and iPad keyboards, both for landscape and portrait mode, both with the toolbar on and off.

I even explained how you can use these dimensions in your code here.

Note that you should only use these dimensions if you need to know the keyboard's dimension before you layout the view. Otherwise the solutions from the other answers work better.

enter image description here

How to set time delay in javascript

Here is what I am doing to solve this issue. I agree this is because of the timing issue and needed a pause to execute the code.

var delayInMilliseconds = 1000; 
setTimeout(function() {
 //add your code here to execute
 }, delayInMilliseconds);

This new code will pause it for 1 second and meanwhile run your code.

Pretty printing XML with javascript

here is another function to format xml

function formatXml(xml){
    var out = "";
    var tab = "    ";
    var indent = 0;
    var inClosingTag=false;
    var dent=function(no){
        out += "\n";
        for(var i=0; i < no; i++)
            out+=tab;
    }


    for (var i=0; i < xml.length; i++) {
        var c = xml.charAt(i);
        if(c=='<'){
            // handle </
            if(xml.charAt(i+1) == '/'){
                inClosingTag = true;
                dent(--indent);
            }
            out+=c;
        }else if(c=='>'){
            out+=c;
            // handle />
            if(xml.charAt(i-1) == '/'){
                out+="\n";
                //dent(--indent)
            }else{
              if(!inClosingTag)
                dent(++indent);
              else{
                out+="\n";
                inClosingTag=false;
              }
            }
        }else{
          out+=c;
        }
    }
    return out;
}

How to list all functions in a Python module?

Use vars(module) then filter out anything that isn't a function using inspect.isfunction:

import inspect
import my_module

my_module_functions = [f for _, f in vars(my_module).values() if inspect.isfunction(f)]

The advantage of vars over dir or inspect.getmembers is that it returns the functions in the order they were defined instead of sorted alphabetically.

Also, this will include functions that are imported by my_module, if you want to filter those out to get only functions that are defined in my_module, see my question Get all defined functions in Python module.

How do I reference a local image in React?

the best way for import image is...

import React, { Component } from 'react';

// image import
import CartIcon from '../images/CartIcon.png';

 class App extends Component {
  render() {
    return (
     <div>
         //Call image in source like this
          <img src={CartIcon}/>
     </div>
    );
  }
}

How do change the color of the text of an <option> within a <select>?

You just need to add disabled as option attribute

<option disabled>select one option</option>

Including JavaScript class definition from another file in Node.js

Instead of myFile.js write your files like myFile.mjs. This extension comes with all the goodies of es6, but I mean I recommend you to you webpack and Babel

Python Requests - No connection adapters

One more reason, maybe your url include some hiden characters, such as '\n'.

If you define your url like below, this exception will raise:

url = '''
http://google.com
'''

because there are '\n' hide in the string. The url in fact become:

\nhttp://google.com\n

autocomplete ='off' is not working when the input type is password and make the input field above it to enable autocomplete

    <input type="password" id="byLast" class="bump25" autocomplete="new-password" onclick="this.type='text'" /> )

This worked for me

How do I apply a style to all children of an element

Instead of the * selector you can use the :not(selector) with the > selector and set something that definitely wont be a child.

Edit: I thought it would be faster but it turns out I was wrong. Disregard.

Example:

.container > :not(marquee){
        color:red;
    }


<div class="container">
    <p></p>
    <span></span>
<div>

List submodules in a Git repository

Use:

$ git submodule

It will list all the submodules in the specified Git repository.

What is causing "Unable to allocate memory for pool" in PHP?

Using a TTL of 0 means that APC will flush all the cache when it runs out of memory. The error don't appear anymore but it makes APC far less efficient. It's a no risk, no trouble, "I don't want to do my job" decision. APC is not meant to be used that way. You should choose a TTL high enough so the most accessed pages won't expire. The best is to give enough memory so APC doesn't need to flush cache.

Just read the manual to understand how ttl is used : http://www.php.net/manual/en/apc.configuration.php#ini.apc.ttl

The solution is to increase memory allocated to APC. Do this by increasing apc.shm_size.

If APC is compiled to use Shared Segment Memory you will be limited by your operating system. Type this command to see your system limit for each segment :

sysctl -a | grep -E "shmall|shmmax"

To alocate more memory you'll have to increase the number of segments with the parameter apc.shm_segments.

If APC is using mmap memory then you have no limit. The amount of memory is still defined by the same option apc.shm_size.

If there's not enough memory on the server, then use filters option to prevent less frequently accessed php files from being cached.

But never use a TTL of 0.

As c33s said, use apc.php to check your config. Copy the file from apc package to a webfolder and point browser to it. You'll see what is really allocated and how it is used. The graphs must remain stable after hours, if they are completly changing at each refresh, then it means that your setup is wrong (APC is flushing everything). Allocate 20% more ram than what APC really use as a security margin, and check it on a regular basis.

The default of allowing only 32MB is ridiculously low. PHP was designed when servers were 64MB and most scripts were using one php file per page. Nowadays solutions like Magento require more than 10k files (~60Mb in APC). You should allow enough memory so most of php files are always cached. It's not a waste, it's more efficient to keep opcode in ram rather than having the corresponding raw php in file cache. Nowadays we can find dedicated servers with 24Gb of memory for as low as $80/month, so don't hesitate to allow several GB to APC. I put 2GB out of 24GB on a server hosting 5Magento stores and ~40 wordpress website, APC uses 1.2GB. Count 64MB for Magento installation, 40MB for a Wordpress with some plugins.

Also, if you have developpment websites on the same server. Exclude them from cache.

Get Absolute Position of element within the window in wpf

I think what BrandonS wants is not the position of the mouse relative to the root element, but rather the position of some descendant element.

For that, there is the TransformToAncestor method:

Point relativePoint = myVisual.TransformToAncestor(rootVisual)
                              .Transform(new Point(0, 0));

Where myVisual is the element that was just double-clicked, and rootVisual is Application.Current.MainWindow or whatever you want the position relative to.

Use stored procedure to insert some data into a table

If you have the table definition to have an IDENTITY column e.g. IDENTITY(1,1) then don't include MyId in your INSERT INTO statement. The point of IDENTITY is it gives it the next unused value as the primary key value.

insert into MYDB.dbo.MainTable (MyFirstName, MyLastName, MyAddress, MyPort)
values(@myFirstName, @myLastName, @myAddress, @myPort)

There is then no need to pass the @MyId parameter into your stored procedure either. So change it to:

CREATE PROCEDURE [dbo].[sp_Test]
@myFirstName nvarchar(50)
,@myLastName nvarchar(50)
,@myAddress nvarchar(MAX)
,@myPort int

AS 

If you want to know what the ID of the newly inserted record is add

SELECT @@IDENTITY

to the end of your procedure. e.g. http://msdn.microsoft.com/en-us/library/ms187342.aspx

You will then be able to pick this up in which ever way you are calling it be it SQL or .NET.

P.s. a better way to show you table definision would have been to script the table and paste the text into your stackoverflow browser window because your screen shot is missing the column properties part where IDENTITY is set via the GUI. To do that right click the table 'Script Table as' --> 'CREATE to' --> Clipboard. You can also do File or New Query Editor Window (all self explanitory) experient and see what you get.

Comparing strings in C# with OR in an if statement

try

if (testString.Equals(testString2)){
}

How to sort Map values by key in Java?

In Java 8 you can also use .stream().sorted():

myMap.keySet().stream().sorted().forEach(key -> {
        String value = myMap.get(key);

        System.out.println("key: " + key);
        System.out.println("value: " + value);
    }
);

How to strip all non-alphabetic characters from string in SQL Server?

This solution, inspired by Mr. Allen's solution, requires a Numbers table of integers (which you should have on hand if you want to do serious query operations with good performance). It does not require a CTE. You can change the NOT IN (...) expression to exclude specific characters, or change it to an IN (...) OR LIKE expression to retain only certain characters.

SELECT (
    SELECT  SUBSTRING([YourString], N, 1)
    FROM    dbo.Numbers
    WHERE   N > 0 AND N <= CONVERT(INT, LEN([YourString]))
        AND SUBSTRING([YourString], N, 1) NOT IN ('(',')',',','.')
    FOR XML PATH('')
) AS [YourStringTransformed]
FROM ...

Moving Panel in Visual Studio Code to right side

Hope this will help someone.

-> open to keyboard shortcut

-> search for "workbench.action.togglePanelPosition"

-> assign your desired shortcut

I've assigned keybinding "cmd+`"

{
  "key": "cmd+`",
  "command": "workbench.action.togglePanelPosition"
}

now I can toggle the terminal by pressing "cmd + `"

How to add \newpage in Rmarkdown in a smart way?

In the initialization chunk I define a function

pagebreak <- function() {
  if(knitr::is_latex_output())
    return("\\newpage")
  else
    return('<div style="page-break-before: always;" />')
}

In the markdown part where I want to insert a page break, I type

`r pagebreak()`

How to set text color in submit button?

_x000D_
_x000D_
.button_x000D_
{_x000D_
    font-size: 13px;_x000D_
    color:green;_x000D_
}
_x000D_
<input type="submit" value="Fetch" class="button"/>
_x000D_
_x000D_
_x000D_

Difference between modes a, a+, w, w+, and r+ in built-in open function?

Same info, just in table form

                  | r   r+   w   w+   a   a+
------------------|--------------------------
read              | +   +        +        +
write             |     +    +   +    +   +
write after seek  |     +    +   +
create            |          +   +    +   +
truncate          |          +   +
position at start | +   +    +   +
position at end   |                   +   +

where meanings are: (just to avoid any misinterpretation)

  • read - reading from file is allowed
  • write - writing to file is allowed

  • create - file is created if it does not exist yet

  • trunctate - during opening of the file it is made empty (all content of the file is erased)

  • position at start - after file is opened, initial position is set to the start of the file

  • position at end - after file is opened, initial position is set to the end of the file

Note: a and a+ always append to the end of file - ignores any seek movements.
BTW. interesting behavior at least on my win7 / python2.7, for new file opened in a+ mode:
write('aa'); seek(0, 0); read(1); write('b') - second write is ignored
write('aa'); seek(0, 0); read(2); write('b') - second write raises IOError

#1071 - Specified key was too long; max key length is 1000 bytes

I was facing same issue, used below query to resolve it.

While creating DB you can use utf-8 encoding

eg. create database my_db character set utf8 collate utf8mb4;

EDIT: (Considering suggestions from comments) Changed utf8_bin to utf8mb4

Using NSLog for debugging

The proper way of using NSLog, as the warning tries to explain, is the use of a formatter, instead of passing in a literal:

Instead of:

NSString *digit = [[sender titlelabel] text];
NSLog(digit);

Use:

NSString *digit = [[sender titlelabel] text];
NSLog(@"%@",digit);

It will still work doing that first way, but doing it this way will get rid of the warning.

How to pass macro definition from "make" command line arguments (-D) to C source code?

Because of low reputation, I cannot comment the accepted answer.

I would like to mention the predefined variable CPPFLAGS. It might represent a better fit than CFLAGS or CXXFLAGS, since it is described by the GNU Make manual as:

Extra flags to give to the C preprocessor and programs that use it (the C and Fortran compilers).

Examples of built-in implicit rules that use CPPFLAGS

  • n.o is made automatically from n.c with a recipe of the form:
    • $(CC) $(CPPFLAGS) $(CFLAGS) -c
  • n.o is made automatically from n.cc, n.cpp, or n.C with a recipe of the form:
    • $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c

One would use the command make CPPFLAGS=-Dvar=123 to define the desired macro.

More info

How do you display code snippets in MS Word preserving format and syntax highlighting?

Use a monospaced font like Lucida Console, which comes with Windows. If you cut/paste from Visual Studio or something that supports syntax highlighting, you can often preserve the colour scheme of the syntax highlighter.

mysql count group by having

SELECT COUNT(*) 
FROM   (SELECT COUNT(*) 
        FROM   movies 
        GROUP  BY id 
        HAVING COUNT(genre) = 4) t

How can I revert a single file to a previous version?

You can take a diff that undoes the changes you want and commit that.

E.g. If you want to undo the changes in the range from..to, do the following

git diff to..from > foo.diff  # get a reverse diff
patch < foo.diff
git commit -a -m "Undid changes from..to".

Change navbar text color Bootstrap

.nav-link {
color: blue !important;
}

Worked for me. Bootstrap v4.3.1

append multiple values for one key in a dictionary

If I can rephrase your question, what you want is a dictionary with the years as keys and an array for each year containing a list of values associated with that year, right? Here's how I'd do it:

years_dict = dict()

for line in list:
    if line[0] in years_dict:
        # append the new number to the existing array at this slot
        years_dict[line[0]].append(line[1])
    else:
        # create a new array in this slot
        years_dict[line[0]] = [line[1]]

What you should end up with in years_dict is a dictionary that looks like the following:

{
    "2010": [2],
    "2009": [4,7],
    "1989": [8]
}

In general, it's poor programming practice to create "parallel arrays", where items are implicitly associated with each other by having the same index rather than being proper children of a container that encompasses them both.

How to construct a REST API that takes an array of id's for the resources

 api.com/users?id=id1,id2,id3,id4,id5
 api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5

IMO, above calls does not looks RESTful, however these are quick and efficient workaround (y). But length of the URL is limited by webserver, eg tomcat.

RESTful attempt:

POST http://example.com/api/batchtask

   [
    {
      method : "GET",
      headers : [..],
      url : "/users/id1"
    },
    {
      method : "GET",
      headers : [..],
      url : "/users/id2"
    }
   ]

Server will reply URI of newly created batchtask resource.

201 Created
Location: "http://example.com/api/batchtask/1254"

Now client can fetch batch response or task progress by polling

GET http://example.com/api/batchtask/1254


This is how others attempted to solve this issue:

Writing outputs to log file and console

I wanted to display logs on stdout and log file along with the timestamp. None of the above answers worked for me. I made use of process substitution and exec command and came up with the following code. Sample logs:

2017-06-21 11:16:41+05:30 Fetching information about files in the directory...

Add following lines at the top of your script:

LOG_FILE=script.log
exec > >(while read -r line; do printf '%s %s\n' "$(date --rfc-3339=seconds)" "$line" | tee -a $LOG_FILE; done)
exec 2> >(while read -r line; do printf '%s %s\n' "$(date --rfc-3339=seconds)" "$line" | tee -a $LOG_FILE; done >&2)

Hope this helps somebody!

Is there are way to make a child DIV's width wider than the parent DIV using CSS?

I had a similar issue. The content of the child element was supposed to stay in the parent element while the background had to extend the full viewport width.

I resolved this issue by making the child element position: relative and adding a pseudo element (:before) to it with position: absolute; top: 0; bottom: 0; width: 4000px; left: -1000px;. The pseudo element stays behind the actual child as a pseudo background element. This works in all browsers (even IE8+ and Safari 6+ - don't have the possibility to test older versions).

Small example fiddle: http://jsfiddle.net/vccv39j9/

SQL query to check if a name begins and ends with a vowel

select distinct(city) from STATION 
where lower(substr(city, -1)) in ('a','e','i','o','u') 
      and lower(substr(city, 1,1)) in ('a','e','i','o','u');

How can I send an HTTP POST request to a server from Excel using VBA?

In addition to the anwser of Bill the Lizard:

Most of the backends parse the raw post data. In PHP for example, you will have an array $_POST in which individual variables within the post data will be stored. In this case you have to use an additional header "Content-type: application/x-www-form-urlencoded":

Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = "http://www.somedomain.com"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
objHTTP.send ("var1=value1&var2=value2&var3=value3")

Otherwise you have to read the raw post data on the variable "$HTTP_RAW_POST_DATA".

How do I check for vowels in JavaScript?

benchmark

I think you can safely say a for loop is faster.

I do admit that a regexp looks cleaner in terms of code. If it's a real bottleneck then use a for loop, otherwise stick with the regular expression for reasons of "elegance"

If you want to go for simplicity then just use

function isVowel(c) {
    return ['a', 'e', 'i', 'o', 'u'].indexOf(c.toLowerCase()) !== -1
}

Importing data from a JSON file into R

First install the rjson package:

install.packages("rjson")

Then:

library("rjson")
json_file <- "http://api.worldbank.org/country?per_page=10&region=OED&lendingtype=LNX&format=json"
json_data <- fromJSON(paste(readLines(json_file), collapse=""))

Update: since version 0.2.1

json_data <- fromJSON(file=json_file)

Copy array items into another array

Use the concat function, like so:

var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayA.concat(arrayB);

The value of newArray will be [1, 2, 3, 4] (arrayA and arrayB remain unchanged; concat creates and returns a new array for the result).

How do I determine if a checkbox is checked?

You are trying to read the value of your checkbox before it is loaded. The script runs before the checkbox exists. You need to call your script when the page loads:

<body onload="dosomething()">

Example:

http://jsfiddle.net/jtbowden/6dx6A/

You are also missing a semi-colon after your first assignment.

await is only valid in async function

I had the same problem and the following block of code was giving the same error message:

repositories.forEach( repo => {
        const commits = await getCommits(repo);
        displayCommit(commits);
});

The problem is that the method getCommits() was async but I was passing it the argument repo which was also produced by a Promise. So, I had to add the word async to it like this: async(repo) and it started working:

repositories.forEach( async(repo) => {
        const commits = await getCommits(repo);
        displayCommit(commits);
});

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

how to use the Box-Cox power transformation in R

According to the Box-cox transformation formula in the paper Box,George E. P.; Cox,D.R.(1964). "An analysis of transformations", I think mlegge's post might need to be slightly edited.The transformed y should be (y^(lambda)-1)/lambda instead of y^(lambda). (Actually, y^(lambda) is called Tukey transformation, which is another distinct transformation formula.)
So, the code should be:

(trans <- bc$x[which.max(bc$y)])
[1] 0.4242424
# re-run with transformation
mnew <- lm(((y^trans-1)/trans) ~ x) # Instead of mnew <- lm(y^trans ~ x) 

More information

Please correct me if I misunderstood it.

"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.

How to define relative paths in Visual Studio Project?

If I get you right, you need ..\..\src

Get a list of URLs from a site

I would look into any number of online sitemap generation tools. Personally, I've used this one (java based)in the past, but if you do a google search for "sitemap builder" I'm sure you'll find lots of different options.

How to check if string contains Latin characters only?

There is no jquery needed:

var matchedPosition = str.search(/[a-z]/i);
if(matchedPosition != -1) {
    alert('found');
}

How to query data out of the box using Spring data JPA by both Sort and Pageable?

Pageable has an option to specify sort as well. From the java doc

PageRequest(int page, int size, Sort.Direction direction, String... properties) 

Creates a new PageRequest with sort parameters applied.

Find object by id in an array of JavaScript objects

As long as the browser supports ECMA-262, 5th edition (December 2009), this should work, almost one-liner:

var bFound = myArray.some(function (obj) {
    return obj.id === 45;
});

File Upload to HTTP server in iphone programming

This isn't an alternative solution; rather a suggestion for Brandon's popular answer (seeing as though I don't have enough rep to comment on that answer). If you're uploading large files; you're probably going to get a mmap malloc exception on account of having to read the file into memory to post it to your server.

You can tweak Brandon's code by replacing:

[request setHTTPBody:postbody];

With:

NSInputStream *stream = [[NSInputStream alloc] initWithData:postbody];
[request setHTTPBodyStream:stream];

Use Toast inside Fragment

        public void onClick(View v) {
            Context context = v.getContext();
            CharSequence text = "Message";
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }

postgresql - sql - count of `true` values

probably, the best approach is to use nullif function.

in general

select
    count(nullif(myCol = false, true)),  -- count true values
    count(nullif(myCol = true, true)),   -- count false values
    count(myCol);

or in short

select
    count(nullif(myCol, true)),  -- count false values
    count(nullif(myCol, false)), -- count true values
    count(myCol);

http://www.postgresql.org/docs/9.0/static/functions-conditional.html

How to show only next line after the matched one?

you can try with awk:

awk '/blah/{getline; print}' logfile

How can I write output from a unit test?

Solved with the following example:

public void CheckConsoleOutput()
{
    Console.WriteLine("Hello, World!");
    Trace.WriteLine("Trace Trace the World");
    Debug.WriteLine("Debug Debug World");
    Assert.IsTrue(true);
}

After running this test, under 'Test Passed', there is the option to view the output, which will bring up the output window.

When to choose mouseover() and hover() function?

.hover() function accepts two function arguments, one for mouseenter event and one for mouseleave event.

What does the M stand for in C# Decimal literal notation?

A real literal suffixed by M or m is of type decimal (money). For example, the literals 1m, 1.5m, 1e10m, and 123.456M are all of type decimal. This literal is converted to a decimal value by taking the exact value, and, if necessary, rounding to the nearest representable value using banker's rounding. Any scale apparent in the literal is preserved unless the value is rounded or the value is zero (in which latter case the sign and scale will be 0). Hence, the literal 2.900m will be parsed to form the decimal with sign 0, coefficient 2900, and scale 3.

Read more about real literals

Using NSPredicate to filter an NSArray based on NSDictionary keys

NSPredicate is only available in iPhone 3.0.

You won't notice that until try to run on device.

How to call a PHP file from HTML or Javascript

I just want to have a button on my website make a PHP file run

<form action="my.php" method="post">
    <input type="submit">
</form>

Generally speaking, however, unless you are sending new data to the server to be stored, you would just use a link.

<a href="my.php">run php</a>

(Although you should use link text that describes what happens from the user's point of view, not the servers)


I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately. I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.

This is tricker.

First, you do need to use a form and POST (since you are sending data to be stored).

Then you need to store the data somewhere. This is normally done using a database. Read up on the PDO library for PHP. It is the standard way to interact with databases.

Then you need to pull the data back out again. The simplest approach here is to use the query string to pass the primary key for the database row with the entry you wish to display.

<a href="showBlogEntry.php?entry_id=123">...</a>

Make sure you also read up on SQL injection and XSS.

Error: "setFile(null,false) call failed" when using log4j

To prevent this isue I changed all values in log4j.properties file with directory ${kafka.logs.dir} to my own directory. For example D:/temp/...

What is the difference between HTTP and REST?

No, REST is the way HTTP should be used.

Today we only use a tiny bit of the HTTP protocol's methods – namely GET and POST. The REST way to do it is to use all of the protocol's methods.

For example, REST dictates the usage of DELETE to erase a document (be it a file, state, etc.) behind a URI, whereas, with HTTP, you would misuse a GET or POST query like ...product/?delete_id=22.

Declaring an enum within a class

In general, I always put my enums in a struct. I have seen several guidelines including "prefixing".

enum Color
{
  Clr_Red,
  Clr_Yellow,
  Clr_Blue,
};

Always thought this looked more like C guidelines than C++ ones (for one because of the abbreviation and also because of the namespaces in C++).

So to limit the scope we now have two alternatives:

  • namespaces
  • structs/classes

I personally tend to use a struct because it can be used as parameters for template programming while a namespace cannot be manipulated.

Examples of manipulation include:

template <class T>
size_t number() { /**/ }

which returns the number of elements of enum inside the struct T :)

How do I sort a list of datetime or date objects?

You're getting None because list.sort() it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort() without assigning it to a again.

There is a built in function sorted(), which returns a sorted version of the list - a = sorted(a) will do what you want as well.

How do you convert a time.struct_time object into a datetime object?

This is not a direct answer to your question (which was answered pretty well already). However, having had times bite me on the fundament several times, I cannot stress enough that it would behoove you to look closely at what your time.struct_time object is providing, vs. what other time fields may have.

Assuming you have both a time.struct_time object, and some other date/time string, compare the two, and be sure you are not losing data and inadvertently creating a naive datetime object, when you can do otherwise.

For example, the excellent feedparser module will return a "published" field and may return a time.struct_time object in its "published_parsed" field:

time.struct_time(tm_year=2013, tm_mon=9, tm_mday=9, tm_hour=23, tm_min=57, tm_sec=42, tm_wday=0, tm_yday=252, tm_isdst=0)

Now note what you actually get with the "published" field.

Mon, 09 Sep 2013 19:57:42 -0400

By Stallman's Beard! Timezone information!

In this case, the lazy man might want to use the excellent dateutil module to keep the timezone information:

from dateutil import parser
dt = parser.parse(entry["published"])
print "published", entry["published"])
print "dt", dt
print "utcoffset", dt.utcoffset()
print "tzinfo", dt.tzinfo
print "dst", dt.dst()

which gives us:

published Mon, 09 Sep 2013 19:57:42 -0400
dt 2013-09-09 19:57:42-04:00
utcoffset -1 day, 20:00:00
tzinfo tzoffset(None, -14400)
dst 0:00:00

One could then use the timezone-aware datetime object to normalize all time to UTC or whatever you think is awesome.

How do you calculate the variance, median, and standard deviation in C++ or Java?

To calculate the mean, loop through the list/array of numbers, keeping track of the partial sums and the length. Then return the sum/length.

double sum = 0.0;
int length = 0;

for( double number : numbers ) {
    sum += number;
    length++;
}

return sum/length;

Variance is calculated similarly. Standard deviation is simply the square root of the variance:

double stddev = Math.sqrt( variance );

Node.js/Express routing with get params

For Query parameters like domain.com/test?format=json&type=mini format, then you can easily receive it via - req.query.

app.get('/test', function(req, res){
  var format = req.query.format,
      type = req.query.type;
});

Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist

I solved it by doing this:

  1. Copy the file content.
  2. Remove file.
  3. Run command: php artisan make:seeder .
  4. Copy the file content back in this file.

This happened because I made a change in the filename. I don't know why it didn't work after the change.

Creating a Custom Event

Yes you can do like this :

Creating advanced C# custom events

or

The Simplest C# Events Example Imaginable

public class Metronome
{
    public event TickHandler Tick;
    public EventArgs e = null;
    public delegate void TickHandler(Metronome m, EventArgs e);
    public void Start()
    {
        while (true)
        {
            System.Threading.Thread.Sleep(3000);
            if (Tick != null)
            {
                Tick(this, e);
            }
        }
    }
}
public class Listener
{
    public void Subscribe(Metronome m)
    {
        m.Tick += new Metronome.TickHandler(HeardIt);
    }

    private void HeardIt(Metronome m, EventArgs e)
    {
        System.Console.WriteLine("HEARD IT");
    }
}
class Test
{
    static void Main()
    {
        Metronome m = new Metronome();
        Listener l = new Listener();
        l.Subscribe(m);
        m.Start();
    }
}

How do I get video durations with YouTube API version 3?

This code extracts the YouTube video duration using the YouTube API v3 by passing a video ID. It worked for me.

<?php
    function getDuration($videoID){
       $apikey = "YOUR-Youtube-API-KEY"; // Like this AIcvSyBsLA8znZn-i-aPLWFrsPOlWMkEyVaXAcv
       $dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$videoID&key=$apikey");
       $VidDuration =json_decode($dur, true);
       foreach ($VidDuration['items'] as $vidTime)
       {
           $VidDuration= $vidTime['contentDetails']['duration'];
       }
       preg_match_all('/(\d+)/',$VidDuration,$parts);
       return $parts[0][0] . ":" .
              $parts[0][1] . ":".
              $parts[0][2]; // Return 1:11:46 (i.e.) HH:MM:SS
    }

    echo getDuration("zyeubYQxHyY"); // Video ID
?>

You can get your domain's own YouTube API key on https://console.developers.google.com and generate credentials for your own requirement.

How can I make an entire HTML form "readonly"?

I'd rather use jQuery:

$('#'+formID).find(':input').attr('disabled', 'disabled');

find() would go much deeper till nth nested child than children(), which looks for immediate children only.

mysql server port number

port number 3306 is used for MySQL and tomcat using 8080 port.more port numbers are available for run the servers or software whatever may be for our instant compilation..8080 is default for number so only we are getting port error in eclipse IDE. jvm and tomcat always prefer the 8080.3306 is default port number for MySQL.So only do not want to mention every time as "localhost:3306"

  <?php  
    $dbhost = 'localhost:3306';
//3306 default port number $dbhost='localhost'; is enough to specify the port number
//when we are utilizing xammp default port number is 8080.
      $dbuser = 'root';
      $dbpass = '';
         $db='users';

             $conn = mysqli_connect($dbhost, $dbuser, $dbpass,$db) or die ("could not connect to mysql");      

              // mysqli_select_db("users") or die ("no database");  

    if(! $conn ) {
        die('Could not connect: ' . mysqli_error($conn));
    }else{
        echo 'Connected successfully';
    }
    ?>

How to restart a node.js server

During development the best way to restart server for seeing changes made is to use nodemon

npm install nodemon -g

nodemon [your app name]

nodemon will watch the files in the directory that nodemon was started, and if they change, it will automatically restart your node application.

Check nodemon git repo: https://github.com/remy/nodemon

How do you convert between 12 hour time and 24 hour time in PHP?

// 24-hour time to 12-hour time 
$time_in_12_hour_format  = date("g:i a", strtotime("13:30"));

// 12-hour time to 24-hour time 
$time_in_24_hour_format  = date("H:i", strtotime("1:30 PM"));

nginx: how to create an alias url route?

server {
  server_name example.com;
  root /path/to/root;
  location / {
    # bla bla
  }
  location /demo {
    alias /path/to/root/production/folder/here;
  }
}

If you need to use try_files inside /demo you'll need to replace alias with a root and do a rewrite because of the bug explained here

How to enable Bootstrap tooltip on disabled button?

If you're desperate (like i was) for tooltips on checkboxes, textboxes and the like, then here is my hackey workaround:

$('input:disabled, button:disabled').after(function (e) {
    d = $("<div>");
    i = $(this);
    d.css({
        height: i.outerHeight(),
        width: i.outerWidth(),
        position: "absolute",
    })
    d.css(i.offset());
    d.attr("title", i.attr("title"));
    d.tooltip();
    return d;
});

Working examples: http://jsfiddle.net/WB6bM/11/

For what its worth, I believe tooltips on disabled form elements is very important to the UX. If you're preventing somebody from doing something, you should tell them why.

Why I get 411 Length required error?

I had the same error when I imported web requests from fiddler captured sessions to Visual Studio webtests. Some POST requests did not have a StringHttpBody tag. I added an empty one to them and the error was gone. Add this after the Headers tag:

    <StringHttpBody ContentType="" InsertByteOrderMark="False">
  </StringHttpBody>

How to change checkbox's border style in CSS?

You should use

-moz-appearance:none;
-webkit-appearance:none;
-o-appearance:none;

Then you get rid of the default checkbox image/style and can style it. Anyway a border will still be there in Firefox

What is the point of the diamond operator (<>) in Java 7?

Your understanding is slightly flawed. The diamond operator is a nice feature as you don't have to repeat yourself. It makes sense to define the type once when you declare the type but just doesn't make sense to define it again on the right side. The DRY principle.

Now to explain all the fuzz about defining types. You are right that the type is removed at runtime but once you want to retrieve something out of a List with type definition you get it back as the type you've defined when declaring the list otherwise it would lose all specific features and have only the Object features except when you'd cast the retrieved object to it's original type which can sometimes be very tricky and result in a ClassCastException.

Using List<String> list = new LinkedList() will get you rawtype warnings.

Smooth scroll without the use of jQuery

I've made something like this. I have no idea if its working in IE8. Tested in IE9, Mozilla, Chrome, Edge.

function scroll(toElement, speed) {
  var windowObject = window;
  var windowPos = windowObject.pageYOffset;
  var pointer = toElement.getAttribute('href').slice(1);
  var elem = document.getElementById(pointer);
  var elemOffset = elem.offsetTop;

  var counter = setInterval(function() {
    windowPos;

    if (windowPos > elemOffset) { // from bottom to top
      windowObject.scrollTo(0, windowPos);
      windowPos -= speed;

      if (windowPos <= elemOffset) { // scrolling until elemOffset is higher than scrollbar position, cancel interval and set scrollbar to element position
        clearInterval(counter);
        windowObject.scrollTo(0, elemOffset);
      }
    } else { // from top to bottom
      windowObject.scrollTo(0, windowPos);
      windowPos += speed;

      if (windowPos >= elemOffset) { // scroll until scrollbar is lower than element, cancel interval and set scrollbar to element position
        clearInterval(counter);
        windowObject.scrollTo(0, elemOffset);
      }
    }

  }, 1);
}

//call example

var navPointer = document.getElementsByClassName('nav__anchor');

for (i = 0; i < navPointer.length; i++) {
  navPointer[i].addEventListener('click', function(e) {
    scroll(this, 18);
    e.preventDefault();
  });
}

Description

  • pointer—get element and chceck if it has attribute "href" if yes, get rid of "#"
  • elem—pointer variable without "#"
  • elemOffset—offset of "scroll to" element from the top of the page

Detecting Windows or Linux?

Useful simple class are forked by me on: https://gist.github.com/kiuz/816e24aa787c2d102dd0

public class OSValidator {

    private static String OS = System.getProperty("os.name").toLowerCase();

    public static void main(String[] args) {

        System.out.println(OS);

        if (isWindows()) {
            System.out.println("This is Windows");
        } else if (isMac()) {
            System.out.println("This is Mac");
        } else if (isUnix()) {
            System.out.println("This is Unix or Linux");
        } else if (isSolaris()) {
            System.out.println("This is Solaris");
        } else {
            System.out.println("Your OS is not support!!");
        }
    }

    public static boolean isWindows() {
        return OS.contains("win");
    }

    public static boolean isMac() {
        return OS.contains("mac");
    }

    public static boolean isUnix() {
        return (OS.contains("nix") || OS.contains("nux") || OS.contains("aix"));
    }

    public static boolean isSolaris() {
        return OS.contains("sunos");
    }
    public static String getOS(){
        if (isWindows()) {
            return "win";
        } else if (isMac()) {
            return "osx";
        } else if (isUnix()) {
            return "uni";
        } else if (isSolaris()) {
            return "sol";
        } else {
            return "err";
        }
    }

}

jwt check if token expired

Sadly @Andrés Montoya answer has a flaw which is related to how he compares the obj. I found a solution here which should solve this:

const now = Date.now().valueOf() / 1000

if (typeof decoded.exp !== 'undefined' && decoded.exp < now) {
    throw new Error(`token expired: ${JSON.stringify(decoded)}`)
}
if (typeof decoded.nbf !== 'undefined' && decoded.nbf > now) {
    throw new Error(`token expired: ${JSON.stringify(decoded)}`)
}

Thanks to thejohnfreeman!

ORA-28040: No matching authentication protocol exception

I was using eclipse and after trying all the other answers it didn't work for me. In the end, what worked for me was moving the ojdb7.jar to top in the Build Path. This occurs when multiple jars have conflicting same classes.

  1. Select project in Project Explorer
  2. Right click on Project -> Build Path -> Configure Build Path
  3. Go to Order and Export tab and select ojdbc.jar
  4. Click button TOP to move it to top

How to insert current datetime in postgresql insert query

You can of course format the result of current_timestamp(). Please have a look at the various formatting functions in the official documentation.

What is jQuery Unobtrusive Validation?

With the unobtrusive way:

  • You don't have to call the validate() method.
  • You specify requirements using data attributes (data-val, data-val-required, etc.)

Jquery Validate Example:

<input type="text" name="email" class="required">
<script>
        $(function () {
            $("form").validate();
        });
</script>

Jquery Validate Unobtrusive Example:

<input type="text" name="email" data-val="true" 
data-val-required="This field is required.">  

<div class="validation-summary-valid" data-valmsg-summary="true">
    <ul><li style="display:none"></li></ul>
</div>

Django templates: If false?

In old version you can only use the ifequal or ifnotequal

{% ifequal YourVariable ExpectValue %}
    # Do something here.
{% endifequal %}

Example:

{% ifequal userid 1 %}
  Hello No.1
{% endifequal %}

{% ifnotequal username 'django' %}
  You are not django!
{% else %}
  Hi django!
{% endifnotequal %}

As in the if tag, an {% else %} clause is optional.

The arguments can be hard-coded strings, so the following is valid:

{% ifequal user.username "adrian" %} ... {% endifequal %} An alternative to the ifequal tag is to use the if tag and the == operator.

ifnotequal Just like ifequal, except it tests that the two arguments are not equal.

An alternative to the ifnotequal tag is to use the if tag and the != operator.

However, now we can use if/else easily

{% if somevar >= 1 %}
{% endif %}

{% if "bc" in "abcdef" %}
  This appears since "bc" is a substring of "abcdef"
{% endif %}

Complex expressions

All of the above can be combined to form complex expressions. For such expressions, it can be important to know how the operators are grouped when the expression is evaluated - that is, the precedence rules. The precedence of the operators, from lowest to highest, is as follows:

  • or
  • and
  • not
  • in
  • ==, !=, <, >, <=, >=

More detail

https://docs.djangoproject.com/en/dev/ref/templates/builtins/

How can I check if mysql is installed on ubuntu?

With this command:

 dpkg -s mysql-server | grep Status

How can I determine if a variable is 'undefined' or 'null'?

Calling typeof null returns a value of “object”, as the special value null is considered to be an empty object reference. Safari through version 5 and Chrome through version 7 have a quirk where calling typeof on a regular expression returns “function” while all other browsers return “object”.

Converting a generic list to a CSV string

I like a nice simple extension method

 public static string ToCsv(this List<string> itemList)
         {
             return string.Join(",", itemList);
         }

Then you can just call the method on the original list:

string CsvString = myList.ToCsv();

Cleaner and easier to read than some of the other suggestions.

How to add dividers and spaces between items in RecyclerView?

If you want to add same space for items, the simplest way is to add top+left padding for RecycleView and right+bottom margins to card items.

dimens.xml

<resources>
    <dimen name="divider">1dp</dimen>
</resources>

list_item.xml

<CardView
 android:layout_marginBottom="@dimen/divider"
 android:layout_marginRight="@dimen/divider">
 ...
</CardView>

list.xml

<RecyclerView
 android:paddingLeft="@dimen/divider"
 android:paddingTop="@dimen/divider"
/>

Web.Config Debug/Release

To make the transform work in development (using F5 or CTRL + F5) I drop ctt.exe (https://ctt.codeplex.com/) in the packages folder (packages\ConfigTransform\ctt.exe).

Then I register a pre- or post-build event in Visual Studio...

$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)connectionStrings.config" transform:"$(ProjectDir)connectionStrings.$(ConfigurationName).config" destination:"$(ProjectDir)connectionStrings.config"
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)web.config" transform:"$(ProjectDir)web.$(ConfigurationName).config" destination:"$(ProjectDir)web.config"

For the transforms I use SlowCheeta VS extension (https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5).

How to read a line from a text file in c/c++?

In C, fgets(), and you need to know the maximum size to prevent truncation.

append option to select menu?

You can also use insertAdjacentHTML function:

const select = document.querySelector('select')
const value = 'bmw'
const label = 'BMW'

select.insertAdjacentHTML('beforeend', `
  <option value="${value}">${label}</option>
`)

React Hooks useState() with Object

I leave you a utility function to inmutably update objects

/**
 * Inmutable update object
 * @param  {Object} oldObject     Object to update
 * @param  {Object} updatedValues Object with new values
 * @return {Object}               New Object with updated values
 */
export const updateObject = (oldObject, updatedValues) => {
  return {
    ...oldObject,
    ...updatedValues
  };
};

So you can use it like this

const MyComponent = props => {

  const [orderForm, setOrderForm] = useState({
    specialities: {
      elementType: "select",
      elementConfig: {
        options: [],
        label: "Specialities"
      },
      touched: false
    }
  });


// I want to update the options list, to fill a select element

  // ---------- Update with fetched elements ---------- //

  const updateSpecialitiesData = data => {
    // Inmutably update elementConfig object. i.e label field is not modified
    const updatedOptions = updateObject(
      orderForm[formElementKey]["elementConfig"],
      {
        options: data
      }
    );
    // Inmutably update the relevant element.
    const updatedFormElement = updateObject(orderForm[formElementKey], {
      touched: true,
      elementConfig: updatedOptions
    });
    // Inmutably update the relevant element in the state.
    const orderFormUpdated = updateObject(orderForm, {
      [formElementKey]: updatedFormElement
    });
    setOrderForm(orderFormUpdated);
  };

  useEffect(() => {
      // some code to fetch data
      updateSpecialitiesData.current("specialities",fetchedData);
  }, [updateSpecialitiesData]);

// More component code
}

If not you have more utilities here : https://es.reactjs.org/docs/update.html

How to make "if not true condition"?

What am I doing wrong?

$(...) holds the value, not the exit status, that is why this approach is wrong. However, in this specific case, it does indeed work because sysa will be printed which makes the test statement come true. However, if ! [ $(true) ]; then echo false; fi would always print false because the true command does not write anything to stdout (even though the exit code is 0). That is why it needs to be rephrased to if ! grep ...; then.

An alternative would be cat /etc/passwd | grep "sysa" || echo error. Edit: As Alex pointed out, cat is useless here: grep "sysa" /etc/passwd || echo error.

Found the other answers rather confusing, hope this helps someone.

Hash string in c#

If performance is not a major concern, you can also use any of these methods:
(In case you wanted the hash string to be in upper case, replace "x2" with "X2".)

public static string SHA256ToString(string s) 
{
    using (var alg = SHA256.Create())
        return string.Join(null, alg.ComputeHash(Encoding.UTF8.GetBytes(s)).Select(x => x.ToString("x2")));
}

or:

public static string SHA256ToString(string s)
{            
    using (var alg = SHA256.Create())
        return alg.ComputeHash(Encoding.UTF8.GetBytes(s)).Aggregate(new StringBuilder(), (sb, x) => sb.Append(x.ToString("x2"))).ToString();
}

Open URL in Java to get the content

public class UrlContent{
    public static void main(String[] args) {

        URL url;

        try {
            // get URL content

            String a="http://localhost:8080/TestWeb/index.jsp";
            url = new URL(a);
            URLConnection conn = url.openConnection();

            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(
                               new InputStreamReader(conn.getInputStream()));

            String inputLine;
            while ((inputLine = br.readLine()) != null) {
                    System.out.println(inputLine);
            }
            br.close();

            System.out.println("Done");

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Truncate all tables in a MySQL database in one command?

Soln 1)

mysql> select group_concat('truncate',' ',table_name,';') from information_schema.tables where table_schema="db_name" into outfile '/tmp/a.txt';
mysql> /tmp/a.txt;

Soln 2)

- Export only structure of a db
- drop the database
- import the .sql of structure 

-- edit ----

earlier in solution 1, i had mentioned concat() instead of group_concat() which would have not returned the desired result

What is the difference between map and flatMap and a good use case for each?

map and flatMap are similar, in the sense they take a line from the input RDD and apply a function on it. The way they differ is that the function in map returns only one element, while function in flatMap can return a list of elements (0 or more) as an iterator.

Also, the output of the flatMap is flattened. Although the function in flatMap returns a list of elements, the flatMap returns an RDD which has all the elements from the list in a flat way (not a list).

Send and Receive a file in socket programming in Linux with C/C++ (GCC/G++)

Minimal runnable POSIX read + write example

Usage:

  1. get two computers on a LAN.

    For example, this will work if both computers are connected to your home router in most cases, which is how I tested it.

  2. On the server computer:

    1. Find the server local IP with ifconfig, e.g. 192.168.0.10

    2. Run:

      ./server output.tmp 12345
      
  3. On the client computer:

    printf 'ab\ncd\n' > input.tmp
    ./client input.tmp 192.168.0.10 12345
    
  4. Outcome: a file output.tmp is created on the sever computer containing 'ab\ncd\n'!

server.c

/*
Receive a file over a socket.

Saves it to output.tmp by default.

Interface:

    ./executable [<output_file> [<port>]]

Defaults:

- output_file: output.tmp
- port: 12345
*/

#define _XOPEN_SOURCE 700

#include <stdio.h>
#include <stdlib.h>

#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h> /* getprotobyname */
#include <netinet/in.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <unistd.h>

int main(int argc, char **argv) {
    char *file_path = "output.tmp";
    char buffer[BUFSIZ];
    char protoname[] = "tcp";
    int client_sockfd;
    int enable = 1;
    int filefd;
    int i;
    int server_sockfd;
    socklen_t client_len;
    ssize_t read_return;
    struct protoent *protoent;
    struct sockaddr_in client_address, server_address;
    unsigned short server_port = 12345u;

    if (argc > 1) {
        file_path = argv[1];
        if (argc > 2) {
            server_port = strtol(argv[2], NULL, 10);
        }
    }

    /* Create a socket and listen to it.. */
    protoent = getprotobyname(protoname);
    if (protoent == NULL) {
        perror("getprotobyname");
        exit(EXIT_FAILURE);
    }
    server_sockfd = socket(
        AF_INET,
        SOCK_STREAM,
        protoent->p_proto
    );
    if (server_sockfd == -1) {
        perror("socket");
        exit(EXIT_FAILURE);
    }
    if (setsockopt(server_sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) < 0) {
        perror("setsockopt(SO_REUSEADDR) failed");
        exit(EXIT_FAILURE);
    }
    server_address.sin_family = AF_INET;
    server_address.sin_addr.s_addr = htonl(INADDR_ANY);
    server_address.sin_port = htons(server_port);
    if (bind(
            server_sockfd,
            (struct sockaddr*)&server_address,
            sizeof(server_address)
        ) == -1
    ) {
        perror("bind");
        exit(EXIT_FAILURE);
    }
    if (listen(server_sockfd, 5) == -1) {
        perror("listen");
        exit(EXIT_FAILURE);
    }
    fprintf(stderr, "listening on port %d\n", server_port);

    while (1) {
        client_len = sizeof(client_address);
        puts("waiting for client");
        client_sockfd = accept(
            server_sockfd,
            (struct sockaddr*)&client_address,
            &client_len
        );
        filefd = open(file_path,
                O_WRONLY | O_CREAT | O_TRUNC,
                S_IRUSR | S_IWUSR);
        if (filefd == -1) {
            perror("open");
            exit(EXIT_FAILURE);
        }
        do {
            read_return = read(client_sockfd, buffer, BUFSIZ);
            if (read_return == -1) {
                perror("read");
                exit(EXIT_FAILURE);
            }
            if (write(filefd, buffer, read_return) == -1) {
                perror("write");
                exit(EXIT_FAILURE);
            }
        } while (read_return > 0);
        close(filefd);
        close(client_sockfd);
    }
    return EXIT_SUCCESS;
}

client.c

/*
Send a file over a socket.

Interface:

    ./executable [<input_path> [<sever_hostname> [<port>]]]

Defaults:

- input_path: input.tmp
- server_hostname: 127.0.0.1
- port: 12345
*/

#define _XOPEN_SOURCE 700

#include <stdio.h>
#include <stdlib.h>

#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h> /* getprotobyname */
#include <netinet/in.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <unistd.h>

int main(int argc, char **argv) {
    char protoname[] = "tcp";
    struct protoent *protoent;
    char *file_path = "input.tmp";
    char *server_hostname = "127.0.0.1";
    char *server_reply = NULL;
    char *user_input = NULL;
    char buffer[BUFSIZ];
    in_addr_t in_addr;
    in_addr_t server_addr;
    int filefd;
    int sockfd;
    ssize_t i;
    ssize_t read_return;
    struct hostent *hostent;
    struct sockaddr_in sockaddr_in;
    unsigned short server_port = 12345;

    if (argc > 1) {
        file_path = argv[1];
        if (argc > 2) {
            server_hostname = argv[2];
            if (argc > 3) {
                server_port = strtol(argv[3], NULL, 10);
            }
        }
    }

    filefd = open(file_path, O_RDONLY);
    if (filefd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }

    /* Get socket. */
    protoent = getprotobyname(protoname);
    if (protoent == NULL) {
        perror("getprotobyname");
        exit(EXIT_FAILURE);
    }
    sockfd = socket(AF_INET, SOCK_STREAM, protoent->p_proto);
    if (sockfd == -1) {
        perror("socket");
        exit(EXIT_FAILURE);
    }
    /* Prepare sockaddr_in. */
    hostent = gethostbyname(server_hostname);
    if (hostent == NULL) {
        fprintf(stderr, "error: gethostbyname(\"%s\")\n", server_hostname);
        exit(EXIT_FAILURE);
    }
    in_addr = inet_addr(inet_ntoa(*(struct in_addr*)*(hostent->h_addr_list)));
    if (in_addr == (in_addr_t)-1) {
        fprintf(stderr, "error: inet_addr(\"%s\")\n", *(hostent->h_addr_list));
        exit(EXIT_FAILURE);
    }
    sockaddr_in.sin_addr.s_addr = in_addr;
    sockaddr_in.sin_family = AF_INET;
    sockaddr_in.sin_port = htons(server_port);
    /* Do the actual connection. */
    if (connect(sockfd, (struct sockaddr*)&sockaddr_in, sizeof(sockaddr_in)) == -1) {
        perror("connect");
        return EXIT_FAILURE;
    }

    while (1) {
        read_return = read(filefd, buffer, BUFSIZ);
        if (read_return == 0)
            break;
        if (read_return == -1) {
            perror("read");
            exit(EXIT_FAILURE);
        }
        /* TODO use write loop: https://stackoverflow.com/questions/24259640/writing-a-full-buffer-using-write-system-call */
        if (write(sockfd, buffer, read_return) == -1) {
            perror("write");
            exit(EXIT_FAILURE);
        }
    }
    free(user_input);
    free(server_reply);
    close(filefd);
    exit(EXIT_SUCCESS);
}

GitHub upstream.

Further comments

Possible improvements:

  • Currently output.tmp gets overwritten each time a send is done.

    This begs for the creation of a simple protocol that allows to pass a filename so that multiple files can be uploaded, e.g.: filename up to the first newline character, max filename 256 chars, and the rest until socket closure are the contents. Of course, that would require sanitation to avoid a path transversal vulnerability.

    Alternatively, we could make a server that hashes the files to find filenames, and keeps a map from original paths to hashes on disk (on a database).

  • Only one client can connect at a time.

    This is specially harmful if there are slow clients whose connections last for a long time: the slow connection halts everyone down.

    One way to work around that is to fork a process / thread for each accept, start listening again immediately, and use file lock synchronization on the files.

  • Add timeouts, and close clients if they take too long. Or else it would be easy to do a DoS.

    poll or select are some options: How to implement a timeout in read function call?

A simple HTTP wget implementation is shown at: How to make an HTTP get request in C without libcurl?

Tested on Ubuntu 15.10.

How to change the port of Tomcat from 8080 to 80?

On modern linux the best approach (for me) is to use xinetd :

1) create /etc/xinet.d/tomcat-http

service http
{
        disable = no
        socket_type = stream
        user = root
        wait = no
        redirect = 127.0.0.1 8080
}

2) create /etc/xinet.d/tomcat-https

service https
{
        disable = no
        socket_type = stream
        user = root
        wait = no
        redirect = 127.0.0.1 8443
}

3) chkconfig xinetd on

4) /etc/init.d/xinetd start

how to bold words within a paragraph in HTML/CSS?

I know this question is old but I ran across it and I know other people might have the same problem. All these answers are okay but do not give proper detail or actual TRUE advice.

When wanting to style a specific section of a paragraph use the span tag.

<p><span style="font-weight:900">Andy Warhol</span> (August 6, 1928 - February 22, 1987) 

was an American artist who was a leading figure in the visual art movement known as pop 

art.</p>

Andy Warhol (August 6, 1928 - February 22, 1987) was an American artist who was a leading figure in the visual art movement known as pop art.

As the code shows, the span tag styles on the specified words: "Andy Warhol". You can further style a word using any CSS font styling codes.

{font-weight; font-size; text-decoration; font-family; margin; color}, etc. 

Any of these and more can be used to style a word, group of words, or even specified paragraphs without having to add a class to the CSS Style Sheet Doc. I hope this helps someone!

Most efficient way to remove special characters from string

HashSet is O(1)
Not sure if it is faster than the existing comparison

private static HashSet<char> ValidChars = new HashSet<char>() { 'a', 'b', 'c', 'A', 'B', 'C', '1', '2', '3', '_' };
public static string RemoveSpecialCharacters(string str)
{
    StringBuilder sb = new StringBuilder(str.Length / 2);
    foreach (char c in str)
    {
        if (ValidChars.Contains(c)) sb.Append(c);
    }
    return sb.ToString();
}

I tested and this in not faster than the accepted answer.
I will leave it up as if you needed a configurable set of characters this would be a good solution.

How to correct TypeError: Unicode-objects must be encoded before hashing?

To store the password (PY3):

import hashlib, os
password_salt = os.urandom(32).hex()
password = '12345'

hash = hashlib.sha512()
hash.update(('%s%s' % (password_salt, password)).encode('utf-8'))
password_hash = hash.hexdigest()

How to get all elements which name starts with some string?

A quick and easy way is to use jQuery and do this:

var $eles = $(":input[name^='q1_']").css("color","yellow");

That will grab all elements whose name attribute starts with 'q1_'. To convert the resulting collection of jQuery objects to a DOM collection, do this:

var DOMeles = $eles.get();

see http://api.jquery.com/attribute-starts-with-selector/

In pure DOM, you could use getElementsByTagName to grab all input elements, and loop through the resulting array. Elements with name starting with 'q1_' get pushed to another array:

var eles = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
    if(inputs[i].name.indexOf('q1_') == 0) {
        eles.push(inputs[i]);
    }
}

How to get status code from webclient?

If you are using .Net 4.0 (or less):

class BetterWebClient : WebClient
{
        private WebRequest _Request = null;

        protected override WebRequest GetWebRequest(Uri address)
        {
            this._Request = base.GetWebRequest(address);

            if (this._Request is HttpWebRequest)
            {
                ((HttpWebRequest)this._Request).AllowAutoRedirect = false;
            }

            return this._Request;
        } 

        public HttpStatusCode StatusCode()
        {
            HttpStatusCode result;

            if (this._Request == null)
            {
                throw (new InvalidOperationException("Unable to retrieve the status 
                       code, maybe you haven't made a request yet."));
            }

            HttpWebResponse response = base.GetWebResponse(this._Request) 
                                       as HttpWebResponse;

            if (response != null)
            {
                result = response.StatusCode;
            }
            else
            {
                throw (new InvalidOperationException("Unable to retrieve the status 
                       code, maybe you haven't made a request yet."));
            }

            return result;
        }
    }

If you are using .Net 4.5.X or newer, switch to HttpClient:

var response = await client.GetAsync("http://www.contoso.com/");
var statusCode = response.StatusCode;

How to check if any flags of a flag combination are set?

I created a simple extension method that does not need a check on Enum types:

public static bool HasAnyFlag(this Enum value, Enum flags)
{
    return
        value != null && ((Convert.ToInt32(value) & Convert.ToInt32(flags)) != 0);
}

It also works on nullable enums. The standard HasFlag method does not, so I created an extension to cover that too.

public static bool HasFlag(this Enum value, Enum flags)
{
    int f = Convert.ToInt32(flags);

    return
        value != null && ((Convert.ToInt32(value) & f) == f);
}

A simple test:

[Flags]
enum Option
{
    None = 0x00,
    One = 0x01,
    Two = 0x02,
    Three = One | Two,
    Four = 0x04
}

[TestMethod]
public void HasAnyFlag()
{
    Option o1 = Option.One;
    Assert.AreEqual(true, o1.HasAnyFlag(Option.Three));
    Assert.AreEqual(false, o1.HasFlag(Option.Three));

    o1 |= Option.Two;
    Assert.AreEqual(true, o1.HasAnyFlag(Option.Three));
    Assert.AreEqual(true, o1.HasFlag(Option.Three));
}

[TestMethod]
public void HasAnyFlag_NullableEnum()
{
    Option? o1 = Option.One;
    Assert.AreEqual(true, o1.HasAnyFlag(Option.Three));
    Assert.AreEqual(false, o1.HasFlag(Option.Three));

    o1 |= Option.Two;
    Assert.AreEqual(true, o1.HasAnyFlag(Option.Three));
    Assert.AreEqual(true, o1.HasFlag(Option.Three));
}

Enjoy!

Java Byte Array to String to Byte Array

What I did:

return to clients:

byte[] result = ****encrypted data****;

String str = Base64.encodeBase64String(result);

return str;

receive from clients:

 byte[] bytes = Base64.decodeBase64(str);

your data will be transferred in this format:

OpfyN9paAouZ2Pw+gDgGsDWzjIphmaZbUyFx5oRIN1kkQ1tDbgoi84dRfklf1OZVdpAV7TonlTDHBOr93EXIEBoY1vuQnKXaG+CJyIfrCWbEENJ0gOVBr9W3OlFcGsZW5Cf9uirSmx/JLLxTrejZzbgq3lpToYc3vkyPy5Y/oFWYljy/3OcC/S458uZFOc/FfDqWGtT9pTUdxLDOwQ6EMe0oJBlMXm8J2tGnRja4F/aVHfQddha2nUMi6zlvAm8i9KnsWmQG//ok25EHDbrFBP2Ia/6Bx/SGS4skk/0couKwcPVXtTq8qpNh/aYK1mclg7TBKHfF+DHppwd30VULpA== 

Setting background images in JFrame

You can use the Background Panel class. It does the custom painting as explained above but gives you options to display the image scaled, tiled or normal size. It also explains how you can use a JLabel with an image as the content pane for the frame.

Change onClick attribute with javascript

Well, just do this and your problem is solved :

document.getElementById('buttonLED'+id).setAttribute('onclick','writeLED(1,1)')

Have a nice day XD

Using PowerShell to remove lines from a text file if it contains a string

Escape the | character using a backtick

get-content c:\new\temp_*.txt | select-string -pattern 'H`|159' -notmatch | Out-File c:\new\newfile.txt

How to process a file in PowerShell line-by-line as a stream

If you are really about to work on multi-gigabyte text files then do not use PowerShell. Even if you find a way to read it faster processing of huge amount of lines will be slow in PowerShell anyway and you cannot avoid this. Even simple loops are expensive, say for 10 million iterations (quite real in your case) we have:

# "empty" loop: takes 10 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) {} }

# "simple" job, just output: takes 20 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i } }

# "more real job": 107 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i.ToString() -match '1' } }

UPDATE: If you are still not scared then try to use the .NET reader:

$reader = [System.IO.File]::OpenText("my.log")
try {
    for() {
        $line = $reader.ReadLine()
        if ($line -eq $null) { break }
        # process the line
        $line
    }
}
finally {
    $reader.Close()
}

UPDATE 2

There are comments about possibly better / shorter code. There is nothing wrong with the original code with for and it is not pseudo-code. But the shorter (shortest?) variant of the reading loop is

$reader = [System.IO.File]::OpenText("my.log")
while($null -ne ($line = $reader.ReadLine())) {
    $line
}

Ajax post request in laravel 5 return error 500 (Internal Server Error)

You can add your URLs to VerifyCsrfToken.php middleware. The URLs will be excluded from CSRF verification.

protected $except = [
    "your url",
    "your url/abc"
];

Install dependencies globally and locally using package.json

New Note: You probably don't want or need to do this. What you probably want to do is just put those types of command dependencies for build/test etc. in the devDependencies section of your package.json. Anytime you use something from scripts in package.json your devDependencies commands (in node_modules/.bin) act as if they are in your path.

For example:

npm i --save-dev mocha # Install test runner locally
npm i --save-dev babel # Install current babel locally

Then in package.json:

// devDependencies has mocha and babel now

"scripts": {
  "test": "mocha",
  "build": "babel -d lib src",
  "prepublish": "babel -d lib src"
}

Then at your command prompt you can run:

npm run build # finds babel
npm test # finds mocha

npm publish # will run babel first

But if you really want to install globally, you can add a preinstall in the scripts section of the package.json:

"scripts": {
  "preinstall": "npm i -g themodule"
}

So actually my npm install executes npm install again .. which is weird but seems to work.

Note: you might have issues if you are using the most common setup for npm where global Node package installs required sudo. One option is to change your npm configuration so this isn't necessary:

npm config set prefix ~/npm, add $HOME/npm/bin to $PATH by appending export PATH=$HOME/npm/bin:$PATH to your ~/.bashrc.

Excel column number from column name

Based on Anastasiya's answer. I think this is the shortest vba command:

Option Explicit

Sub Sample()
    Dim sColumnLetter as String
    Dim iColumnNumber as Integer

    sColumnLetter = "C"
    iColumnNumber = Columns(sColumnLetter).Column

    MsgBox "The column number is " & iColumnNumber
End Sub

Caveat: The only condition for this code to work is that a worksheet is active, because Columns is equivalent to ActiveSheet.Columns. ;)

VBA code to set date format for a specific column as "yyyy-mm-dd"

Use the range's NumberFormat property to force the format of the range like this:

Sheet1.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"

MySql Error: Can't update table in stored function/trigger because it is already used by statement which invoked this stored function/trigger

@gerrit_hoekstra wrote: "However, the value of an auto-increment field is only available to an "AFTER-INSERT" trigger - it defaults to 0 in the BEFORE-case."

That is correct but you can select the auto-increment field value that will be inserted by the subsequent INSERT quite easily. This is an example that works:

CREATE DEFINER = CURRENT_USER TRIGGER `lgffin`.`variable_BEFORE_INSERT` BEFORE INSERT 
ON `variable` FOR EACH ROW
BEGIN
    SET NEW.prefixed_id = CONCAT(NEW.fixed_variable, (SELECT `AUTO_INCREMENT`
                                                FROM  INFORMATION_SCHEMA.TABLES
                                                WHERE TABLE_SCHEMA = 'lgffin'
                                                AND   TABLE_NAME   = 'variable'));      
END

how to activate a textbox if I select an other option in drop down box

Inline:

<select 
onchange="var val = this.options[this.selectedIndex].value;
this.form.color[1].style.display=(val=='others')?'block':'none'">

I used to do this

In the head (give the select an ID):

window.onload=function() {
  var sel = document.getElementById('color');
  sel.onchange=function() {
    var val = this.options[this.selectedIndex].value;
    if (val == 'others') {
      var newOption = prompt('Your own color','');
      if (newOption) {
        this.options[this.options.length-1].text = newOption;
        this.options[this.options.length-1].value = newOption;
        this.options[this.options.length] = new Option('other','other');
      }
    }
  }
}

Fatal error: "No Target Architecture" in Visual Studio

Use #include <windows.h> instead of #include <windef.h>.

From the windows.h wikipedia page:

There are a number of child header files that are automatically included with windows.h. Many of these files cannot simply be included by themselves (they are not self-contained), because of dependencies.

windef.h is one of the files automatically included with windows.h.

Calling variable defined inside one function from another function

def oneFunction(lists):
    category=random.choice(list(lists.keys()))
    word=random.choice(lists[category])
    return word

def anotherFunction():
    for letter in word:             
        print("_",end=" ")

Ruby: Can I write multi-line string with no concatenation?

Yes, if you don't mind the extra newlines being inserted:

 conn.exec 'select attr1, attr2, attr3, attr4, attr5, attr6, attr7
            from table1, table2, table3, etc, etc, etc, etc, etc,
            where etc etc etc etc etc etc etc etc etc etc etc etc etc'

Alternatively you can use a heredoc:

conn.exec <<-eos
   select attr1, attr2, attr3, attr4, attr5, attr6, attr7
   from table1, table2, table3, etc, etc, etc, etc, etc,
   where etc etc etc etc etc etc etc etc etc etc etc etc etc
eos

How to pass parameters to ThreadStart method in Thread?

I would recommend you to have another class called File.

public class File
{
   private string filename;

   public File(string filename)
   {
      this.filename= filename;
   }

   public void download()
   {
       // download code using filename
   }
}

And in your thread creation code, you instantiate a new file:

string filename = "my_file_name";

myFile = new File(filename);

ThreadStart threadDelegate = new ThreadStart(myFile.download);

Thread newThread = new Thread(threadDelegate);

How to center canvas in html5

Add text-align: center; to the parent tag of <canvas>. That's it.

Example:

<div style="text-align: center">
    <canvas width="300" height="300">
        <!--your canvas code -->
    </canvas>
</div>

How do I specify "close existing connections" in sql script

Go to management studio and do everything you describe, only instead of clicking OK, click on Script. It will show the code it will run which you can then incorporate in your scripts.

In this case, you want:

ALTER DATABASE [MyDatabase] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

gitx How do I get my 'Detached HEAD' commits back into master

If checkout master was the last thing you did, then the reflog entry HEAD@{1} will contain your commits (otherwise use git reflog or git log -p to find them). Use git merge HEAD@{1} to fast forward them into master.

EDIT:

As noted in the comments, Git Ready has a great article on this.

git reflog and git reflog --all will give you the commit hashes of the mis-placed commits.

Git Ready: Reflog, Your Safety Net

Source: http://gitready.com/intermediate/2009/02/09/reflog-your-safety-net.html

Giving multiple conditions in for loop in Java

A basic for statement includes

  • 0..n initialization statements (ForInit)
  • 0..1 expression statements that evaluate to boolean or Boolean (ForStatement) and
  • 0..n update statements (ForUpdate)

If you need multiple conditions to build your ForStatement, then use the standard logic operators (&&, ||, |, ...) but - I suggest to use a private method if it gets to complicated:

for (int i = 0, j = 0; isMatrixElement(i,j,myArray); i++, j++) { 
   // ...
}

and

private boolean isMatrixElement(i,j,myArray) {
  return (i < myArray.length) && (j < myArray[i].length);  //  stupid dummy code!
}