Programs & Examples On #Swingbuilder

Jquery/Ajax call with timer

If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:

setTimeout ( expression, timeout );
setInterval ( expression, interval );

Where expression is a function and timeout and interval are integers in milliseconds. setTimeout runs the timer once and runs the expression once whereas setInterval will run the expression every time the interval passes.

So in your case it would work something like this:

setInterval(function() {
    //call $.ajax here
}, 5000); //5 seconds

As far as the Ajax goes, see jQuery's ajax() method. If you run an interval, there is nothing stopping you from calling the same ajax() from other places in your code.


If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:

setInterval() returns an integer which is the ID of the interval.

var id = setInterval(function() {
    //call $.ajax here
}, 30000); // 30 seconds

If you store that ID in a variable, you can then call clearInterval(id) which will stop the progression.

Then you can reinstantiate the setInterval() call after you've completed your ajax form submission.

How to search JSON tree with jQuery

I have kind of similar condition plus my Search Query not limited to particular Object property ( like "John" Search query should be matched with first_name and also with last_name property ). After spending some hours I got this function from Google's Angular project. They have taken care of every possible cases.

/* Seach in Object */

var comparator = function(obj, text) {
if (obj && text && typeof obj === 'object' && typeof text === 'object') {
    for (var objKey in obj) {
        if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) &&
                comparator(obj[objKey], text[objKey])) {
            return true;
        }
    }
    return false;
}
text = ('' + text).toLowerCase();
return ('' + obj).toLowerCase().indexOf(text) > -1;
};

var search = function(obj, text) {
if (typeof text == 'string' && text.charAt(0) === '!') {
    return !search(obj, text.substr(1));
}
switch (typeof obj) {
    case "boolean":
    case "number":
    case "string":
        return comparator(obj, text);
    case "object":
        switch (typeof text) {
            case "object":
                return comparator(obj, text);
            default:
                for (var objKey in obj) {
                    if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
                        return true;
                    }
                }
                break;
        }
        return false;
    case "array":
        for (var i = 0; i < obj.length; i++) {
            if (search(obj[i], text)) {
                return true;
            }
        }
        return false;
    default:
        return false;
}
};

Centering brand logo in Bootstrap Navbar

A solution where the logo is truly centered and the links are justified.

The max recommended number of links for the nav is 6, depending on the length of the words in eache link.

If you have 5 links, insert an empty link and style it with:

class="hidden-xs" style="visibility: hidden;"

in this way the number of links is always even.

_x000D_
_x000D_
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<style>_x000D_
  .navbar-nav > li {_x000D_
    float: none;_x000D_
    vertical-align: bottom;_x000D_
  }_x000D_
  #site-logo {_x000D_
    position: relative;_x000D_
    vertical-align: bottom;_x000D_
    bottom: -35px;_x000D_
  }_x000D_
  #site-logo a {_x000D_
    margin-top: -53px;_x000D_
  }_x000D_
</style>_x000D_
<nav class="navbar navbar-default navbar-fixed-top">_x000D_
  <div class="container">_x000D_
    <div class="navbar-header">_x000D_
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">_x000D_
        <span class="sr-only">Nav</span>_x000D_
        <span class="icon-bar"></span>_x000D_
        <span class="icon-bar"></span>_x000D_
        <span class="icon-bar"></span>_x000D_
      </button>_x000D_
    </div>_x000D_
    <div id="navbar" class="collapse navbar-collapse">_x000D_
      <ul class="nav nav-justified navbar-nav center-block">_x000D_
        <li class="active"><a href="#">First Link</a></li>_x000D_
        <li><a href="#">Second Link</a></li>_x000D_
        <li><a href="#">Third Link</a></li>_x000D_
        <li id="site-logo" class="hidden-xs"><a href="#"><img id="logo-navbar-middle" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/32877/logo-thing.png" width="200" alt="Logo Thing main logo"></a></li>_x000D_
        <li><a href="#">Fourth Link</a></li>_x000D_
        <li><a href="#">Fifth Link</a></li>_x000D_
        <li class="hidden-xs" style="visibility: hidden;"><a href="#">Sixth Link</a></li>_x000D_
      </ul>_x000D_
    </div>_x000D_
  </div>_x000D_
</nav>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>_x000D_
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
_x000D_
_x000D_
_x000D_

To see result click on run snippet and then full page

Fiddle

Configure hibernate to connect to database via JNDI Datasource

Apparently, you did it right. But here is a list of things you'll need with examples from a working application:

1) A context.xml file in META-INF, specifying your data source:

<Context>
    <Resource 
        name="jdbc/DsWebAppDB" 
        auth="Container" 
        type="javax.sql.DataSource" 
        username="sa" 
        password="" 
        driverClassName="org.h2.Driver" 
        url="jdbc:h2:mem:target/test/db/h2/hibernate" 
        maxActive="8" 
        maxIdle="4"/>
</Context>

2) web.xml which tells the container that you are using this resource:

<resource-env-ref>
    <resource-env-ref-name>jdbc/DsWebAppDB</resource-env-ref-name>
    <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>

3) Hibernate configuration which consumes the data source. In this case, it's a persistence.xml, but it's similar in hibernate.cfg.xml

<persistence-unit name="dswebapp">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
        <property name="hibernate.connection.datasource" value="java:comp/env/jdbc/DsWebAppDB"/>
    </properties>
</persistence-unit>

Why Is Subtracting These Two Times (in 1927) Giving A Strange Result?

You've encountered a local time discontinuity:

When local standard time was about to reach Sunday, 1. January 1928, 00:00:00 clocks were turned backward 0:05:52 hours to Saturday, 31. December 1927, 23:54:08 local standard time instead

This is not particularly strange and has happened pretty much everywhere at one time or another as timezones were switched or changed due to political or administrative actions.

docker entrypoint running bash script gets "permission denied"

This is a bit stupid maybe but the error message I got was Permission denied and it sent me spiralling down in a very wrong direction to attempt to solve it. (Here for example)

I haven't even added any bash script myself, I think one is added by nodejs image which I use.

FROM node:14.9.0

I was wrongly running to expose/connect the port on my local:

docker run -p 80:80 [name] . # this is wrong!

which gives

/usr/local/bin/docker-entrypoint.sh: 8: exec: .: Permission denied

But you shouldn't even have a dot in the end, it was added to documentation of another projects docker image by misstake. You should simply run:

docker run -p 80:80 [name]

I like Docker a lot but it's sad it has so many gotchas like this and not always very clear error messages...

How to create a GUID/UUID in Python

This function is fully configurable and generates unique uid based on the format specified

eg:- [8, 4, 4, 4, 12] , this is the format mentioned and it will generate the following uuid

LxoYNyXe-7hbQ-caJt-DSdU-PDAht56cMEWi

 import random as r

 def generate_uuid():
        random_string = ''
        random_str_seq = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        uuid_format = [8, 4, 4, 4, 12]
        for n in uuid_format:
            for i in range(0,n):
                random_string += str(random_str_seq[r.randint(0, len(random_str_seq) - 1)])
            if n != 12:
                random_string += '-'
        return random_string

How can I delete using INNER JOIN with SQL Server?

You need to specify what table you are deleting from. Here is a version with an alias:

DELETE w
FROM WorkRecord2 w
INNER JOIN Employee e
  ON EmployeeRun=EmployeeNo
WHERE Company = '1' AND Date = '2013-05-06'

Can we make unsigned byte in Java

Yes and no. Ive been digging around with this problem. Like i understand this:

The fact is that java has signed interger -128 to 127.. It is possible to present a unsigned in java with:

public static int toUnsignedInt(byte x) {
    return ((int) x) & 0xff;
}

If you for example add -12 signed number to be unsigned you get 244. But you can use that number again in signed, it has to be shifted back to signed and it´ll be again -12.

If you try to add 244 to java byte you'll get outOfIndexException.

Cheers..

var self = this?

I haven't used jQuery, but in a library like Prototype you can bind functions to a specific scope. So with that in mind your code would look like this:

 $('#foobar').ready('click', this.doSomething.bind(this));

The bind method returns a new function that calls the original method with the scope you have specified.

React JS Error: is not defined react/jsx-no-undef

its very similar with nodejs

var User= require('./Users');

in this case its React:

import User from './User'

right now you can use

return (
      <Users></Users>
    )

Authenticating against Active Directory with Java on Linux

I just finished a project that uses AD and Java. We used Spring ldapTemplate.

AD is LDAP compliant (almost), I don't think you will have any issues with the task you have. I mean the fact that it is AD or any other LDAP server it doesn't matter if you want just to connect.

I would take a look at: Spring LDAP

They have examples too.

As for encryption, we used SSL connection (so it was LDAPS). AD had to be configured on a SSL port/protocol.

But first of all, make sure you can properly connect to your AD via an LDAP IDE. I use Apache Directory Studio, it is really cool, and it is written in Java. That is all I needed. For testing purposes you could also install Apache Directory Server

How to write a file or data to an S3 object using boto3

it is worth mentioning smart-open that uses boto3 as a back-end.

smart-open is a drop-in replacement for python's open that can open files from s3, as well as ftp, http and many other protocols.

for example

from smart_open import open
import json
with open("s3://your_bucket/your_key.json", 'r') as f:
    data = json.load(f)

The aws credentials are loaded via boto3 credentials, usually a file in the ~/.aws/ dir or an environment variable.

Java String split removed empty values

you may have multiple separators, including whitespace characters, commas, semicolons, etc. take those in repeatable group with []+, like:

 String[] tokens = "a , b,  ,c; ;d,      ".split( "[,; \t\n\r]+" );

you'll have 4 tokens -- a, b, c, d

leading separators in the source string need to be removed before applying this split.

as answer to question asked:

String data = "5|6|7||8|9||";
String[] split = data.split("[\\| \t\n\r]+");

whitespaces added just in case if you'll have those as separators along with |

Load vs. Stress testing

Load Testing: Large amount of users Stress Testing: Too many users, too much data, too little time and too little room

Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

From what I've found online, this is a bug introduced in JDK 1.7.0_45. It appears to also be present in JDK 1.7.0_60. A bug report on Oracle's website states that, while there was a fix, it was removed before the JDK was released. I do not know why the fix was removed, but it confirms what we've already suspected -- the JDK is still broken.

The bug report claims that the error is benign and should not cause any run-time problems, though one of the comments disagrees with that. In my own experience, I have been able to work without any problems using JDK 1.7.0_60 despite seeing the message.

If this issue is causing serious problems, here are a few things I would suggest:

  • Revert back to JDK 1.7.0_25 until a fix is added to the JDK.

  • Keep an eye on the bug report so that you are aware of any work being done on this issue. Maybe even add your own comment so Oracle is aware of the severity of the issue.

  • Try the JDK early releases as they come out. One of them might fix your problem.

Instructions for installing the JDK on Mac OS X are available at JDK 7 Installation for Mac OS X. It also contains instructions for removing the JDK.

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

if ngModule is not working in input means try...remove double quotes around ngModule

like

<input #form="ngModel" [(ngModel)]......></input>

instead of above

<input #form=ngModel [(ngModel)]......></input> try this

In CSS what is the difference between "." and "#" when declaring a set of styles?

Yes, they are different...

# is an id selector, used to target a single specific element with a unique id, but . is a class selector used to target multiple elements with a particular class. To put it another way:

  • #foo {} will style the single element declared with an attribute id="foo"
  • .foo {} will style all elements with an attribute class="foo" (you can have multiple classes assigned to an element too, just separate them with spaces, e.g. class="foo bar")

Typical uses

Generally speaking, you use # for styling something you know is only going to appear once, for example, things like high level layout divs such sidebars, banner areas etc.

Classes are used where the style is repeated, e.g. say you head a special form of header for error messages, you could create a style h1.error {} which would only apply to <h1 class="error">

Specificity

Another aspect where selectors differ is in their specificity - an id selector is deemed to be more specific than class selector. This means that where styles conflict on an element, the ones defined with the more specific selector will override less specific selectors. For example, given <div id="sidebar" class="box"> any rules for #sidebar with override conflicting rules for .box

Learn more about CSS selectors

See Selectutorial for more great primers on CSS selectors - they are incredibly powerful, and if your conception is simply that "# is used for DIVs" you'd do well to read up on exactly how to use CSS more effectively.

EDIT: Looks like Selectutorial might have gone to the big website in the sky, so try this archive link instead.

Linear regression with matplotlib / numpy

import numpy as np
import matplotlib.pyplot as plt 
from scipy import stats

x = np.array([1.5,2,2.5,3,3.5,4,4.5,5,5.5,6])
y = np.array([10.35,12.3,13,14.0,16,17,18.2,20,20.7,22.5])
gradient, intercept, r_value, p_value, std_err = stats.linregress(x,y)
mn=np.min(x)
mx=np.max(x)
x1=np.linspace(mn,mx,500)
y1=gradient*x1+intercept
plt.plot(x,y,'ob')
plt.plot(x1,y1,'-r')
plt.show()

USe this ..

iOS: present view controller programmatically

LandingScreenViewController *nextView=[self.storyboard instantiateViewControllerWithIdentifier:@"nextView"];
[self presentViewController:nextView animated:YES completion:^{}];

git replacing LF with CRLF

git config core.autocrlf false

Opening port 80 EC2 Amazon web services

  1. Check what security group you are using for your instance. See value of Security Groups column in row of your instance. It's important - I changed rules for default group, but my instance was under quickstart-1 group when I had similar issue.
  2. Go to Security Groups tab, go to Inbound tab, select HTTP in Create a new rule combo-box, leave 0.0.0.0/0 in source field and click Add Rule, then Apply rule changes.

Handling back button in Android Navigation Component

The recommended approach is to add an OnBackPressedCallback to the activity's OnBackPressedDispatcher.

requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) { 
    // handle back event
}

why windows 7 task scheduler task fails with error 2147942667

For me it was the "Start In" - I accidentally left in the '.py' at the end of the name of my program. And I forgot to capitalize the name of the folder it was in ('Apps').

ERROR 1396 (HY000): Operation CREATE USER failed for 'jack'@'localhost'

I know this is old, but since it is the first result in Google I figured I should add my solution. In my case dropping the user worked fine, but recreating the user gave me a "ERROR 2013 (HY000): Lost connection to MySQL server during query" and "ERROR 2006 (HY000): MySQL server has gone away." I tried the flush privileges -> drop user solution, but still had the same error.

In my case the error was due to a mysql upgrade from 5.1 -> 5.6. Viewing the error logs, I noticed that it said to run mysql_upgrade. Did that and my create user statement worked fine!

Centering in CSS Grid

The CSS place-items shorthand property sets the align-items and justify-items properties, respectively. If the second value is not set, the first value is also used for it.

.parent {
  display: grid;
  place-items: center;
}

Oracle TNS names not showing when adding new connection to SQL Developer

In SQLDeveloper browse Tools --> Preferences, as shown in below image.

enter image description here

In the Preferences options expand Database --> select Advanced --> under "Tnsnames Directory" --> Browse the directory where tnsnames.ora present.
Then click on Ok.
as shown in below diagram.

enter image description here

You have Done!

Now you can connect via the TNSnames options.

Validating with an XML schema in Python

You can easily validate an XML file or tree against an XML Schema (XSD) with the xmlschema Python package. It's pure Python, available on PyPi and doesn't have many dependencies.

Example - validate a file:

import xmlschema
xmlschema.validate('doc.xml', 'some.xsd')

The method raises an exception if the file doesn't validate against the XSD. That exception then contains some violation details.

If you want to validate many files you only have to load the XSD once:

xsd = xmlschema.XMLSchema('some.xsd')
for filename in filenames:
    xsd.validate(filename)

If you don't need the exception you can validate like this:

if xsd.is_valid('doc.xml'):
    print('do something useful')

Alternatively, xmlschema directly works on file objects and in memory XML trees (either created with xml.etree.ElementTree or lxml). Example:

import xml.etree.ElementTree as ET
t = ET.parse('doc.xml')
result = xsd.is_valid(t)
print('Document is valid? {}'.format(result))

Singular matrix issue with Numpy

The matrix you pasted

[[   1,    8,   50],
 [   8,   64,  400],
 [  50,  400, 2500]]

Has a determinant of zero. This is the definition of a Singular matrix (one for which an inverse does not exist)

http://en.wikipedia.org/wiki/Invertible_matrix

how to run a command at terminal from java program?

You don't actually need to run a command from an xterm session, you can run it directly:

String[] arguments = new String[] {"/path/to/executable", "arg0", "arg1", "etc"};
Process proc = new ProcessBuilder(arguments).start();

If the process responds interactively to the input stream, and you want to inject values, then do what you did before:

OutputStream out = proc.getOutputStream();  
out.write("command\n");  
out.flush();

Don't forget the '\n' at the end though as most apps will use it to identify the end of a single command's input.

Add a prefix string to beginning of each line

Using ed:

ed infile <<'EOE'
,s/^/prefix/
wq
EOE

This substitutes, for each line (,), the beginning of the line (^) with prefix. wq saves and exits.

If the replacement string contains a slash, we can use a different delimiter for s instead:

ed infile <<'EOE'
,s#^#/opt/workdir/#
wq
EOE

I've quoted the here-doc delimiter EOE ("end of ed") to prevent parameter expansion. In this example, it would work unquoted as well, but it's good practice to prevent surprises if you ever have a $ in your ed script.

How do you append to a file?

You probably want to pass "a" as the mode argument. See the docs for open().

with open("foo", "a") as f:
    f.write("cool beans...")

There are other permutations of the mode argument for updating (+), truncating (w) and binary (b) mode but starting with just "a" is your best bet.

getting a checkbox array value from POST

I just used the following code:

<form method="post">
    <input id="user1" value="user1"  name="invite[]" type="checkbox">
    <input id="user2" value="user2"  name="invite[]" type="checkbox">
    <input type="submit">
</form>

<?php
    if(isset($_POST['invite'])){
        $invite = $_POST['invite'];
        print_r($invite);
    }
?>

When I checked both boxes, the output was:

Array ( [0] => user1 [1] => user2 )

I know this doesn't directly answer your question, but it gives you a working example to reference and hopefully helps you solve the problem.

Download single files from GitHub

For users with GitHub Enterprise you need to construct URL in following scheme

Invoke-WebRequest http://github.mycompany.com/api/v3/repos/my-org/my-repo/contents/myfiles/file.txt -Headers @{"Authorization"="token 8d795936d2c1b2806587719b9b6456bd16549ad8"}

Details can be found here

http://artisticcheese.blogspot.com/2017/04/how-to-download-individual-files-from.html

How can I make XSLT work in chrome?

I had the same problem on localhost. Running around the Internet looking for the answer and I approve that adding --allow-file-access-from-files works. I work on Mac, so for me I had to go through terminal sudo /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-file-access-from-files and enter your password (if you have one).

Another small thing - nothing will work unless you add to your .xml file the reference to your .xsl file as follows <?xml-stylesheet type="text/xsl" href="<path to file>"?>. Another small thing I didn't realise immediately - you should be opening your .xml file in browser, no the .xsl.

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

For two Entity Classes Customer and Order , hibernate will create two tables.

Possible Cases:

  1. mappedBy is not used in Customer.java and Order.java Class then->

    At customer side a new table will be created[name = CUSTOMER_ORDER] which will keep mapping of CUSTOMER_ID and ORDER_ID. These are primary keys of Customer and Order Tables. At Order side an additional column is required to save the corresponding Customer_ID record mapping.

  2. mappedBy is used in Customer.java [As given in problem statement] Now additional table[CUSTOMER_ORDER] is not created. Only one column in Order Table

  3. mappedby is used in Order.java Now additional table will be created by hibernate.[name = CUSTOMER_ORDER] Order Table will not have additional column [Customer_ID ] for mapping.

Any Side can be made Owner of the relationship. But its better to choose xxxToOne side.

Coding effect - > Only Owning side of entity can change relationship status. In below example BoyFriend class is owner of the relationship. even if Girlfriend wants to break-up , she can't.

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name = "BoyFriend21")
public class BoyFriend21 {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Boy_ID")
    @SequenceGenerator(name = "Boy_ID", sequenceName = "Boy_ID_SEQUENCER", initialValue = 10,allocationSize = 1)
    private Integer id;

    @Column(name = "BOY_NAME")
    private String name;

    @OneToOne(cascade = { CascadeType.ALL })
    private GirlFriend21 girlFriend;

    public BoyFriend21(String name) {
        this.name = name;
    }

    public BoyFriend21() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public BoyFriend21(String name, GirlFriend21 girlFriend) {
        this.name = name;
        this.girlFriend = girlFriend;
    }

    public GirlFriend21 getGirlFriend() {
        return girlFriend;
    }

    public void setGirlFriend(GirlFriend21 girlFriend) {
        this.girlFriend = girlFriend;
    }
}

import org.hibernate.annotations.*;
import javax.persistence.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.ArrayList;
import java.util.List;

@Entity 
@Table(name = "GirlFriend21")
public class GirlFriend21 {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Girl_ID")
    @SequenceGenerator(name = "Girl_ID", sequenceName = "Girl_ID_SEQUENCER", initialValue = 10,allocationSize = 1)
    private Integer id;

    @Column(name = "GIRL_NAME")
    private String name;

    @OneToOne(cascade = {CascadeType.ALL},mappedBy = "girlFriend")
    private BoyFriend21 boyFriends = new BoyFriend21();

    public GirlFriend21() {
    }

    public GirlFriend21(String name) {
        this.name = name;
    }


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public GirlFriend21(String name, BoyFriend21 boyFriends) {
        this.name = name;
        this.boyFriends = boyFriends;
    }

    public BoyFriend21 getBoyFriends() {
        return boyFriends;
    }

    public void setBoyFriends(BoyFriend21 boyFriends) {
        this.boyFriends = boyFriends;
    }
}


import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.util.Arrays;

public class Main578_DS {

    public static void main(String[] args) {
        final Configuration configuration = new Configuration();
         try {
             configuration.configure("hibernate.cfg.xml");
         } catch (HibernateException e) {
             throw new RuntimeException(e);
         }
        final SessionFactory sessionFactory = configuration.buildSessionFactory();
        final Session session = sessionFactory.openSession();
        session.beginTransaction();

        final BoyFriend21 clinton = new BoyFriend21("Bill Clinton");
        final GirlFriend21 monica = new GirlFriend21("monica lewinsky");

        clinton.setGirlFriend(monica);
        session.save(clinton);

        session.getTransaction().commit();
        session.close();
    }
}

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.util.List;

public class Main578_Modify {

    public static void main(String[] args) {
        final Configuration configuration = new Configuration();
        try {
            configuration.configure("hibernate.cfg.xml");
        } catch (HibernateException e) {
            throw new RuntimeException(e);
        }
        final SessionFactory sessionFactory = configuration.buildSessionFactory();
        final Session session1 = sessionFactory.openSession();
        session1.beginTransaction();

        GirlFriend21 monica = (GirlFriend21)session1.load(GirlFriend21.class,10);  // Monica lewinsky record has id  10.
        BoyFriend21 boyfriend = monica.getBoyFriends();
        System.out.println(boyfriend.getName()); // It will print  Clinton Name
        monica.setBoyFriends(null); // It will not impact relationship

        session1.getTransaction().commit();
        session1.close();

        final Session session2 = sessionFactory.openSession();
        session2.beginTransaction();

        BoyFriend21 clinton = (BoyFriend21)session2.load(BoyFriend21.class,10);  // Bill clinton record

        GirlFriend21 girlfriend = clinton.getGirlFriend();
        System.out.println(girlfriend.getName()); // It will print Monica name.
        //But if Clinton[Who owns the relationship as per "mappedby" rule can break this]
        clinton.setGirlFriend(null);
        // Now if Monica tries to check BoyFriend Details, she will find Clinton is no more her boyFriend
        session2.getTransaction().commit();
        session2.close();

        final Session session3 = sessionFactory.openSession();
        session1.beginTransaction();

        monica = (GirlFriend21)session3.load(GirlFriend21.class,10);  // Monica lewinsky record has id  10.
        boyfriend = monica.getBoyFriends();

        System.out.println(boyfriend.getName()); // Does not print Clinton Name

        session3.getTransaction().commit();
        session3.close();
    }
}

Plot 3D data in R

If you're working with "real" data for which the grid intervals and sequence cannot be guaranteed to be increasing or unique (hopefully the (x,y,z) combinations are unique at least, even if these triples are duplicated), I would recommend the akima package for interpolating from an irregular grid to a regular one.

Using your definition of data:

library(akima)
im <- with(data,interp(x,y,z))
with(im,image(x,y,z))

enter image description here

And this should work not only with image but similar functions as well.

Note that the default grid to which your data is mapped to by akima::interp is defined by 40 equal intervals spanning the range of x and y values:

> formals(akima::interp)[c("xo","yo")]
$xo
seq(min(x), max(x), length = 40)

$yo
seq(min(y), max(y), length = 40)

But of course, this can be overridden by passing arguments xo and yo to akima::interp.

Merge PDF files with PHP

I have tried similar issue and works fine, try it. It can handle different orientations between PDFs.

    // array to hold list of PDF files to be merged
    $files = array("a.pdf", "b.pdf", "c.pdf");
    $pageCount = 0;
    // initiate FPDI
    $pdf = new FPDI();

    // iterate through the files
    foreach ($files AS $file) {
        // get the page count
        $pageCount = $pdf->setSourceFile($file);
        // iterate through all pages
        for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
            // import a page
            $templateId = $pdf->importPage($pageNo);
            // get the size of the imported page
            $size = $pdf->getTemplateSize($templateId);

            // create a page (landscape or portrait depending on the imported page size)
            if ($size['w'] > $size['h']) {
                $pdf->AddPage('L', array($size['w'], $size['h']));
            } else {
                $pdf->AddPage('P', array($size['w'], $size['h']));
            }

            // use the imported page
            $pdf->useTemplate($templateId);

            $pdf->SetFont('Helvetica');
            $pdf->SetXY(5, 5);
            $pdf->Write(8, 'Generated by FPDI');
        }
    }

Get the index of a certain value in an array in PHP

This code should do the same as your new routine, working with the correct multi-dimensional array..

 $arr = array(
  'string1' => array('a' => '', 'b' => '', 'c' => ''),
  'string2' => array('a' => '', 'b' => '', 'c' => ''),
  'string3' => array('a' => '', 'b' => '', 'c' => '')
 );

 echo 'Index of "string2" = '. array_search('string2', array_keys($arr));

How to receive serial data using android bluetooth

try this code :

Activity:

package Android.Arduino.Bluetooth;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;  
import android.widget.Button;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends Activity
{
TextView myLabel;
EditText myTextbox;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button openButton = (Button)findViewById(R.id.open);
    Button sendButton = (Button)findViewById(R.id.send);
    Button closeButton = (Button)findViewById(R.id.close);
    myLabel = (TextView)findViewById(R.id.label);
    myTextbox = (EditText)findViewById(R.id.entry);

    //Open Button
    openButton.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            try 
            {
                findBT();
                openBT();
            }
            catch (IOException ex) { }
        }
    });

    //Send Button
    sendButton.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            try 
            {
                sendData();
            }
            catch (IOException ex) { }
        }
    });

    //Close button
    closeButton.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            try 
            {
                closeBT();
            }
            catch (IOException ex) { }
        }
    });
}

void findBT()
{
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if(mBluetoothAdapter == null)
    {
        myLabel.setText("No bluetooth adapter available");
    }

    if(!mBluetoothAdapter.isEnabled())
    {
        Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBluetooth, 0);
    }

    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    if(pairedDevices.size() > 0)
    {
        for(BluetoothDevice device : pairedDevices)
        {
            if(device.getName().equals("MattsBlueTooth")) 
            {
                mmDevice = device;
                break;
            }
        }
    }
    myLabel.setText("Bluetooth Device Found");
}

void openBT() throws IOException
{
    UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID
    mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);        
    mmSocket.connect();
    mmOutputStream = mmSocket.getOutputStream();
    mmInputStream = mmSocket.getInputStream();

    beginListenForData();

    myLabel.setText("Bluetooth Opened");
}

void beginListenForData()
{
    final Handler handler = new Handler(); 
    final byte delimiter = 10; //This is the ASCII code for a newline character

    stopWorker = false;
    readBufferPosition = 0;
    readBuffer = new byte[1024];
    workerThread = new Thread(new Runnable()
    {
        public void run()
        {                
           while(!Thread.currentThread().isInterrupted() && !stopWorker)
           {
                try 
                {
                    int bytesAvailable = mmInputStream.available();                        
                    if(bytesAvailable > 0)
                    {
                        byte[] packetBytes = new byte[bytesAvailable];
                        mmInputStream.read(packetBytes);
                        for(int i=0;i<bytesAvailable;i++)
                        {
                            byte b = packetBytes[i];
                            if(b == delimiter)
                            {
     byte[] encodedBytes = new byte[readBufferPosition];
     System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
     final String data = new String(encodedBytes, "US-ASCII");
     readBufferPosition = 0;

                                handler.post(new Runnable()
                                {
                                    public void run()
                                    {
                                        myLabel.setText(data);
                                    }
                                });
                            }
                            else
                            {
                                readBuffer[readBufferPosition++] = b;
                            }
                        }
                    }
                } 
                catch (IOException ex) 
                {
                    stopWorker = true;
                }
           }
        }
    });

    workerThread.start();
}

void sendData() throws IOException
{
    String msg = myTextbox.getText().toString();
    msg += "\n";
    mmOutputStream.write(msg.getBytes());
    myLabel.setText("Data Sent");
}

void closeBT() throws IOException
{
    stopWorker = true;
    mmOutputStream.close();
    mmInputStream.close();
    mmSocket.close();
    myLabel.setText("Bluetooth Closed");
}
}

AND Here the layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:ignore="TextFields,HardcodedText" >

<TextView
    android:id="@+id/label"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Type here:" />

<EditText
    android:id="@+id/entry"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/label"
    android:background="@android:drawable/editbox_background" />

<Button
    android:id="@+id/open"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_below="@id/entry"
    android:layout_marginLeft="10dip"
    android:text="Open" />

<Button
    android:id="@+id/send"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@id/open"
    android:layout_toLeftOf="@id/open"
    android:text="Send" />

<Button
    android:id="@+id/close"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@id/send"
    android:layout_toLeftOf="@id/send"
    android:text="Close" />

</RelativeLayout>

Here for Manifest: add to Application

// permission must be enabled complete
<manifest ....>

    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <application>


    </application>
</manifest>

What are C++ functors and their uses?

A Functor is a object which acts like a function. Basically, a class which defines operator().

class MyFunctor
{
   public:
     int operator()(int x) { return x * 2;}
}

MyFunctor doubler;
int x = doubler(5);

The real advantage is that a functor can hold state.

class Matcher
{
   int target;
   public:
     Matcher(int m) : target(m) {}
     bool operator()(int x) { return x == target;}
}

Matcher Is5(5);

if (Is5(n))    // same as if (n == 5)
{ ....}

Does java.util.List.isEmpty() check if the list itself is null?

No java.util.List.isEmpty() doesn't check if a list is null.

If you are using Spring framework you can use the CollectionUtils class to check if a list is empty or not. It also takes care of the null references. Following is the code snippet from Spring framework's CollectionUtils class.

public static boolean isEmpty(Collection<?> collection) {
    return (collection == null || collection.isEmpty());
}

Even if you are not using Spring, you can go on and tweak this code to add in your AppUtil class.

What do I use on linux to make a python program executable

Putting these lines at the starting of the code will tell your operating systems to look up the binary program needed for the execution of the python script i.e it is the python interpreter.

So it depends on your operating system where it keeps the python interpreter. As I have Ubuntu as operating system it keeps the python interpreter in /usr/bin/python so I have to write this line at the starting of my python script;

#!/usr/bin/python

After completing and saving your code

  1. Start your command terminal

  2. Make sure the script lies in your present working directory

  3. Type chmod +x script_name.py

  4. Now you can start the script by clicking the script. An alert box will appear; press "Run" or "Run in Terminal" in the alert box; or, at the terminal prompt, type ./script_name.py

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Cascade will work when you delete something on table Courses. Any record on table BookCourses that has reference to table Courses will be deleted automatically.

But when you try to delete on table BookCourses only the table itself is affected and not on the Courses

follow-up question: why do you have CourseID on table Category?

Maybe you should restructure your schema into this,

CREATE TABLE Categories 
(
  Code CHAR(4) NOT NULL PRIMARY KEY,
  CategoryName VARCHAR(63) NOT NULL UNIQUE
);

CREATE TABLE Courses 
(
  CourseID INT NOT NULL PRIMARY KEY,
  BookID INT NOT NULL,
  CatCode CHAR(4) NOT NULL,
  CourseNum CHAR(3) NOT NULL,
  CourseSec CHAR(1) NOT NULL,
);

ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;

Unable to Connect to GitHub.com For Cloning

I had the same error because I was using proxy. As the answer is given but in case you are using proxy then please set your proxy first using these commands:

git config --global http.proxy http://proxy_username:proxy_password@proxy_ip:port
git config --global https.proxy https://proxy_username:proxy_password@proxy_ip:port

Why aren't Xcode breakpoints functioning?

For Xcode 4:

go Product -> Debug ->  Activate Breakpoints

git pull while not in a git directory

You can write a script like this:

cd /X/Y
git pull

You can name it something like gitpull.
If you'd rather have it do arbitrary directories instead of /X/Y:

cd $1
git pull

Then you can call it with gitpull /X/Z
Lastly, you can try finding repositories. I have a ~/git folder which contains repositories, and you can use this to do a pull on all of them.

g=`find /X -name .git`
for repo in ${g[@]}
do
    cd ${repo}
    cd ..
    git pull
done

Can I call a base class's virtual function if I'm overriding it?

Yes you can call it. C++ syntax for calling parent class function in child class is

class child: public parent {
  // ...

  void methodName() {
    parent::methodName(); // calls Parent class' function
  }
};

Read more about function overriding.

'int' object has no attribute '__getitem__'

Some of the problems:

for i in range[6]:
            for j in range[6]:

should be:

range(6)

Convert byte slice to io.Reader

r := strings(byteData)

This also works to turn []byte into io.Reader

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

What is the purpose of class methods?

It allows you to write generic class methods that you can use with any compatible class.

For example:

@classmethod
def get_name(cls):
    print cls.name

class C:
    name = "tester"

C.get_name = get_name

#call it:
C.get_name()

If you don't use @classmethod you can do it with self keyword but it needs an instance of Class:

def get_name(self):
    print self.name

class C:
    name = "tester"

C.get_name = get_name

#call it:
C().get_name() #<-note the its an instance of class C

How to extract hours and minutes from a datetime.datetime object?

datetime has fields hour and minute. So to get the hours and minutes, you would use t1.hour and t1.minute.

However, when you subtract two datetimes, the result is a timedelta, which only has the days and seconds fields. So you'll need to divide and multiply as necessary to get the numbers you need.

Batch Script to Run as Administrator

its possible using syntax:

RUNAS [/profile] [/env] [/netonly] /user:user Program

Key :
/profile Option to load the user's profile (registry)
/env Use current environment instead of user's.
/netonly Use the credentials specified only for remote connections.
/user Username in form USER@DOMAIN or DOMAIN\USER
(USER@DOMAIN is not compatible with /netonly)
Program The command to execute

example :

runas /env /user:domain\Administrator <program.exe/command you want to execute>

hasNext in Python iterators?

If you really need a has-next functionality (because you're just faithfully transcribing an algorithm from a reference implementation in Java, say, or because you're writing a prototype that will need to be easily transcribed to Java when it's finished), it's easy to obtain it with a little wrapper class. For example:

class hn_wrapper(object):
  def __init__(self, it):
    self.it = iter(it)
    self._hasnext = None
  def __iter__(self): return self
  def next(self):
    if self._hasnext:
      result = self._thenext
    else:
      result = next(self.it)
    self._hasnext = None
    return result
  def hasnext(self):
    if self._hasnext is None:
      try: self._thenext = next(self.it)
      except StopIteration: self._hasnext = False
      else: self._hasnext = True
    return self._hasnext

now something like

x = hn_wrapper('ciao')
while x.hasnext(): print next(x)

emits

c
i
a
o

as required.

Note that the use of next(sel.it) as a built-in requires Python 2.6 or better; if you're using an older version of Python, use self.it.next() instead (and similarly for next(x) in the example usage). [[You might reasonably think this note is redundant, since Python 2.6 has been around for over a year now -- but more often than not when I use Python 2.6 features in a response, some commenter or other feels duty-bound to point out that they are 2.6 features, thus I'm trying to forestall such comments for once;-)]]

The term "Add-Migration" is not recognized

This is what worked for me: From Visual Studio click on

Tools --> NuGet Package Manager --> Package Manager Console

enter image description here

Then you can run Add-Migration, for example:

Add-Migration InitialCreate

How to set default values in Rails?

First of all you can't overload initialize(*args) as it's not called in all cases.

Your best option is to put your defaults into your migration:

add_column :accounts, :max_users, :integer, :default => 10

Second best is to place defaults into your model but this will only work with attributes that are initially nil. You may have trouble as I did with boolean columns:

def after_initialize
  if new_record?
    max_users ||= 10
  end
end

You need the new_record? so the defaults don't override values loaded from the datbase.

You need ||= to stop Rails from overriding parameters passed into the initialize method.

How to convert JSON to XML or XML to JSON?

Try this function. I just wrote it and haven't had much of a chance to test it, but my preliminary tests are promising.

public static XmlDocument JsonToXml(string json)
{
    XmlNode newNode = null;
    XmlNode appendToNode = null;
    XmlDocument returnXmlDoc = new XmlDocument();
    returnXmlDoc.LoadXml("<Document />");
    XmlNode rootNode = returnXmlDoc.SelectSingleNode("Document");
    appendToNode = rootNode;

    string[] arrElementData;
    string[] arrElements = json.Split('\r');
    foreach (string element in arrElements)
    {
        string processElement = element.Replace("\r", "").Replace("\n", "").Replace("\t", "").Trim();
        if ((processElement.IndexOf("}") > -1 || processElement.IndexOf("]") > -1) && appendToNode != rootNode)
        {
            appendToNode = appendToNode.ParentNode;
        }
        else if (processElement.IndexOf("[") > -1)
        {
            processElement = processElement.Replace(":", "").Replace("[", "").Replace("\"", "").Trim();
            newNode = returnXmlDoc.CreateElement(processElement);
            appendToNode.AppendChild(newNode);
            appendToNode = newNode;
        }
        else if (processElement.IndexOf("{") > -1 && processElement.IndexOf(":") > -1)
        {
            processElement = processElement.Replace(":", "").Replace("{", "").Replace("\"", "").Trim();
            newNode = returnXmlDoc.CreateElement(processElement);
            appendToNode.AppendChild(newNode);
            appendToNode = newNode;
        }
        else
        {
            if (processElement.IndexOf(":") > -1)
            {
                arrElementData = processElement.Replace(": \"", ":").Replace("\",", "").Replace("\"", "").Split(':');
                newNode = returnXmlDoc.CreateElement(arrElementData[0]);
                for (int i = 1; i < arrElementData.Length; i++)
                {
                    newNode.InnerText += arrElementData[i];
                }

                appendToNode.AppendChild(newNode);
            }
        }
    }

    return returnXmlDoc;
}

How do I protect Python code?

The reliable only way to protect code is to run it on a server you control and provide your clients with a client which interfaces with that server.

Why Local Users and Groups is missing in Computer Management on Windows 10 Home?

Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.

You can use User Accounts by pressing Window+R, typing netplwiz and pressing OK as described here.

How to set up ES cluster?

its super easy.

You'll need each machine to have it's own copy of ElasticSearch (simply copy the one you have now) -- the reason is that each machine / node whatever is going to keep it's own files that are sharded accross the cluster.

The only thing you really need to do is edit the config file to include the name of the cluster.

If all machines have the same cluster name elasticsearch will do the rest automatically (as long as the machines are all on the same network)

Read here to get you started: https://www.elastic.co/guide/en/elasticsearch/guide/current/deploy.html

When you create indexes (where the data goes) you define at that time how many replicas you want (they'll be distributed around the cluster)

How to set default value for column of new created table from select statement in 11g

You will need to alter table abc modify (salary default 0);

How to empty a Heroku database

To drop the database, if you are using SHARED_DATABASE_URL:

$ heroku pg:reset DATABASE_URL

Now to recreate the database with nothing in it:

$ heroku run rake db:migrate  

To populate the database with your seed data:

$ heroku run rake db:seed

---OR---

You can combine the last two (migrate & seed) into one action by executing this:

$ heroku run rake db:setup

Edit 2014-04-18: rake db:setup doesn't work with Rails 4, it fails with a Couldn't create database error.

Edit 2014-10-09: You can use rake db:setup with Rails 4. It does give you a Couldn't create database error (because the database was already created using the heroku pg:reset command). But it also loads your database schema and your seeds after the error message.

You can do this with pretty much any rake command, but there are exceptions. For example, db:reset doesn't work via heroku run rake. You have to use pg:reset instead.

More information can be found in Heroku's documentation:

Running Rake Commands

Reset Postgres DB

How to present UIActionSheet iOS Swift?

swift4 (tested)

let alertController = UIAlertController(title: "Select Photo", message: "Select atleast one photo", preferredStyle: .actionSheet)
    let action1 = UIAlertAction(title: "From Photo", style: .default) { (action) in
        print("Default is pressed.....")
    }
    let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
        print("Cancel is pressed......")
    }
    let action3 = UIAlertAction(title: "Click new", style: .default) { (action) in
        print("Destructive is pressed....")

    }
    alertController.addAction(action1)
    alertController.addAction(action2)
    alertController.addAction(action3)
    self.present(alertController, animated: true, completion: nil)

}

How to remove commits from a pull request

You have several techniques to do it.

This post - read the part about the revert will explain in details what we want to do and how to do it.

Here is the most simple solution to your problem:

# Checkout the desired branch
git checkout <branch>

# Undo the desired commit
git revert <commit>

# Update the remote with the undo of the code
git push origin <branch>

The revert command will create a new commit with the undo of the original commit.

PHP - Check if two arrays are equal

Another method for checking equality regardless of value order works by using http://php.net/manual/en/function.array-intersect.php, like so:

$array1 = array(2,5,3);
$array2 = array(5,2,3);
if($array1 === array_intersect($array1, $array2) && $array2 === array_intersect($array2, $array1)) {
    echo 'Equal';
} else {
    echo 'Not equal';
}

Here's a version that works also with multidimensional arrays using http://php.net/manual/en/function.array-uintersect.php:

$array1 = array(
    array(5, 2),
    array(3, 6),
    array(2, 9, 4)
);
$array2 = array(
    array(3, 6),
    array(2, 9, 4),
    array(5, 2)
);

if($array1 === array_uintersect($array1, $array2, 'compare') && $array2 === array_uintersect($array2, $array1, 'compare')) {
    echo 'Equal';
} else {
    echo 'Not equal';
}

function compare($v1, $v2) {
    if ($v1===$v2) {
        return 0;
    }
    if ($v1 > $v2) return 1;
    return -1;
}

How to read a text file?

It depends on what you are trying to do.

file, err := os.Open("file.txt")
fmt.print(file)

The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File), not file-content. To obtain file-content, you may READ from a file-descriptor.


To read all file content(in bytes) to memory, ioutil.ReadAll

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "log"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


  b, err := ioutil.ReadAll(file)
  fmt.Print(b)
}

But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read from *os.File

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


    buf := make([]byte, 32*1024) // define your buffer size here.

    for {
        n, err := file.Read(buf)

        if n > 0 {
            fmt.Print(buf[:n]) // your read buffer.
        }

        if err == io.EOF {
            break
        }
        if err != nil {
            log.Printf("read %d bytes: %v", n, err)
            break
        }
    }

}

Otherwise, you could also use the standard util package: bufio, try Scanner. A Scanner reads your file in tokens: separator.

By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).

package main

import (
    "fmt"
    "os"
    "log"
    "bufio"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {             // internally, it advances token based on sperator
        fmt.Println(scanner.Text())  // token in unicode-char
        fmt.Println(scanner.Bytes()) // token in bytes

    }
}

Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

JavaScript - Getting HTML form values

My 5 cents here, using form.elements which allows you to query each field by it's name, not only by iteration:

const form = document.querySelector('form[name="valform"]');
const ccValidation = form.elements['cctextbox'].value;
const ccType = form.elements['cardtype'].value;

Get a UTC timestamp

As wizzard pointed out, the correct method is,

new Date().getTime();

or under Javascript 1.5, just

Date.now();

From the documentation,

The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.

If you wanted to make a time stamp without milliseconds you can use,

Math.floor(Date.now() / 1000);

I wanted to make this an answer so the correct method is more visible.

You can compare ExpExc's and Narendra Yadala's results to the method above at http://jsfiddle.net/JamesFM/bxEJd/, and verify with http://www.unixtimestamp.com/ or by running date +%s on a Unix terminal.

AngularJS: ng-model not binding to ng-checked for checkboxes

ngModel and ngChecked are not meant to be used together.

ngChecked is expecting an expression, so by saying ng-checked="true", you're basically saying that the checkbox will always be checked by default.

You should be able to just use ngModel, tied to a boolean property on your model. If you want something else, then you either need to use ngTrueValue and ngFalseValue (which only support strings right now), or write your own directive.

What is it exactly that you're trying to do? If you just want the first checkbox to be checked by default, you should change your model -- item1: true,.

Edit: You don't have to submit your form to debug the current state of the model, btw, you can just dump {{testModel}} into your HTML (or <pre>{{testModel|json}}</pre>). Also your ngModel attributes can be simplified to ng-model="testModel.item1".

http://plnkr.co/edit/HtdOok8aieBjT5GFZOb3?p=preview

How to close form

new WindowSettings();

You just closed a brand new instance of the form that wasn't visible in the first place.

You need to close the original instance of the form by accepting it as a constructor parameter and storing it in a field.

How to check if an appSettings key exists?

I think the LINQ expression may be best:

   const string MyKey = "myKey"

   if (ConfigurationManager.AppSettings.AllKeys.Any(key => key == MyKey))
          {
              // Key exists
          }

How to use filesaver.js

For people who want to load it in the console :

var s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js';
document.body.appendChild(s);

Then :

saveAs(new Blob([data], {type: "application/octet-stream ;charset=utf-8"}), "video.ts")

File will be save when you're out of a breakpoint (at least on Chrome)

Preventing form resubmission

There are 2 approaches people used to take here:

Method 1: Use AJAX + Redirect

This way you post your form in the background using JQuery or something similar to Page2, while the user still sees page1 displayed. Upon successful posting, you redirect the browser to Page2.

Method 2: Post + Redirect to self

This is a common technique on forums. Form on Page1 posts the data to Page2, Page2 processes the data and does what needs to be done, and then it does a HTTP redirect on itself. This way the last "action" the browser remembers is a simple GET on page2, so the form is not being resubmitted upon F5.

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

If you try to be aware of i18n the solution get even more complicated.

The problem is that in other languages the suffix may depend not only on the number itself, but also on the noun it counts. For example in Russian it would be "2-?? ????", but "2-?? ??????" (these mean "2nd day", but "2nd week"). This is not apply if we formatting only days, but in a bit more generic case you should be aware of complexity.

I think nice solution (I didn't have time to actually implement) would be to extend SimpleDateFormetter to apply Locale-aware MessageFormat before passing to the parent class. This way you would be able to support let say for March formats %M to get "3-rd", %MM to get "03-rd" and %MMM to get "third". From outside this class looks like regular SimpleDateFormatter, but supports more formats. Also if this pattern would be by mistake applied by regular SimpleDateFormetter the result would be incorrectly formatted, but still readable.

What is the T-SQL To grant read and write access to tables in a database in SQL Server?

It will be better to Create a New role, then grant execute, select ... etc permissions to this role and finally assign users to this role.

Create role

CREATE ROLE [db_SomeExecutor] 
GO

Grant Permission to this role

GRANT EXECUTE TO db_SomeExecutor
GRANT INSERT  TO db_SomeExecutor

to Add users database>security> > roles > databaseroles>Properties > Add ( bottom right ) you can search AD users and add then

OR

   EXEC sp_addrolemember 'db_SomeExecutor', 'domainName\UserName'

Please refer this post

How to check whether an object is a date?

The best way I found is:

!isNaN(Date.parse("some date test"))
//
!isNaN(Date.parse("22/05/2001"))  // true
!isNaN(Date.parse("blabla"))  // false

How to get primary key of table?

If you have spatial tables in your database, use:

SHOW KEYS FROM table WHERE Key_name = 'PRIMARY' OR Key_name = 'OGR_FID'

Apache Server (xampp) doesn't run on Windows 10 (Port 80)

Type in command line

netstat -aon | findstr :80

You'll see PID of process which uses port 80. Then try to configure this app to use another port, or just kill it

UPDATE: I'll write my comment here to be more clear: according to this link, in Windows 10, it is the MsDepSvc service which occupies port 80. It's for IIS or Web Matrix 2. If you will not use IIS or Web Matrix 2 for any web development, you can try shutting down the service

And for the second part of your question, you can tell Apache to use another port by editing [Apache folder]/conf/httpd.conf. It has "Listen 80" string. Change 80 to whatever free port you want and reload Apache

Running conda with proxy

The best way I settled with is to set proxy environment variables right before using conda or pip install/update commands. Simply run:

set HTTP_PROXY=http://username:password@proxy_url:port

For example, your actual command could be like

set HTTP_PROXY=http://yourname:[email protected]_company.com:8080

If your company uses https proxy, then also

set HTTPS_PROXY=https://username:password@proxy_url:port

Once you exit Anaconda prompt then this setting is gone, so your username/password won't be saved after the session.

I didn't choose other methods mentioned in Anaconda documentation or some other sources, because they all require hardcoding of username/password into

  • Windows environment variables (also this requires restart of Anaconda prompt for the first time)
  • Conda .condarc or .netrc configuration files (also this won't work for PIP)
  • A batch/script file loaded while starting Anaconda prompt (also this might require configuring the path)

All of these are unsafe and will require constant update later. And if you forget where to update? More troubleshooting will come your way...

Adding two Java 8 streams, or an extra element to a stream

If you don't mind using 3rd Party Libraries cyclops-react has an extended Stream type that will allow you to do just that via the append / prepend operators.

Individual values, arrays, iterables, Streams or reactive-streams Publishers can be appended and prepended as instance methods.

Stream stream = ReactiveSeq.of(1,2)
                           .filter(x -> x!=0)
                           .append(ReactiveSeq.of(3,4))
                           .filter(x -> x!=1)
                           .append(5)
                           .filter(x -> x!=2);

[Disclosure I am the lead developer of cyclops-react]

How to set opacity in parent div and not affect in child div?

I know this is old, but just in case it will help someone else.

<div style="background-color: rgba(255, 0, 0, 0.5)">child</div> 

Where rgba is: red, green, blue, and a is for transparency.

Is there a max size for POST parameter content?

As per this the default is 2 MB for your <Connector>.

maxPostSize = The maximum size in bytes of the POST which will be handled by the container FORM URL parameter parsing. The limit can be disabled by setting this attribute to a value less than or equal to 0. If not specified, this attribute is set to 2097152 (2 megabytes).

Edit Tomcat's server.xml. In the <Connector> element, add an attribute maxPostSize and set a larger value (in bytes) to increase the limit.

Having said that, if this is the issue, you should have got an exception on the lines of Post data too big in tomcat

For Further Info

Complete list of reasons why a css file might not be working

Firefox can reject a stylesheet if it is not served with a content type of "text/css". (This is separate from the 'type="text/css"' declaration in the HTML.)

Adding image inside table cell in HTML

Sould look like:

<td colspan ='4'><img src="\Pics\H.gif" alt="" border='3' height='100' width='100' /></td>

.

<td> need to be closed with </td> <img /> is (in most case) an empty tag. The closing tag is replacede by /> instead... like for br's

<br/>

Your html structure is plain worng (sorry), but this will probably turn into a really bad cross-brwoser compatibility. Also, Encapsulate the value of your attributes with quotes and avoid using upercase in tags.

How to draw border on just one side of a linear layout?

To get a border on just one side of a drawable, apply a negative inset to the other 3 sides (causing those borders to be drawn off-screen).

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetTop="-2dp" 
    android:insetBottom="-2dp"
    android:insetLeft="-2dp">

    <shape android:shape="rectangle">
        <stroke android:width="2dp" android:color="#FF0000" />
        <solid android:color="#000000" />
    </shape>

</inset>

enter image description here

This approach is similar to naykah's answer, but without the use of a layer-list.

How to downgrade the installed version of 'pip' on windows?

well the only thing that will work is

python -m pip install pip==

you can and should run it under IDE terminal (mine was pycharm)

How to insert multiple rows from a single query using eloquent/fluent

using Eloquent

$data = array(
    array('user_id'=>'Coder 1', 'subject_id'=> 4096),
    array('user_id'=>'Coder 2', 'subject_id'=> 2048),
    //...
);

Model::insert($data);

How to pick element inside iframe using document.getElementById

(this is to add to the chosen answer)

Make sure the iframe is loaded before you

contentWindow.document

Otherwise, your getElementById will be null.

PS: Can't comment, still low reputation to comment, but this is a follow-up on the chosen answer as I've spent some good debugging time trying to figure out I should force the iframe load before selecting the inner-iframe element.

CSS: auto height on containing div, 100% height on background div inside containing div

I ended up making 2 display:table;

#container-tv { /* Tiled background */
    display:table;
    width:100%;
    background-image: url(images/back.jpg);
    background-repeat: repeat;  
}
#container-body-background { /* center column but not 100% width */ 
    display:table;
    margin:0 auto;
    background-image:url(images/middle-back.png);
    background-repeat: repeat-y;

}

This made it have a tiled background image with a background image in the middle as a column. It stretches to 100% height of page not just 100% of browser window size

What are DDL and DML?

DDL: Change the schema

DML: Change the data

Seems specific to MySQL limitations (rails's source code)

How do I get the file extension of a file in Java?

// Modified from EboMike's answer

String extension = "/path/to/file/foo.txt".substring("/path/to/file/foo.txt".lastIndexOf('.'));

extension should have ".txt" in it when run.

How to add a linked source folder in Android Studio?

While sourceSets allows you to include entire directory structures, there's no way to exclude parts of it in Android Studio (as of version 1.2), as described here: Android Studio Exclude Class from build?

Until Android Studio gets updated to support include/exclude directives for Android sources, Symlinks work quite well. If you're using Windows, native tools such as junction or mklink can accomplish the equivalent of Un*x symlinks. CygWin can also create these with a little coersion. See: Git Symlinks in Windows and How to make symbolic link with cygwin in Windows 7

Spring @Transactional - isolation, propagation

You almost never want to use Read Uncommited since it's not really ACID compliant. Read Commmited is a good default starting place. Repeatable Read is probably only needed in reporting, rollup or aggregation scenarios. Note that many DBs, postgres included don't actually support Repeatable Read, you have to use Serializable instead. Serializable is useful for things that you know have to happen completely independently of anything else; think of it like synchronized in Java. Serializable goes hand in hand with REQUIRES_NEW propagation.

I use REQUIRES for all functions that run UPDATE or DELETE queries as well as "service" level functions. For DAO level functions that only run SELECTs, I use SUPPORTS which will participate in a TX if one is already started (i.e. being called from a service function).

Get elements by attribute when querySelectorAll is not available without using libraries?

Try this it works

document.querySelector('[attribute="value"]')

example :

document.querySelector('[role="button"]')

ValueError: Wrong number of items passed - Meaning and suggestions?

for i in range(100):
try:
  #Your code here
  break
except:
  continue

This one worked for me.

How to urlencode data for curl command?

Simple PHP option:

echo 'part-that-needs-encoding' | php -R 'echo urlencode($argn);'

Overflow Scroll css is not working in the div

You didn't gave the div a height. So it will automatically stretch when more content is added. Give it a fix-height and the scroll bars will show up.

JSF(Primefaces) ajax update of several elements by ID's

If the to-be-updated component is not inside the same NamingContainer component (ui:repeat, h:form, h:dataTable, etc), then you need to specify the "absolute" client ID. Prefix with : (the default NamingContainer separator character) to start from root.

<p:ajax process="@this" update="count :subTotal"/>

To be sure, check the client ID of the subTotal component in the generated HTML for the actual value. If it's inside for example a h:form as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.

<p:ajax process="@this" update="count :formId:subTotal"/>

Space separation of IDs is more recommended as <f:ajax> doesn't support comma separation and starters would otherwise get confused.

Sniffing/logging your own Android Bluetooth traffic

Also, this might help finding the actual location the btsnoop_hci.log is being saved:

adb shell "cat /etc/bluetooth/bt_stack.conf | grep FileName"

Change Image of ImageView programmatically in Android

If the above solutions are not working just delete this entire line from XML

android:src="@drawable/image"

& only try

imageView.setBackgroundResource(R.drawable.image);

How to check if any Checkbox is checked in Angular

Try to think in terms of a model and what happens to that model when a checkbox is checked.

Assuming that each checkbox is bound to a field on the model with ng-model then the property on the model is changed whenever a checkbox is clicked:

<input type='checkbox' ng-model='fooSelected' />
<input type='checkbox' ng-model='baaSelected' />

and in the controller:

$scope.fooSelected = false;
$scope.baaSelected = false;

The next button should only be available under certain circumstances so add the ng-disabled directive to the button:

<button type='button' ng-disabled='nextButtonDisabled'></button>

Now the next button should only be available when either fooSelected is true or baaSelected is true and we need to watch any changes to these fields to make sure that the next button is made available or not:

$scope.$watch('[fooSelected,baaSelected]', function(){
    $scope.nextButtonDisabled = !$scope.fooSelected && !scope.baaSelected;
}, true );

The above assumes that there are only a few checkboxes that affect the availability of the next button but it could be easily changed to work with a larger number of checkboxes and use $watchCollection to check for changes.

phpMyAdmin mbstring error

I've solved my problem by this way: Edit the php.ini file:

  1. change extension_dir = "ext" into extension_dir = "D:\php\ext" (please write ur own full path for the extension directory)
  2. change ;extension=php_mbstring.dll into extension=php_mbstring.dll (delete the ";")
  3. Then just save your php.ini file and copy it to ur Windows directory?(“C:\Windows“)
  4. restart the apache server?

The above is my solution,Hope it will work for u.

Xcode 8 shows error that provisioning profile doesn't include signing certificate

I had remaining private keys from certificates I had revoked, certificates were gone but not the private keys. Deleting them solved the problem.

To find them:

  1. Open Keychain access
  2. Click "Keys" under category on the side left menu
  3. Look for iOS Developer: ..." keys that do not have a certificate tied to them
  4. I deleted them and problem went away

The highlighted key in the picture is a sample private key without a certificate.

The highlighted item was one key causing issues, deleting it solved issue

Get filename and path from URI from mediastore

Simple and easy. You can do this from the URI just like below!

public void getContents(Uri uri)
{
    Cursor vidCursor = getActivity.getContentResolver().query(uri, null, null,
                                                              null, null);
    if (vidCursor.moveToFirst())
    {
        int column_index =
        vidCursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        Uri filePathUri = Uri.parse(vidCursor .getString(column_index));
        String video_name =  filePathUri.getLastPathSegment().toString();
        String file_path=filePathUri.getPath();
        Log.i("TAG", video_name + "\b" file_path);
    }
}

How to solve could not create the virtual machine error of Java Virtual Machine Launcher?

I had to add an older jdk on my project.

Right button on Project folder > Properties > Java Build Path > Libraries > Add Library > JRE System Library

enter image description here

enter image description here

In case you don't have the package for jdk8, download the jdk that some user mentioned above (http://download.oracle.com/otn-pub/java/jdk/8u172-b11/a58eab1ec242421181065cdc37240b08/jdk-8u172-windows-x64.exe) and click on "Installed JREs" and search for the directory you downloaded the jdk8.

enter image description here

Then click on Finish.

Remove the apache server and add again.

The magic is done ;)

iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

This is the complete answer to my question. I had originally marked @Colin Williams' answer as the correct answer, as it helped me get to the complete solution. A community member, @Slipp D. Thompson edited my question, after about 2.5 years of me having asked it, and told me I was abusing SO's Q & A format. He also told me to separately post this as the answer. So here's the complete answer that solved my problem:

@Colin Williams, thank you! Your answer and the article you linked out to gave me a lead to try something with CSS.

So, I was using translate3d before. It produced unwanted results. Basically, it would chop off and NOT RENDER elements that were offscreen, until I interacted with them. So, basically, in landscape orientation, half of my site that was offscreen was not being shown. This is a iPad web app, owing to which I was in a fix.

Applying translate3d to relatively positioned elements solved the problem for those elements, but other elements stopped rendering, once offscreen. The elements that I couldn't interact with (artwork) would never render again, unless I reloaded the page.

The complete solution:

*:not(html) {
    -webkit-transform: translate3d(0, 0, 0);
}

Now, although this might not be the most "efficient" solution, it was the only one that works. Mobile Safari does not render the elements that are offscreen, or sometimes renders erratically, when using -webkit-overflow-scrolling: touch. Unless a translate3d is applied to all other elements that might go offscreen owing to that scroll, those elements will be chopped off after scrolling.

So, thanks again, and hope this helps some other lost soul. This surely helped me big time!

How do I parse a string with a decimal point to a double?

The trick is to use invariant culture, to parse dot in all cultures.

double.Parse("3.5", System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.NumberFormatInfo.InvariantInfo);

Android; Check if file exists without creating a new one

public boolean FileExists(String fname) {
        File file = getBaseContext().getFileStreamPath(fname);
        return file.exists();
}

Binding List<T> to DataGridView in WinForm

Yes, it is possible to do with out rebinding by implementing INotifyPropertyChanged Interface.

Pretty Simple example is available here,

http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

How to find a value in an excel column by vba code Cells.Find

Dim strFirstAddress As String
Dim searchlast As Range
Dim search As Range

Set search = ActiveSheet.Range("A1:A100")
Set searchlast = search.Cells(search.Cells.Count)

Set rngFindValue = ActiveSheet.Range("A1:A100").Find(Text, searchlast, xlValues)
If Not rngFindValue Is Nothing Then
  strFirstAddress = rngFindValue.Address
  Do
    Set rngFindValue = search.FindNext(rngFindValue)
  Loop Until rngFindValue.Address = strFirstAddress

How can I make PHP display the error instead of giving me 500 Internal Server Error

It's worth noting that if your error is due to .htaccess, for example a missing rewrite_module, you'll still see the 500 internal server error.

Add a column in a table in HIVE QL

You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);, you just need to get rid of default sum(max_count). No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL as the value for every cell in that column.

So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.

You also have the option to always COALESCE the column to your desired default and leave it NULL for now. This option fails when you want NULL to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE.

If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.

What is the difference between DBMS and RDBMS?

DBMS stands for "Database Management Systems" it includes all Databases. RDBMS are a special Type of DMBS . R in RDBMS implies that the database uses the Relational model. a collection of related tables in the relational model makes up a database.DBMS is used for simple and small application while RDBMS is used for applications with a huge database.DBMS are for smaller organizations where security is not concerned(i.e. DBMS does not impose any constraints) while RDBMS is quitely opposite( RDBMS define the integrity constraint for the purpose of holding ACID PROPERTY).

Using grep to help subset a data frame in R

It's pretty straightforward using [ to extract:

grep will give you the position in which it matched your search pattern (unless you use value = TRUE).

grep("^G45", My.Data$x)
# [1] 2

Since you're searching within the values of a single column, that actually corresponds to the row index. So, use that with [ (where you would use My.Data[rows, cols] to get specific rows and columns).

My.Data[grep("^G45", My.Data$x), ]
#      x y
# 2 G459 2

The help-page for subset shows how you can use grep and grepl with subset if you prefer using this function over [. Here's an example.

subset(My.Data, grepl("^G45", My.Data$x))
#      x y
# 2 G459 2

As of R 3.3, there's now also the startsWith function, which you can again use with subset (or with any of the other approaches above). According to the help page for the function, it's considerably faster than using substring or grepl.

subset(My.Data, startsWith(as.character(x), "G45"))
#      x y
# 2 G459 2

JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

The github project JavaScript-Load-Image provides a complete solution to the EXIF orientation problem, correctly rotating/mirroring images for all 8 exif orientations. See the online demo of javascript exif orientation

The image is drawn onto an HTML5 canvas. Its correct rendering is implemented in js/load-image-orientation.js through canvas operations.

Hope this saves somebody else some time, and teaches the search engines about this open source gem :)

VBA Convert String to Date

Looks like it could be throwing the error on the empty data row, have you tried to just make sure itemDate isn't empty before you run the CDate() function? I think this might be your problem.

importing pyspark in python shell

Turns out that the pyspark bin is LOADING python and automatically loading the correct library paths. Check out $SPARK_HOME/bin/pyspark :

# Add the PySpark classes to the Python path:
export PYTHONPATH=$SPARK_HOME/python/:$PYTHONPATH

I added this line to my .bashrc file and the modules are now correctly found!

Java Enum return Int

First you should ask yourself the following question: Do you really need an int?

The purpose of enums is to have a collection of items (constants), that have a meaning in the code without relying on an external value (like an int). Enums in Java can be used as an argument on switch statments and they can safely be compared using "==" equality operator (among others).

Proposal 1 (no int needed) :

Often there is no need for an integer behind it, then simply use this:

private enum DownloadType{
    AUDIO, VIDEO, AUDIO_AND_VIDEO
}

Usage:

DownloadType downloadType = MyObj.getDownloadType();
if (downloadType == DownloadType.AUDIO) {
    //...
}
//or
switch (downloadType) {
  case AUDIO:  //...
          break;
  case VIDEO: //...
          break;
  case AUDIO_AND_VIDEO: //...
          break;
}

Proposal 2 (int needed) :

Nevertheless, sometimes it may be useful to convert an enum to an int (for instance if an external API expects int values). In this case I would advise to mark the methods as conversion methods using the toXxx()-Style. For printing override toString().

private enum DownloadType {
    AUDIO(2), VIDEO(5), AUDIO_AND_VIDEO(11);
    private final int code;

    private DownloadType(int code) {
        this.code = code;
    }

    public int toInt() {
        return code;
    }

    public String toString() {
        //only override toString, if the returned value has a meaning for the
        //human viewing this value 
        return String.valueOf(code);
    }
}

System.out.println(DownloadType.AUDIO.toInt());           //returns 2
System.out.println(DownloadType.AUDIO);                   //returns 2 via `toString/code`
System.out.println(DownloadType.AUDIO.ordinal());         //returns 0
System.out.println(DownloadType.AUDIO.name());            //returns AUDIO
System.out.println(DownloadType.VIDEO.toInt());           //returns 5
System.out.println(DownloadType.VIDEO.ordinal());         //returns 1
System.out.println(DownloadType.AUDIO_AND_VIDEO.toInt()); //returns 11

Summary

  • Don't use an Integer together with an enum if you don't have to.
  • Don't rely on using ordinal() for getting an integer of an enum, because this value may change, if you change the order (for example by inserting a value). If you are considering to use ordinal() it might be better to use proposal 1.
  • Normally don't use int constants instead of enums (like in the accepted answer), because you will loose type-safety.

Check if value exists in the array (AngularJS)

U can use something like this....

  function (field,value) {

         var newItemOrder= value;
          // Make sure user hasnt already added this item
        angular.forEach(arr, function(item) {
            if (newItemOrder == item.value) {
                arr.splice(arr.pop(item));

            } });

        submitFields.push({"field":field,"value":value});
    };

PostgreSQL, checking date relative to "today"

This should give you the current date minus 1 year:

select now() - interval '1 year';

Update one MySQL table with values from another

It depends what is a use of those tables, but you might consider putting trigger on original table on insert and update. When insert or update is done, update the second table based on only one item from the original table. It will be quicker.

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"

How to set null to a GUID property

extrac Guid values from database functions:

    #region GUID

    public static Guid GGuid(SqlDataReader reader, string field)
    {
        try
        {
            return reader[field] == DBNull.Value ? Guid.Empty : (Guid)reader[field];
        }
        catch { return Guid.Empty; }
    }

    public static Guid GGuid(SqlDataReader reader, int ordinal = 0)
    {
        try
        {
            return reader[ordinal] == DBNull.Value ? Guid.Empty : (Guid)reader[ordinal];
        }
        catch { return Guid.Empty; }
    }

    public static Guid? NGuid(SqlDataReader reader, string field)
    {
        try
        {
            if (reader[field] == DBNull.Value) return (Guid?)null; else return (Guid)reader[field];
        }
        catch { return (Guid?)null; }
    }

    public static Guid? NGuid(SqlDataReader reader, int ordinal = 0)
    {
        try
        {
            if (reader[ordinal] == DBNull.Value) return (Guid?)null; else return (Guid)reader[ordinal];
        }
        catch { return (Guid?)null; }
    }

    #endregion

Responsive Google Map?

I am an amateur but I found this worked:

.maps iframe {
    position: absolute;
}

body {
    padding-top: 40px;
    padding-bottom: 820px;
    height: available;
}

There may be a bit of whitespace at the bottom but I am satified

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

Try using a format file since your data file only has 4 columns. Otherwise, try OPENROWSET or use a staging table.

myTestFormatFiles.Fmt may look like:

9.0
4
1       SQLINT        0       3       ","      1     StudentNo      ""
2       SQLCHAR       0       100     ","      2     FirstName      SQL_Latin1_General_CP1_CI_AS
3       SQLCHAR       0       100     ","      3     LastName       SQL_Latin1_General_CP1_CI_AS
4       SQLINT        0       4       "\r\n"   4     Year           "


(source: microsoft.com)

This tutorial on skipping a column with BULK INSERT may also help.

Your statement then would look like:

USE xta9354
GO
BULK INSERT xta9354.dbo.Students
    FROM 'd:\userdata\xta9_Students.txt' 
    WITH (FORMATFILE = 'C:\myTestFormatFiles.Fmt')

What is TypeScript and why would I use it in place of JavaScript?

I originally wrote this answer when TypeScript was still hot-off-the-presses. Five years later, this is an OK overview, but look at Lodewijk's answer below for more depth

1000ft view...

TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code.

To get an idea of what I mean, watch Microsoft's introductory video on the language.

For a large JavaScript project, adopting TypeScript might result in more robust software, while still being deployable where a regular JavaScript application would run.

It is open source, but you only get the clever Intellisense as you type if you use a supported IDE. Initially, this was only Microsoft's Visual Studio (also noted in blog post from Miguel de Icaza). These days, other IDEs offer TypeScript support too.

Are there other technologies like it?

There's CoffeeScript, but that really serves a different purpose. IMHO, CoffeeScript provides readability for humans, but TypeScript also provides deep readability for tools through its optional static typing (see this recent blog post for a little more critique). There's also Dart but that's a full on replacement for JavaScript (though it can produce JavaScript code)

Example

As an example, here's some TypeScript (you can play with this in the TypeScript Playground)

class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}  

And here's the JavaScript it would produce

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();

Notice how the TypeScript defines the type of member variables and class method parameters. This is removed when translating to JavaScript, but used by the IDE and compiler to spot errors, like passing a numeric type to the constructor.

It's also capable of inferring types which aren't explicitly declared, for example, it would determine the greet() method returns a string.

Debugging TypeScript

Many browsers and IDEs offer direct debugging support through sourcemaps. See this Stack Overflow question for more details: Debugging TypeScript code with Visual Studio

Want to know more?

I originally wrote this answer when TypeScript was still hot-off-the-presses. Check out Lodewijk's answer to this question for some more current detail.

Correct mime type for .mp4

When uploading .mp4 file into Perl script, using CGI.pm I see it as video/mp when printing out Content-type for the uploaded file. I hope it will help someone.

Sequence contains no elements?

From "Fixing LINQ Error: Sequence contains no elements":

When you get the LINQ error "Sequence contains no elements", this is usually because you are using the First() or Single() command rather than FirstOrDefault() and SingleOrDefault().

This can also be caused by the following commands:

  • FirstAsync()
  • SingleAsync()
  • Last()
  • LastAsync()
  • Max()
  • Min()
  • Average()
  • Aggregate()

Is Google Play Store supported in avd emulators?

There is no google play store in avd emulator. But you can install it manually.

  1. Install Google APIs System Image, so you will have google services already (without play store)

  2. Create AVD based on Google APIs image

  3. Download smallest archive from http://opengapps.org/ and extract Phonesky.apk from it

  4. Push Phonesky.apk to /system/priv-app/ on avd.

  5. Restart avd. Google play should be there.

Recently I've just tried to do it by myself and you can find detailed tutorial on my blog: http://linuxoidchannel.blogspot.com/2017/01/how-to-install-google-play-store-on.html

DLL load failed error when importing cv2

Please Remember if you want to install python package/libraries for windows,

you should always consider Python unofficial Binaries

Step 1:

Search for your package, download dependent version 2.7 or 3.6 you can find it under Downloads/your_package_version.whl its called python wheel

Step 2:

Now install using pip,

pip install ~/Downloads/your_packae_ver.whl

this will install without any error.

How to compare two floating point numbers in Bash?

num1=0.555
num2=2.555


if [ `echo "$num1>$num2"|bc` -eq 1 ]; then
       echo "$num1 is greater then $num2"
else
       echo "$num2 is greater then $num1"
fi

How to configure Spring Security to allow Swagger URL to be accessed without authentication

I updated with /configuration/** and /swagger-resources/** and it worked for me.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**");

}

Changing capitalization of filenames in Git

Sometimes you want to change the capitalization of a lot of file names on a case insensitive filesystem (e.g. on OS X or Windows). Doing git mv commands will tire quickly. To make things a bit easier this is what I do:

  1. Move all files outside of the directory to, let’s, say the desktop.
  2. Do a git add . -A to remove all files.
  3. Rename all files on the desktop to the proper capitalization.
  4. Move all the files back to the original directory.
  5. Do a git add .. Git should see that the files are renamed.

Now you can make a commit saying you have changed the file name capitalization.

Callback when CSS3 transition finishes

There is an animationend Event that can be observed see documentation here, also for css transition animations you could use the transitionend event

There is no need for additional libraries these all work with vanilla JS

_x000D_
_x000D_
document.getElementById("myDIV").addEventListener("transitionend", myEndFunction);_x000D_
function myEndFunction() {_x000D_
 this.innerHTML = "transition event ended";_x000D_
}
_x000D_
#myDIV {transition: top 2s; position: relative; top: 0;}_x000D_
div {background: #ede;cursor: pointer;padding: 20px;}
_x000D_
<div id="myDIV" onclick="this.style.top = '55px';">Click me to start animation.</div>
_x000D_
_x000D_
_x000D_

nginx showing blank PHP pages

Many users fall in this thread expecting to find a solution for blank pages being displayed while using nginx+php-fpm, me being one of them. This is a recap of what I ended up doing after reading many of the answers here plus my own investigations (updated to php7.2):

1) Open /etc/php/7.2/fpm/pool.d/www.conf and check the value of parameter listen.

listen = /var/run/php/php7.2-fpm.sock

2) Parameter listen should match fastcgi_pass parameter in your site configuration file (i,e: /etc/nginx/sites-enabled/default).

fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;

3) Check the file actually exists:

$ file /var/run/php/php7.2-fpm.sock 
/var/run/php/php7.2-fpm.sock: socket

4) If it doesn't exist that means php7.2-fpm is not running, so you need to restart it:

$ sudo /etc/init.d/php7.2-fpm restart
[ ok ] Restarting php7.2-fpm (via systemctl): php7.2-fpm.service.


With regard to the location section in /etc/nginx/sites-enabled/default:

   # pass PHP scripts to FastCGI server
   #
   location ~ \.php$ {
      include snippets/fastcgi-php.conf;

      # With php-fpm (or other unix sockets):
      fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
   }

Check the file snippets/fastcgi-php.conf exists at location /etc/nginx/:

$ file /etc/nginx/snippets/fastcgi-php.conf
/etc/nginx/snippets/fastcgi-php.conf: ASCII text

This file contains a list of variable definitions required by php7.2-fpm. The variables are defined directly or through an include of a separated file.

 include fastcgi.conf;

This file is located at /etc/nginx/fastcgi.conf and it looks like:

fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
...
fastcgi_param  REDIRECT_STATUS    200;

nginx includes two possible parameter files: fastcgi_params and fastcgi.conf. The difference between both is the definition of variable SCRIPT_FILENAME:

$ diff fastcgi_params fastcgi.conf 
1a2
> fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;

To make a long story short, fastcgi.conf should always work. If for some reason you're set up is using fastcgi_params, you should define SCRIPT_FILENAME:

location ~ \.php$ {
  include snippets/fastcgi-php.conf;

  # With php-fpm (or other unix sockets):
  fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;

  fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
}

Now reload nginx configuration:

$ sudo nginx -s reload

And check a php file is displayed correctly. For instance:

/var/www/html/test.php

<pre><?php var_export($_SERVER)?></pre>

Where /var/www/html is the path to the document root.

If despite all that, you're still seeing a blank file, make sure your php.ini has short_open_tag enabled (if you're testing a PHP page with short tags).

Can't install any packages in Node.js using "npm install"

I found the there is a certificate expired issue with:

npm set registry https://registry.npmjs.org/

So I made it http, not https :-

npm set registry http://registry.npmjs.org/

And have no problems so far.

printf formatting (%d versus %u)

You can find a list of formatting escapes on this page.

%d is a signed integer, while %u is an unsigned integer. Pointers (when treated as numbers) are usually non-negative.

If you actually want to display a pointer, use the %p format specifier.

Log all requests from the python-requests module

When trying to get the Python logging system (import logging) to emit low level debug log messages, it suprised me to discover that given:

requests --> urllib3 --> http.client.HTTPConnection

that only urllib3 actually uses the Python logging system:

  • requests no
  • http.client.HTTPConnection no
  • urllib3 yes

Sure, you can extract debug messages from HTTPConnection by setting:

HTTPConnection.debuglevel = 1

but these outputs are merely emitted via the print statement. To prove this, simply grep the Python 3.7 client.py source code and view the print statements yourself (thanks @Yohann):

curl https://raw.githubusercontent.com/python/cpython/3.7/Lib/http/client.py |grep -A1 debuglevel` 

Presumably redirecting stdout in some way might work to shoe-horn stdout into the logging system and potentially capture to e.g. a log file.

Choose the 'urllib3' logger not 'requests.packages.urllib3'

To capture urllib3 debug information through the Python 3 logging system, contrary to much advice on the internet, and as @MikeSmith points out, you won’t have much luck intercepting:

log = logging.getLogger('requests.packages.urllib3')

instead you need to:

log = logging.getLogger('urllib3')

Debugging urllib3 to a log file

Here is some code which logs urllib3 workings to a log file using the Python logging system:

import requests
import logging
from http.client import HTTPConnection  # py3

# log = logging.getLogger('requests.packages.urllib3')  # useless
log = logging.getLogger('urllib3')  # works

log.setLevel(logging.DEBUG)  # needed
fh = logging.FileHandler("requests.log")
log.addHandler(fh)

requests.get('http://httpbin.org/')

the result:

Starting new HTTP connection (1): httpbin.org:80
http://httpbin.org:80 "GET / HTTP/1.1" 200 3168

Enabling the HTTPConnection.debuglevel print() statements

If you set HTTPConnection.debuglevel = 1

from http.client import HTTPConnection  # py3
HTTPConnection.debuglevel = 1
requests.get('http://httpbin.org/')

you'll get the print statement output of additional juicy low level info:

send: b'GET / HTTP/1.1\r\nHost: httpbin.org\r\nUser-Agent: python- 
requests/2.22.0\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nConnection: keep-alive\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Access-Control-Allow-Credentials header: Access-Control-Allow-Origin 
header: Content-Encoding header: Content-Type header: Date header: ...

Remember this output uses print and not the Python logging system, and thus cannot be captured using a traditional logging stream or file handler (though it may be possible to capture output to a file by redirecting stdout).

Combine the two above - maximise all possible logging to console

To maximise all possible logging, you must settle for console/stdout output with this:

import requests
import logging
from http.client import HTTPConnection  # py3

log = logging.getLogger('urllib3')
log.setLevel(logging.DEBUG)

# logging from urllib3 to console
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
log.addHandler(ch)

# print statements from `http.client.HTTPConnection` to console/stdout
HTTPConnection.debuglevel = 1

requests.get('http://httpbin.org/')

giving the full range of output:

Starting new HTTP connection (1): httpbin.org:80
send: b'GET / HTTP/1.1\r\nHost: httpbin.org\r\nUser-Agent: python-requests/2.22.0\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nConnection: keep-alive\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
http://httpbin.org:80 "GET / HTTP/1.1" 200 3168
header: Access-Control-Allow-Credentials header: Access-Control-Allow-Origin 
header: Content-Encoding header: ...

ImportError: No module named pythoncom

If you're on windows you probably want the pywin32 library, which includes pythoncom and a whole lot of other stuff that is pretty standard.

WPF global exception handler

As mentioned above

Application.Current.DispatcherUnhandledException will not catch exceptions that are thrown from another thread then the main thread.

That actual depend on how the thread was created

One case that is not handled by Application.Current.DispatcherUnhandledException is System.Windows.Forms.Timer for which Application.ThreadException can be used to handle these if you run Forms on other threads than the main thread you will need to set Application.ThreadException from each such thread

C++ Returning reference to local variable

A good thing to remember are these simple rules, and they apply to both parameters and return types...

  • Value - makes a copy of the item in question.
  • Pointer - refers to the address of the item in question.
  • Reference - is literally the item in question.

There is a time and place for each, so make sure you get to know them. Local variables, as you've shown here, are just that, limited to the time they are locally alive in the function scope. In your example having a return type of int* and returning &i would have been equally incorrect. You would be better off in that case doing this...

void func1(int& oValue)
{
    oValue = 1;
}

Doing so would directly change the value of your passed in parameter. Whereas this code...

void func1(int oValue)
{
    oValue = 1;
}

would not. It would just change the value of oValue local to the function call. The reason for this is because you'd actually be changing just a "local" copy of oValue, and not oValue itself.

how to change the default positioning of modal in bootstrap?

To change the Modal position in the viewport you can target the Modal div id, in this example this id is myModal3

    <div id="modal3" class="modal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>One fine body…</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>


#myModal3 {
top:5%;
right:50%;
outline: none;
overflow:hidden;
}

Conversion of a datetime2 data type to a datetime data type results out-of-range value

What kind of dates do you have in the column?

Do all of them fit within the range of the type?


As an aside, the correct way to get a Type object for the DataColumn constructor is the typeof keyword, which is orders of magnitude faster.

Therefore, to create the column, you should write

new DataColumn("myDate", typeof(DateTime))

PHP header() redirect with POST variables

If you don't want to use sessions, the only thing you can do is POST to the same page. Which IMO is the best solution anyway.

// form.php

<?php

    if (!empty($_POST['submit'])) {
        // validate

        if ($allGood) {
            // put data into database or whatever needs to be done

            header('Location: nextpage.php');
            exit;
        }
    }

?>

<form action="form.php">
    <input name="foo" value="<?php if (!empty($_POST['foo'])) echo htmlentities($_POST['foo']); ?>">
    ...
</form>

This can be made more elegant, but you get the idea...

How to downgrade php from 5.5 to 5.3

Short answer is no.

XAMPP is normally built around a specific PHP version to ensure plugins and modules are all compatible and working correctly.

If your project specifically needs PHP 5.3 - the cleanest method is simply reinstalling an older version of XAMPP with PHP 5.3 packaged into it.

XAMPP 1.7.7 was their last update before moving off PHP 5.3.

Copy an entire worksheet to a new worksheet in Excel 2010

ThisWorkbook.Worksheets("Master").Sheet1.Cells.Copy _
    Destination:=newWorksheet.Cells

The above will copy the cells. If you really want to duplicate the entire sheet, then I'd go with @brettdj's answer.

htmlentities() vs. htmlspecialchars()

The differences between htmlspecialchars() and htmlentities() is very small. Lets see some examples:

htmlspecialchars

htmlspecialchars(string $string) takes multiple arguments where as the first argument is a string and all other arguments (certain flags, certain encodings etc. ) are optional. htmlspecialchars converts special characters in the string to HTML entities. For example if you have < br > in your string, htmlspecialchars will convert it into &lt; b &gt;. Whereas characters like µ † etc. have no special significance in HTML. So they will be not converted to HTML entities by htmlspecialchars function as shown in the below example.

echo htmlspecialchars('An example <br>'); // This will print - An example &lt; br &gt;
echo htmlspecialchars('µ †');             // This will print -  µ †

htmlentities

htmlentities ( string $string) is very similar to htmlspecialchars and takes multiple arguments where as the first argument is a string and all other arguments are optional (certain flags, certain encodings etc.). Unlike htmlspecialchars, htmlentities converts not only special characters in the string to HTML entities but all applicable characters to HTML entities.

echo htmlentities('An example <br>'); // This will print - An example &lt; br &gt;
echo htmlentities('µ †');             // This will print -  &micro; &dagger; 

Which HTTP methods match up to which CRUD methods?

The whole key is whether you're doing an idempotent change or not. That is, if taking action on the message twice will result in “the same” thing being there as if it was only done once, you've got an idempotent change and it should be mapped to PUT. If not, it maps to POST. If you never permit the client to synthesize URLs, PUT is pretty close to Update and POST can handle Create just fine, but that's most certainly not the only way to do it; if the client knows that it wants to create /foo/abc and knows what content to put there, it works just fine as a PUT.

The canonical description of a POST is when you're committing to purchasing something: that's an action which nobody wants to repeat without knowing it. By contrast, setting the dispatch address for the order beforehand can be done with PUT just fine: it doesn't matter if you are told to send to 6 Anywhere Dr, Nowhereville once, twice or a hundred times: it's still the same address. Does that mean that it's an update? Could be… It all depends on how you want to write the back-end. (Note that the results might not be identical: you could report back to the user when they last did a PUT as part of the representation of the resource, which would ensure that repeated PUTs do not cause an identical result, but the result would still be “the same” in a functional sense.)

forEach loop Java 8 for Map entry set

Read the javadoc: Map<K, V>.forEach() expects a BiConsumer<? super K,? super V> as argument, and the signature of the BiConsumer<T, U> abstract method is accept(T t, U u).

So you should pass it a lambda expression that takes two inputs as argument: the key and the value:

map.forEach((key, value) -> {
    System.out.println("Key : " + key + " Value : " + value);
});

Your code would work if you called forEach() on the entry set of the map, not on the map itself:

map.entrySet().forEach(entry -> {
    System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}); 

Git reset --hard and push to remote repository

The whole git resetting business looked far to complicating for me.

So I did something along the lines to get my src folder in the state i had a few commits ago

# reset the local state
git reset <somecommit> --hard 
# copy the relevant part e.g. src (exclude is only needed if you specify .)
tar cvfz /tmp/current.tgz --exclude .git  src
# get the current state of git
git pull
# remove what you don't like anymore
rm -rf src
# restore from the tar file
tar xvfz /tmp/current.tgz
# commit everything back to git
git commit -a
# now you can properly push
git push

This way the state of affairs in the src is kept in a tar file and git is forced to accept this state without too much fiddling basically the src directory is replaced with the state it had several commits ago.

Why is String immutable in Java?

In addition to the great answers, I wanted to add a few points. Like Strings, Array holds a reference to the starting of the array so if you create two arrays arr1 and arr2 and did something like arr2 = arr1 this will make the reference of arr2 same as arr1 hence changing value in one of them will result in change of the other one for example

public class Main {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4};
        int[] b = a;
        a[0] = 8;
        b[1] = 7;
        System.out.println("A: " + a[0] + ", B: " + b[0]);
        System.out.println("A: " + a[1] + ", B: " + b[1]);
        //outputs
        //A: 8, B: 8
        //A: 7, B: 7
    }
}

Not only that it would cause bugs in the code it also can(and will) be exploited by malicious user. Suppose if you have a system that changes the admin password. The user have to first enter the newPassword and then the oldPassword if the oldPassword is same as the adminPass the program change the password by adminPass = newPassword. let's say that the new password has the same reference as the admin password so a bad programmer may create a temp variable to hold the admin password before the users inputs data if the oldPassword is equal to temp it changes the password otherwise adminPass = temp. Someone knowing that could easily enter the new password and never enter the old password and abracadabra he has admin access. Another thing I didn't understand when learning about Strings why doesn't JVM create a new string for every object and have a unique place in memory for it and you can just do that using new String("str"); The reason you wouldn't want to always use new is because it's not memory efficient and it is slower in most cases read more.

Removing multiple classes (jQuery)

jQuery .removeClass() documentation.

One or more CSS classes to remove from the elements, these are separated by spaces.

Array or List in Java. Which is faster?

I suggest that you use a profiler to test which is faster.

My personal opinion is that you should use Lists.

I work on a large codebase and a previous group of developers used arrays everywhere. It made the code very inflexible. After changing large chunks of it to Lists we noticed no difference in speed.

Diff files present in two different directories

diff can not only compare two files, it can, by using the -r option, walk entire directory trees, recursively checking differences between subdirectories and files that occur at comparable points in each tree.

$ man diff

...

-r  --recursive
        Recursively compare any subdirectories found.

...

Keep placeholder text in UITextField on input in IOS

Instead of using the placeholder text, you'll want to set the actual text property of the field to MM/YYYY, set the delegate of the text field and listen for this method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {     // update the text of the label } 

Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.

Trim a string in C

/* Function to remove white spaces on both sides of a string i.e trim */

void trim (char *s)
{
    int i;

    while (isspace (*s)) s++;   // skip left side white spaces
    for (i = strlen (s) - 1; (isspace (s[i])); i--) ;   // skip right side white spaces
    s[i + 1] = '\0';
    printf ("%s\n", s);
}

jQuery - get all divs inside a div with class ".container"

To get all divs under 'container', use the following:

$(".container>div")  //or
$(".container").children("div");

You can stipulate a specific #id instead of div to get a particular one.

You say you want a div with an 'undefined' id. if I understand you right, the following would achieve this:

$(".container>div[id=]")

Display current date and time without punctuation

Interesting/funny way to do this using parameter expansion (requires bash 4.4 or newer):

${parameter@operator} - P operator

The expansion is a string that is the result of expanding the value of parameter as if it were a prompt string.

$ show_time() { local format='\D{%Y%m%d%H%M%S}'; echo "${format@P}"; }
$ show_time
20180724003251

TransactionRequiredException Executing an update/delete query

Using @PersistenceContext with @Modifying as below fixes error while using createNativeQuery

    import org.springframework.data.jpa.repository.Modifying;
    import org.springframework.transaction.annotation.Transactional;

    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @Transactional
    @Modifying
    public <S extends T> S save(S entity) {
         Query q = entityManager.createNativeQuery(...);
         q.setParameter...
         q.executeUpdate();
         return entity;
    }

Android RelativeLayout programmatically Set "centerInParent"

Completely untested, but this should work:

View positiveButton = findViewById(R.id.positiveButton);
RelativeLayout.LayoutParams layoutParams = 
    (RelativeLayout.LayoutParams)positiveButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
positiveButton.setLayoutParams(layoutParams);

add android:configChanges="orientation|screenSize" inside your activity in your manifest

Disable asp.net button after click to prevent double clicking

using jQuery:

$('form').submit(function(){
    $(':submit', this).click(function() {
        return false;
    });
});

Is there a template engine for Node.js?

I use Twig with Symfony and am now dabbling in node.js, so I'm looking at https://github.com/justjohn/twig.js and https://github.com/paularmstrong/swig, which you'll probably like if you use django.

Font size relative to the user's screen resolution?

I've created a variant of https://stackoverflow.com/a/17845473/189411

where you can set min and max text size in relation of min and max size of box that you want "check" size. In addition you can check size of dom element different than box where you want apply text size.

You resize text between 19px and 25px on #size-2 element, based on 500px and 960px width of #size-2 element

resizeTextInRange(500,960,19,25,'#size-2');

You resize text between 13px and 20px on #size-1 element, based on 500px and 960px width of body element

resizeTextInRange(500,960,13,20,'#size-1','body');

complete code are there https://github.com/kiuz/sandbox-html-js-css/tree/gh-pages/text-resize-in-range-of-text-and-screen/src

function inRange (x,min,max) {
    return Math.min(Math.max(x, min), max);
}

function resizeTextInRange(minW,maxW,textMinS,textMaxS, elementApply, elementCheck=0) {

    if(elementCheck==0){elementCheck=elementApply;}

    var ww = $(elementCheck).width();
    var difW = maxW-minW;
    var difT = textMaxS- textMinS;
    var rapW = (ww-minW);
    var out=(difT/100)*(rapW/(difW/100))+textMinS;
    var normalizedOut = inRange(out, textMinS, textMaxS);
    $(elementApply).css('font-size',normalizedOut+'px');

    console.log(normalizedOut);

}

$(function () {
    resizeTextInRange(500,960,19,25,'#size-2');
    resizeTextInRange(500,960,13,20,'#size-1','body');
    $(window).resize(function () {
        resizeTextInRange(500,960,19,25,'#size-2');
        resizeTextInRange(500,960,13,20,'#size-1','body');
    });
});

Python: TypeError: cannot concatenate 'str' and 'int' objects

str(c) returns a new string representation of c, and does not mutate c itself.

c = str(c) 

is probably what you are looking for

No connection could be made because the target machine actively refused it 127.0.0.1:3446

Check if any other program is using that port.

If an instance of the same program is still active, kill that process.

Is it possible to get multiple values from a subquery?

In Oracle query

select a.x
            ,(select b.y || ',' || b.z
                from   b
                where  b.v = a.v
                and    rownum = 1) as multple_columns
from   a

can be transformed to:

select a.x, b1.y, b1.z
from   a, b b1
where  b1.rowid = (
       select b.rowid
       from   b
       where  b.v = a.v
       and    rownum = 1
)

Is useful when we want to prevent duplication for table A. Similarly, we can increase the number of tables:

.... where (b1.rowid,c1.rowid) = (select b.rowid,c.rowid ....

check if file exists on remote host with ssh

ssh -q $HOST [[ -f $FILE_PATH ]] && echo "File exists"

The above will run the echo command on the machine you're running the ssh command from. To get the remote server to run the command:

ssh -q $HOST "[[ ! -f $FILE_PATH ]] && touch $FILE_PATH"

Git add all subdirectories

Also struggled, but got it right typing

git add -f ./JS/*

where JS was my folder name which contain sub folders and files

Excel concatenation quotes

I was Forming some Programming Logic Used CHAR(34) for Quotes at Excel : A small Part of same I am posting which can be helpfull ,Hopefully

1   Customers
2   Invoices

Formula Used :

=CONCATENATE("listEvents.Add(",D4,",",CHAR(34),E4,CHAR(34),");")

Result :

listEvents.Add(1,"Customers");
listEvents.Add(2,"Invoices");

Using cut command to remove multiple columns

Sometimes it's easier to think in terms of which fields to exclude.

If the number of fields not being cut (not being retained in the output) is small, it may be easier to use the --complement flag, e.g. to include all fields 1-20 except not 3, 7, and 12 -- do this:

cut -d, --complement -f3,7,12 <inputfile

Rather than

cut -d, -f-2,4-6,8-11,13-

Is there a way to iterate over a dictionary?

This is iteration using block approach:

    NSDictionary *dict = @{@"key1":@1, @"key2":@2, @"key3":@3};

    [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSLog(@"%@->%@",key,obj);
        // Set stop to YES when you wanted to break the iteration.
    }];

With autocompletion is very fast to set, and you do not have to worry about writing iteration envelope.

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

If you're sure you configure your aws correctly, just make sure the user of the project can read from ./aws or just run your project as a root

How can I read a whole file into a string variable

I think the best thing to do, if you're really concerned about the efficiency of concatenating all of these files, is to copy them all into the same bytes buffer.

buf := bytes.NewBuffer(nil)
for _, filename := range filenames {
  f, _ := os.Open(filename) // Error handling elided for brevity.
  io.Copy(buf, f)           // Error handling elided for brevity.
  f.Close()
}
s := string(buf.Bytes())

This opens each file, copies its contents into buf, then closes the file. Depending on your situation you may not actually need to convert it, the last line is just to show that buf.Bytes() has the data you're looking for.

OSX - How to auto Close Terminal window after the "exit" command executed.

Actually, you should set a config on your Terminal, when your Terminal is up press ?+, then you will see below screen:

enter image description here

Then press shell tab and you will see below screen:

enter image description here

Now select Close if the shell exited cleanly for When the shell exits.

By the above config each time with exit command the Terminal will close but won't quit.

Force Internet Explorer to use a specific Java Runtime Environment install?

First, disable the currently installed version of Java. To do this, go to Control Panel > Java > Advanced > Default Java for Browsers and uncheck Microsoft Internet Explorer.

Next, enable the version of Java you want to use instead. To do this, go to (for example) C:\Program Files\Java\jre1.5.0_15\bin (where jre1.5.0_15 is the version of Java you want to use), and run javacpl.exe. Go to Advanced > Default Java for Browsers and check Microsoft Internet Explorer.

To get your old version of Java back you need to reverse these steps.

Note that in older versions of Java, Default Java for Browsers is called <APPLET> Tag Support (but the effect is the same).

The good thing about this method is that it doesn't affect other browsers, and doesn't affect the default system JRE.

Calling a function in jQuery with click()

$("#closeLink").click(closeIt);

Let's say you want to call your function passing some args to it i.e., closeIt(1, false). Then, you should build an anonymous function and call closeIt from it.

$("#closeLink").click(function() {
    closeIt(1, false);
});

How to delete an SVN project from SVN repository

I too felt like the accepted answer was a bit misleading as it could lead to a user inadvertently deleting multiple Projects. It is not accurate to state that the words Repository, Project and Directory are ambiguous within the context of SVN. They have specific meanings, even if the system itself doesn't enforce those meanings. The community and more importantly the SVN Clients have an agreed upon understanding of these terms which allow them to Tag, Branch and Merge.

Ideally this will help clear any confusion. As someone that has had to go from git to svn for a few projects, it can be frustrating until you learn that SVN branching and SVN projects are really talking about folder structures.

SVN Terminology

Repository

The database of commits and history for your folders and files. A repository can contain multiple 'projects' or no projects.

Project

A specific SVN folder structure which enables SVN tools to perform tagging, merging and branching. SVN does not inherently support branching. Branching was added later and is a result of a special folder structure as follows:

  • /project
    • /tags
    • /branches
    • /trunk

Note: Remember, an SVN 'Project' is a term used to define a specific folder strcuture within a Repository

Projects in a Repository

Repository Layout

As a repository is just a database of the files and directory commits, it can host multiple projects. When discussing Repositories and Projects be sure the correct term is being used.

Removing a Repository could mean removing multiple Projects!

Local SVN Directory (.svn directory at root)

When using a URL commits occur automatically.

  • svn co http://svn.server.local/svn/myrepo
  • cd myrepo

  • Remove a Project: svn rm skunkworks + svn commit

  • Remove a Directory: svn rm regulardir/subdir + svn commit
  • Remove a Project (Without Checking Out): svn rm http://svn.server.local/svn/myrepo/app1
  • Remove a Directory (Without Checking Out): svn rm http://svn.server.local/svn/myrepo/regulardir

Because an SVN Project is really a specific directory structure, removing a project is the same as removing a directory.

SVN Repository Management

There are several SVN servers available to host your repositories. The management of repositories themselves are typically done through the admin consoles of the servers. For example, Visual SVN allows you to create Repositories (databases), directories and Projects. But you cannot remove files, manage commits, rename folders, etc. from within the server console as those are SVN specific tasks. The SVN server typically manages the creation of a repository. Once a repository has been created and you have a new URL, the rest of your work is done through the svn command.

Trust Store vs Key Store - creating with keytool

To explain in common usecase/purpose or layman way:

TrustStore : As the name indicates, its normally used to store the certificates of trusted entities. A process can maintain a store of certificates of all its trusted parties which it trusts.

keyStore : Used to store the server keys (both public and private) along with signed cert.

During the SSL handshake,

  1. A client tries to access https://

  2. And thus, Server responds by providing a SSL certificate (which is stored in its keyStore)

  3. Now, the client receives the SSL certificate and verifies it via trustStore (i.e the client's trustStore already has pre-defined set of certificates which it trusts.). Its like : Can I trust this server ? Is this the same server whom I am trying to talk to ? No middle man attacks ?

  4. Once, the client verifies that it is talking to server which it trusts, then SSL communication can happen over a shared secret key.

Note : I am not talking here anything about client authentication on server side. If a server wants to do a client authentication too, then the server also maintains a trustStore to verify client. Then it becomes mutual TLS

What is the most efficient/quickest way to loop through rows in VBA (excel)?

If you are just looping through 10k rows in column A, then dump the row into a variant array and then loop through that.

You can then either add the elements to a new array (while adding rows when needed) and using Transpose() to put the array onto your range in one move, or you can use your iterator variable to track which row you are on and add rows that way.

Dim i As Long
Dim varray As Variant

varray = Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row).Value

For i = 1 To UBound(varray, 1)
    ' do stuff to varray(i, 1)
Next

Here is an example of how you could add rows after evaluating each cell. This example just inserts a row after every row that has the word "foo" in column A. Not that the "+2" is added to the variable i during the insert since we are starting on A2. It would be +1 if we were starting our array with A1.

Sub test()

Dim varray As Variant
Dim i As Long

varray = Range("A2:A10").Value

'must step back or it'll be infinite loop
For i = UBound(varray, 1) To LBound(varray, 1) Step -1
    'do your logic and evaluation here
    If varray(i, 1) = "foo" Then
       'not how to offset the i variable 
       Range("A" & i + 2).EntireRow.Insert
    End If
Next

End Sub

How does one add keyboard languages and switch between them in Linux Mint 16?

This assumes you have other languages already added in Language Support. (To check this, Menu > Language Support)

Now to make the keyboard language appear in the Panel:

  • Menu > Keyboard > Layouts > Add (+)

The icon 'en' or your language should now appear in the right panel tray. Click it to switch language.

In previous Mint versions, the shortcut for switching language was LEFT SHIFT + CAPS.

It seems now there is no default, and it must be added:

  • System settings > Keyboard > Layouts > Options > Switching to another layout

Keyboard Preferences is also accessible by right-clicking the language icon in the Panel.

Create a root password for PHPMyAdmin

If you tried mysqladmin -u root password 'your_password' and MySQL says denied access, you need to change the my.ini so that the value password is blank. then try mysqladmin -u root password 'your_password' again. It should change your password and open my.ini again and change the value password to the previous one.

How does one convert a HashMap to a List in Java?

Basically you should not mess the question with answer, because it is confusing.

Then you could specify what convert mean and pick one of this solution

List<Integer> keyList = Collections.list(Collections.enumeration(map.keySet()));

List<String> valueList = Collections.list(Collections.enumeration(map.values()));

How do I get the find command to print out the file size with the file name?

If you need to get total size, here is a script proposal

#!/bin/bash
totalSize=0

allSizes=`find . -type f -name *.ear -exec stat -c "%s" {} \;`

for fileSize in $allSizes; do
    totalSize=`echo "$(($totalSize+$fileSize))"`
done
echo "Total size is $totalSize bytes"

Show empty string when date field is 1/1/1900

Try this code

(case when CONVERT(VARCHAR(10), CreatedDate, 103) = '01/01/1900' then '' else CONVERT(VARCHAR(24), CreatedDate, 121) end) as Date_Resolved

Convert .cer certificate to .jks

Just to be sure that this is really the "conversion" you need, please note that jks files are keystores, a file format used to store more than one certificate and allows you to retrieve them programmatically using the Java security API, it's not a one-to-one conversion between equivalent formats.

So, if you just want to import that certificate in a new ad-hoc keystore you can do it with Keystore Explorer, a graphical tool. You'll be able to modify the keystore and the certificates contained therein like you would have done with the java terminal utilities like keytool (but in a more accessible way).

What is the difference between bool and Boolean types in C#

They are one in the same. bool is just an alias for Boolean.

Force uninstall of Visual Studio

If you don't have media, doing a dir /s vs_ultimate.exe from the root prompt will find it. Mine was in C:\ProgramData\Package Cache\{[guid]}. Once I navigated there and ran vs_ultimate.exe with the /uninstall and /force flags, the uninstaller ran

I opened the program "Command Prompt" with as administrator and search run "dir /s vs_ultimate.exe" in ProgramData folder and find path to vs_ultimate.exe file.

Then I changed my working directory to that path and ran vs_ultimate.exe /uninstall /force.

Finally its done.

JOptionPane YES/No Options Confirm Dialog Box Issue

You need to look at the return value of the call to showConfirmDialog. I.E.:

int dialogResult = JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);
if(dialogResult == JOptionPane.YES_OPTION){
  // Saving code here
}

You were testing against dialogButton, which you were using to set the buttons that should be displayed by the dialog, and this variable was never updated - so dialogButton would never have been anything other than JOptionPane.YES_NO_OPTION.

Per the Javadoc for showConfirmDialog:

Returns: an integer indicating the option selected by the user

C++ Array Of Pointers

For example, if you want an array of int pointers it will be int* a[10]. It means that variable a is a collection of 10 int* s.

EDIT

I guess this is what you want to do:

class Bar
{
};

class Foo
{
public:

    //Takes number of bar elements in the pointer array
    Foo(int size_in);

    ~Foo();
    void add(Bar& bar);
private:

    //Pointer to bar array
    Bar** m_pBarArr;

    //Current fee bar index
    int m_index;
};

Foo::Foo(int size_in) : m_index(0)
{
    //Allocate memory for the array of bar pointers
    m_pBarArr = new Bar*[size_in];
}

Foo::~Foo()
{
    //Notice delete[] and not delete
    delete[] m_pBarArr;
    m_pBarArr = NULL;
}

void Foo::add(Bar &bar)
{
    //Store the pointer into the array. 
    //This is dangerous, you are assuming that bar object
    //is valid even when you try to use it
    m_pBarArr[m_index++] = &bar;
}

How to calculate difference between two dates in oracle 11g SQL

Oracle DateDiff is from a different product, probably mysql (which is now owned by Oracle).

The difference between two dates (in oracle's usual database product) is in days (which can have fractional parts). Factor by 24 to get hours, 24*60 to get minutes, 24*60*60 to get seconds (that's as small as dates go). The math is 100% accurate for dates within a couple of hundred years or so. E.g. to get the date one second before midnight of today, you could say

select trunc(sysdate) - 1/24/60/60 from dual;

That means "the time right now", truncated to be just the date (i.e. the midnight that occurred this morning). Then it subtracts a number which is the fraction of 1 day that measures one second. That gives you the date from the previous day with the time component of 23:59:59.

Is it possible to insert multiple rows at a time in an SQLite database?

Yes, sql can do this, but with a different syntax. The sqlite documentation is pretty good, by the way. It will also tell you that the only way to insert several row is use a select statement as the source of the data to be inserted.

MVC - Set selected value of SelectList

Further to @Womp answer, it's worth noting that the "Where" Can be dropped, and the predicate can be put into the "First" call directly, like this:

list.First(x => x.Value == "selectedValue").Selected = true;

WPF loading spinner

This repo on github seems to do the job quite well:

https://github.com/blackspikeltd/Xaml-Spinners-WPF

The spinners are all light weight and can easily be placed wherever needed. There is a sample project included in the repo that shows how to use them.

No nasty code-behinds with a bunch of logic either. If MVVM support is needed, one can just take these and throw them in a Grid with a Visibility binding.