Programs & Examples On #Securityexception

SecurityException indicates a security violation and is thrown when a security error is detected.

The source was not found, but some or all event logs could not be searched

For me this error was due to the command prompt, which was not running under administrator privileges. You need to right click on the command prompt and say "Run as administrator".

You need administrator role to install or uninstall a service.

Android: java.lang.SecurityException: Permission Denial: start Intent

I was running into the same issue and wanted to avoid adding the intent filter as you described. After some digging, I found an xml attribute android:exported that you should add to the activity you would like to be called.

It is by default set to false if no intent filter added to your activity, but if you do have an intent filter it gets set to true.

here is the documentation http://developer.android.com/guide/topics/manifest/activity-element.html#exported

tl;dr: addandroid:exported="true" to your activity in your AndroidManifest.xml file and avoid adding the intent-filter :)

Java SecurityException: signer information does not match

Based on @Mohit Phougat response, if you are running a Groovy with @Grab annotations, you could try to re-order such annotations.

Overloading operators in typedef structs (c++)

Instead of typedef struct { ... } pos; you should be doing struct pos { ... };. The issue here is that you are using the pos type name before it is defined. By moving the name to the top of the struct definition, you are able to use that name within the struct definition itself.

Further, the typedef struct { ... } name; pattern is a C-ism, and doesn't have much place in C++.

To answer your question about inline, there is no difference in this case. When a method is defined within the struct/class definition, it is implicitly declared inline. When you explicitly specify inline, the compiler effectively ignores it because the method is already declared inline.

(inline methods will not trigger a linker error if the same method is defined in multiple object files; the linker will simply ignore all but one of them, assuming that they are all the same implementation. This is the only guaranteed change in behavior with inline methods. Nowadays, they do not affect the compiler's decision regarding whether or not to inline functions; they simply facilitate making the function implementation available in all translation units, which gives the compiler the option to inline the function, if it decides it would be beneficial to do so.)

Using varchar(MAX) vs TEXT on SQL Server

The VARCHAR(MAX) type is a replacement for TEXT. The basic difference is that a TEXT type will always store the data in a blob whereas the VARCHAR(MAX) type will attempt to store the data directly in the row unless it exceeds the 8k limitation and at that point it stores it in a blob.

Using the LIKE statement is identical between the two datatypes. The additional functionality VARCHAR(MAX) gives you is that it is also can be used with = and GROUP BY as any other VARCHAR column can be. However, if you do have a lot of data you will have a huge performance issue using these methods.

In regard to if you should use LIKE to search, or if you should use Full Text Indexing and CONTAINS. This question is the same regardless of VARCHAR(MAX) or TEXT.

If you are searching large amounts of text and performance is key then you should use a Full Text Index.

LIKE is simpler to implement and is often suitable for small amounts of data, but it has extremely poor performance with large data due to its inability to use an index.

Access Session attribute on jstl

You don't need the jsp:useBean to set the model if you already have a controller which prepared the model.

Just access it plain by EL:

<p>${Questions.questionPaperID}</p>
<p>${Questions.question}</p>

or by JSTL <c:out> tag if you'd like to HTML-escape the values or when you're still working on legacy Servlet 2.3 containers or older when EL wasn't supported in template text yet:

<p><c:out value="${Questions.questionPaperID}" /></p>
<p><c:out value="${Questions.question}" /></p>

See also:


Unrelated to the problem, the normal practice is by the way to start attribute name with a lowercase, like you do with normal variable names.

session.setAttribute("questions", questions);

and alter EL accordingly to use ${questions}.

Also note that you don't have any JSTL tag in your code. It's all plain JSP.

How to remove RVM (Ruby Version Manager) from my system

For other shell newbies trying to fix the PATH variable

After following instructions in accepted answer, check and modify your PATH variable if necessary :

env | grep PATH 

if you see "rvm" anywhere, you need to figure out where you are setting PATH and modify. I was setting it in 3 files - so check all the following files:

vim .bashrc  

Delete the lines in the file referencing rvm using the dd command. :wq to save and exit.
source .bashrc to "reload"

Repeat this process (starting with the vim command) for .profile and .bash_profile

fatal error: iostream.h no such file or directory

You should be using iostream without the .h.

Early implementations used the .h variants but the standard mandates the more modern style.

Progress Bar with HTML and CSS

Same as @RoToRa's answer, with a some slight adjustments (correct colors and dimensions):

_x000D_
_x000D_
body {_x000D_
  background-color: #636363;_x000D_
  padding: 1em;_x000D_
}_x000D_
_x000D_
#progressbar {_x000D_
  background-color: #20201F;_x000D_
  border-radius: 20px; /* (heightOfInnerDiv / 2) + padding */_x000D_
  padding: 4px;_x000D_
}_x000D_
_x000D_
#progressbar>div {_x000D_
  background-color: #F7901E;_x000D_
  width: 48%;_x000D_
  /* Adjust with JavaScript */_x000D_
  height: 16px;_x000D_
  border-radius: 10px;_x000D_
}
_x000D_
<div id="progressbar">_x000D_
  <div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here's the fiddle: jsFiddle

And here's what it looks like: jsFiddle-screenshot

how to make twitter bootstrap submenu to open on the left side?

If you're using LESS CSS, I wrote a little mixin to move the dropdown with the connecting arrow:

.dropdown-menu-shift( @num-pixels, @arrow-position: 10px ) {  // mixin to shift the dropdown menu
    left: @num-pixels;
    &:before { left: -@num-pixels + @arrow-position; }        // triangle outline
    &:after  { left: -@num-pixels + @arrow-position + 1px; }  // triangle internal
}

Then to move a .dropdown-menu with an id of dropdown-menu-x for example, you can do:

#dropdown-menu-x {
    .dropdown-menu-shift( -100px );
}

How to call stopservice() method of Service class from the calling activity class

In fact to stopping the service we must use the method stopService() and you are doing in right way:

Start service:

  Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
  startService(myService);

Stop service:

  Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
  stopService(myService);

if you call stopService(), then the method onDestroy() in the service is called (NOT the stopService() method):

  @Override
    public void onDestroy() {
      timer.cancel();
      task.cancel();    
        Log.i(TAG, "onCreate() , service stopped...");
    }

you must implement the onDestroy() method!.

Here is a complete example including how to start/stop the service.

How do I encode a JavaScript object as JSON?

I think you can use JSON.stringify:

// after your each loop
JSON.stringify(values);

How do I check if an object has a specific property in JavaScript?

Use:

_x000D_
_x000D_
var x = {
  'key': 1
};

if ('key' in x) {
  console.log('has');
}
_x000D_
_x000D_
_x000D_

copying all contents of folder to another folder using batch file?

if you want remove the message that tells if the destination is a file or folder you just add a slash:

xcopy /s c:\Folder1 d:\Folder2\

Manage toolbar's navigation and back button from fragment in android

OnToolBar there is a navigation icon at left side

Toolbar  toolbar = (Toolbar) findViewById(R.id.tool_bar);
        toolbar.setTitle(getResources().getString(R.string.title_activity_select_event));
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

By using this at left side navigation icon appear and on navigation icon click it call parent activity.

and in manifest we can notify system about parent activity.

  <activity
            android:name=".CategoryCloudSelectActivity"
            android:parentActivityName=".EventSelectionActivity"
            android:screenOrientation="portrait" />

How to define dimens.xml for every different screen size in android?

In case you want to view more: Here's a link for a list of devices (tablet, mobile, watches), including watch,chromebook, windows and mac. Here you can find the density, dimensions, and etc. Just based it in here, it's a good resource if your using an emulator too.

If you click a specific item, it will show more details in the right side. sample

Since it's Android , I will post related to it. sample1

sample2

~ It's better if you save a copy of the web. To view it offline.

here-document gives 'unexpected end of file' error

The EOF token must be at the beginning of the line, you can't indent it along with the block of code it goes with.

If you write <<-EOF you may indent it, but it must be indented with Tab characters, not spaces. So it still might not end up even with the block of code.

Also make sure you have no whitespace after the EOF token on the line.

Could not load type from assembly error

I experienced the same as above after removing signing of assemblies in the solution. The projects would not build.

I found that one of the projects referenced the StrongNamer NuGet package, which modifies the build process and tries to sign non-signed Nuget packages.

After removing the StrongNamer package I was able to build the project again without signing/strong-naming the assemblies.

Mail multipart/alternative vs multipart/mixed

I hit this challenge today and I found these answers useful but not quite explicit enough for me.

Edit: Just found the Apache Commons Email that wraps this up nicely, meaning you don't need to know below.

If your requirement is an email with:

  1. text and html versions
  2. html version has embedded (inline) images
  3. attachments

The only structure I found that works with Gmail/Outlook/iPad is:

  • mixed
    • alternative
      • text
      • related
        • html
        • inline image
        • inline image
    • attachment
    • attachment

And the code is:

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by StrongMan on 25/05/14.
 */
public class MailContentBuilder {

    private static final Pattern COMPILED_PATTERN_SRC_URL_SINGLE = Pattern.compile("src='([^']*)'",  Pattern.CASE_INSENSITIVE);
    private static final Pattern COMPILED_PATTERN_SRC_URL_DOUBLE = Pattern.compile("src=\"([^\"]*)\"",  Pattern.CASE_INSENSITIVE);

    /**
     * Build an email message.
     *
     * The HTML may reference the embedded image (messageHtmlInline) using the filename. Any path portion is ignored to make my life easier
     * e.g. If you pass in the image C:\Temp\dog.jpg you can use <img src="dog.jpg"/> or <img src="C:\Temp\dog.jpg"/> and both will work
     *
     * @param messageText
     * @param messageHtml
     * @param messageHtmlInline
     * @param attachments
     * @return
     * @throws MessagingException
     */
    public Multipart build(String messageText, String messageHtml, List<URL> messageHtmlInline, List<URL> attachments) throws MessagingException {
        final Multipart mpMixed = new MimeMultipart("mixed");
        {
            // alternative
            final Multipart mpMixedAlternative = newChild(mpMixed, "alternative");
            {
                // Note: MUST RENDER HTML LAST otherwise iPad mail client only renders the last image and no email
                addTextVersion(mpMixedAlternative,messageText);
                addHtmlVersion(mpMixedAlternative,messageHtml, messageHtmlInline);
            }
            // attachments
            addAttachments(mpMixed,attachments);
        }

        //msg.setText(message, "utf-8");
        //msg.setContent(message,"text/html; charset=utf-8");
        return mpMixed;
    }

    private Multipart newChild(Multipart parent, String alternative) throws MessagingException {
        MimeMultipart child =  new MimeMultipart(alternative);
        final MimeBodyPart mbp = new MimeBodyPart();
        parent.addBodyPart(mbp);
        mbp.setContent(child);
        return child;
    }

    private void addTextVersion(Multipart mpRelatedAlternative, String messageText) throws MessagingException {
        final MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(messageText, "text/plain");
        mpRelatedAlternative.addBodyPart(textPart);
    }

    private void addHtmlVersion(Multipart parent, String messageHtml, List<URL> embeded) throws MessagingException {
        // HTML version
        final Multipart mpRelated = newChild(parent,"related");

        // Html
        final MimeBodyPart htmlPart = new MimeBodyPart();
        HashMap<String,String> cids = new HashMap<String, String>();
        htmlPart.setContent(replaceUrlWithCids(messageHtml,cids), "text/html");
        mpRelated.addBodyPart(htmlPart);

        // Inline images
        addImagesInline(mpRelated, embeded, cids);
    }

    private void addImagesInline(Multipart parent, List<URL> embeded, HashMap<String,String> cids) throws MessagingException {
        if (embeded != null)
        {
            for (URL img : embeded)
            {
                final MimeBodyPart htmlPartImg = new MimeBodyPart();
                DataSource htmlPartImgDs = new URLDataSource(img);
                htmlPartImg.setDataHandler(new DataHandler(htmlPartImgDs));
                String fileName = img.getFile();
                fileName = getFileName(fileName);
                String newFileName = cids.get(fileName);
                boolean imageNotReferencedInHtml = newFileName == null;
                if (imageNotReferencedInHtml) continue;
                // Gmail requires the cid have <> around it
                htmlPartImg.setHeader("Content-ID", "<"+newFileName+">");
                htmlPartImg.setDisposition(BodyPart.INLINE);
                parent.addBodyPart(htmlPartImg);
            }
        }
    }

    private void addAttachments(Multipart parent, List<URL> attachments) throws MessagingException {
        if (attachments != null)
        {
            for (URL attachment : attachments)
            {
                final MimeBodyPart mbpAttachment = new MimeBodyPart();
                DataSource htmlPartImgDs = new URLDataSource(attachment);
                mbpAttachment.setDataHandler(new DataHandler(htmlPartImgDs));
                String fileName = attachment.getFile();
                fileName = getFileName(fileName);
                mbpAttachment.setDisposition(BodyPart.ATTACHMENT);
                mbpAttachment.setFileName(fileName);
                parent.addBodyPart(mbpAttachment);
            }
        }
    }

    public String replaceUrlWithCids(String html, HashMap<String,String> cids)
    {
        html = replaceUrlWithCids(html, COMPILED_PATTERN_SRC_URL_SINGLE, "src='cid:@cid'", cids);
        html = replaceUrlWithCids(html, COMPILED_PATTERN_SRC_URL_DOUBLE, "src=\"cid:@cid\"", cids);
        return html;
    }

    private String replaceUrlWithCids(String html, Pattern pattern, String replacement, HashMap<String,String> cids) {
        Matcher matcherCssUrl = pattern.matcher(html);
        StringBuffer sb = new StringBuffer();
        while (matcherCssUrl.find())
        {
            String fileName = matcherCssUrl.group(1);
            // Disregarding file path, so don't clash your filenames!
            fileName = getFileName(fileName);
            // A cid must start with @ and be globally unique
            String cid = "@" + UUID.randomUUID().toString() + "_" + fileName;
            if (cids.containsKey(fileName))
                cid = cids.get(fileName);
            else
                cids.put(fileName,cid);
            matcherCssUrl.appendReplacement(sb,replacement.replace("@cid",cid));
        }
        matcherCssUrl.appendTail(sb);
        html = sb.toString();
        return html;
    }

    private String getFileName(String fileName) {
        if (fileName.contains("/"))
            fileName = fileName.substring(fileName.lastIndexOf("/")+1);
        return fileName;
    }
}

And an example of using it with from Gmail

/**
 * Created by StrongMan on 25/05/14.
 */
import com.sun.mail.smtp.SMTPTransport;

import java.net.URL;
import java.security.Security;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.*;
import javax.mail.internet.*;

/**
 *
 * http://stackoverflow.com/questions/14744197/best-practices-sending-javamail-mime-multipart-emails-and-gmail
 * http://stackoverflow.com/questions/3902455/smtp-multipart-alternative-vs-multipart-mixed
 *
 *
 *
 * @author doraemon
 */
public class GoogleMail {


    private GoogleMail() {
    }

    /**
     * Send email using GMail SMTP server.
     *
     * @param username GMail username
     * @param password GMail password
     * @param recipientEmail TO recipient
     * @param title title of the message
     * @param messageText message to be sent
     * @throws AddressException if the email address parse failed
     * @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
     */
    public static void Send(final String username, final String password, String recipientEmail, String title, String messageText, String messageHtml, List<URL> messageHtmlInline, List<URL> attachments) throws AddressException, MessagingException {
        GoogleMail.Send(username, password, recipientEmail, "", title, messageText, messageHtml, messageHtmlInline,attachments);
    }

    /**
     * Send email using GMail SMTP server.
     *
     * @param username GMail username
     * @param password GMail password
     * @param recipientEmail TO recipient
     * @param ccEmail CC recipient. Can be empty if there is no CC recipient
     * @param title title of the message
     * @param messageText message to be sent
     * @throws AddressException if the email address parse failed
     * @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
     */
    public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String messageText, String messageHtml, List<URL> messageHtmlInline, List<URL> attachments) throws AddressException, MessagingException {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        // Get a Properties object
        Properties props = System.getProperties();
        props.setProperty("mail.smtps.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        props.setProperty("mail.smtps.auth", "true");

        /*
        If set to false, the QUIT command is sent and the connection is immediately closed. If set
        to true (the default), causes the transport to wait for the response to the QUIT command.

        ref :   http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html
                http://forum.java.sun.com/thread.jspa?threadID=5205249
                smtpsend.java - demo program from javamail
        */
        props.put("mail.smtps.quitwait", "false");

        Session session = Session.getInstance(props, null);

        // -- Create a new message --
        final MimeMessage msg = new MimeMessage(session);

        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress(username + "@gmail.com"));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));

        if (ccEmail.length() > 0) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
        }

        msg.setSubject(title);

        // mixed
        MailContentBuilder mailContentBuilder = new MailContentBuilder();
        final Multipart mpMixed = mailContentBuilder.build(messageText, messageHtml, messageHtmlInline, attachments);
        msg.setContent(mpMixed);
        msg.setSentDate(new Date());

        SMTPTransport t = (SMTPTransport)session.getTransport("smtps");

        t.connect("smtp.gmail.com", username, password);
        t.sendMessage(msg, msg.getAllRecipients());
        t.close();
    }

}

div inside php echo

Just wrap it around then.

<?php        
    if ( ($cart->count_product) > 0) 
    { 
        echo "<div class='my_class'>";
        print $cart->count_product; 
        echo "</div>";
    }

?>

WHERE Clause to find all records in a specific month

Using the MONTH and YEAR functions as suggested in most of the responses has the disadvantage that SQL Server will not be able to use any index there may be on your date column. This can kill performance on a large table.

I would be inclined to pass a DATETIME value (e.g. @StartDate) to the stored procedure which represents the first day of the month you are interested in.

You can then use

SELECT ... FROM ...
WHERE DateColumn >= @StartDate 
AND DateColumn < DATEADD(month, 1, @StartDate)

If you must pass the month and year as separate parameters to the stored procedure, you can generate a DATETIME representing the first day of the month using CAST and CONVERT then proceed as above. If you do this I would recommend writing a function that generates a DATETIME from integer year, month, day values, e.g. the following from a SQL Server blog.

create function Date(@Year int, @Month int, @Day int)
returns datetime
as
    begin
    return dateadd(month,((@Year-1900)*12)+@Month-1,@Day-1)
    end
go

The query then becomes:

SELECT ... FROM ...
WHERE DateColumn >= Date(@Year,@Month,1)
AND DateColumn < DATEADD(month, 1, Date(@Year,@Month,1))

How to deal with "data of class uneval" error from ggplot2?

when you add a new data set to a geom you need to use the data= argument. Or put the arguments in the proper order mapping=..., data=.... Take a look at the arguments for ?geom_line.

Thus:

p + geom_line(data=df.last, aes(HrEnd, MWh, group=factor(Date)), color="red") 

Or:

p + geom_line(aes(HrEnd, MWh, group=factor(Date)), df.last, color="red") 

Is there a way to make npm install (the command) to work behind proxy?

A lot of applications (e.g. npm) can use proxy setting from user environment variables.

You can just add to your environment following variables HTTP_PROXY and HTTPS_PROXY that will have the same value for each one

http://user:password@proxyAddress:proxyPort

For example if you have Windows you can add proxy as follow:

How it looks on Windows

Java: Add elements to arraylist with FOR loop where element name has increasing number

There's always some reflection hacks that you can adapt. Here is some example, but using a collection would be the solution to your problem (the integers you stick on your variables name is a good hint telling us you should use a collection!).

public class TheClass {

    private int theField= 42;

    public static void main(String[] args) throws Exception {

        TheClass c= new TheClass();

        System.out.println(c.getClass().getDeclaredField("theField").get(c));
    }
}

How can I remove file extension from a website address?

The problem with creating a directory and keeping index.php in it is that

  1. your links with menu will stop functioning
  2. There will be way too many directories. For eg, there will be a seperate directory for each and every question here on stackoverflow

The solutions are 1. MOD REWRITE (as suggested above) 2. use a php code to dynamically include other files in index file. Read a bit more abt it here http://inobscuro.com/tutorials/read/16/

How to find all occurrences of a substring?

This function does not look at all positions inside the string, it does not waste compute resources. My try:

def findAll(string,word):
    all_positions=[]
    next_pos=-1
    while True:
        next_pos=string.find(word,next_pos+1)
        if(next_pos<0):
            break
        all_positions.append(next_pos)
    return all_positions

to use it call it like this:

result=findAll('this word is a big word man how many words are there?','word')

Returning a boolean from a Bash function

I found the shortest form to test the function output is simply

do_something() {
    [[ -e $1 ]] # e.g. test file exists
}

do_something "myfile.txt" || { echo "File doesn't exist!"; exit 1; }

Execute Stored Procedure from a Function

EDIT: I haven't tried this, so I can't vouch for it! And you already know you shouldn't be doing this, so please don't do it. BUT...

Try looking here: http://sqlblog.com/blogs/denis_gobo/archive/2008/05/08/6703.aspx

The key bit is this bit which I have attempted to tweak for your purposes:

DECLARE @SQL varchar(500)

SELECT @SQL = 'osql -S' +@@servername +' -E -q "exec dbName..sprocName "'

EXEC master..xp_cmdshell @SQL

How to convert float value to integer in php?

Use round()

$float_val = 4.5;

echo round($float_val);

You can also set param for precision and rounding mode, for more info

Update (According to your updated question):

$float_val = 1.0000124668092E+14;
printf('%.0f', $float_val / 1E+14); //Output Rounds Of To 1000012466809201

mongodb/mongoose findMany - find all documents with IDs listed in array

Combining Daniel's and snnsnn's answers:

_x000D_
_x000D_
let ids = ['id1','id2','id3']
let data = await MyModel.find(
  {'_id': { $in: ids}}
);
_x000D_
_x000D_
_x000D_

Simple and clean code. It works and tested against:

"mongodb": "^3.6.0", "mongoose": "^5.10.0",

Any tools to generate an XSD schema from an XML instance document?

You can use an open source and cross-platform option: inst2xsd from Apache's XMLBeans. I find it very useful and easy.

Just download, unzip and play (it requires Java).

How can I use different certificates on specific connections?

I read through LOTS of places online to solve this thing. This is the code I wrote to make it work:

ByteArrayInputStream derInputStream = new ByteArrayInputStream(app.certificateString.getBytes());
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(derInputStream);
String alias = "alias";//cert.getSubjectX500Principal().getName();

KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);
trustStore.setCertificateEntry(alias, cert);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(trustStore, null);
KeyManager[] keyManagers = kmf.getKeyManagers();

TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(trustStore);
TrustManager[] trustManagers = tmf.getTrustManagers();

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
URL url = new URL(someURL);
conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(sslContext.getSocketFactory());

app.certificateString is a String that contains the Certificate, for example:

static public String certificateString=
        "-----BEGIN CERTIFICATE-----\n" +
        "MIIGQTCCBSmgAwIBAgIHBcg1dAivUzANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UE" +
        "BhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBE" +
        ... a bunch of characters...
        "5126sfeEJMRV4Fl2E5W1gDHoOd6V==\n" +
        "-----END CERTIFICATE-----";

I have tested that you can put any characters in the certificate string, if it is self signed, as long as you keep the exact structure above. I obtained the certificate string with my laptop's Terminal command line.

How do I create a Linked List Data Structure in Java?

Java has a LinkedList implementation, that you might wanna check out. You can download the JDK and it's sources at java.sun.com.

PHP $_POST not working?

Try get instead for test reasons

<form action="#?name=test" method="GET">
  <input type="text" name="firstname" />
  <input type="submit" name="submit" value="Submit" />
</form>

and

if(isset($_GET)){
    echo $_GET['name'] . '<br>';
    echo $_GET['firstname'];
}

Is calculating an MD5 hash less CPU intensive than SHA family functions?

MD5 also benefits from SSE2 usage, check out BarsWF and then tell me that it doesn't. All it takes is a little assembler knowledge and you can craft your own MD5 SSE2 routine(s). For large amounts of throughput however, there is a tradeoff of the speed during hashing as opposed to the time spent rearranging the input data to be compatible with the SIMD instructions used.

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

I also had this issue while developping on HTML5 in local. I had issues with images and getImageData function. Finally, I discovered one can launch chrome with the --allow-file-access-from-file command switch, that get rid of this protection security. The only thing is that it makes your browser less safe, and you can't have one chrome instance with the flag on and another without the flag.

Cannot find JavaScriptSerializer in .Net 4.0

Did you include a reference to System.Web.Extensions? If you click on your first link it says which assembly it's in.

How to convert string to string[]?

string[] is an array (vector) of strings string is just a string (a list/array of characters)

Depending on how you want to convert this, the canonical answer could be:

string[] -> string

return String.Join(" ", myStringArray);

string -> string[]

return new []{ myString };

Given URL is not permitted by the application configuration

Settings -> Advanced, add url to "Valid OAuth redirect URIs". This works for me.

npm install error from the terminal

I had this problem when trying to run 'npm install' in a Terminal window which had been opened before installing Node.js.

Opening a new Terminal window (i.e. bash session) worked. (Presumably this provided the correct environment variables for npm to run correctly.)

Vue Js - Loop via v-for X times (in a range)

The same goes for v-for in range:

<li v-for="n in 20 " :key="n">{{n}}</li>

How do I use grep to search the current directory for all files having the a string "hello" yet display only .h and .cc files?

grep -r --include=*.{cc,h} "hello" .

This reads: search recursively (in all sub directories also) for all .cc OR .h files that contain "hello" at this . (current) directory

From another stackoverflow question

jQuery first child of "this"

If you want immediate first child you need

    $(element).first();

If you want particular first element in the dom from your element then use below

    var spanElement = $(elementId).find(".redClass :first");
    $(spanElement).addClass("yourClassHere");

try out : http://jsfiddle.net/vgGbc/2/

What exactly is OAuth (Open Authorization)?

What is oAuth?

OAuth is simply a secure authorization protocol that deals with the authorization of third party application to access the user data without exposing their password. eg. (Login with fb, gPlus, twitter in many websites..) all work under this protocol.

Parties involved

The Protocol becomes easier when you know the involved parties. Basically there are three parties involved: oAuth Provider, oAuth Client and Owner.

  • oAuth Client (Application Which wants to access your credential)
  • oAuth Provider (eg. facebook, twitter...)
  • Owner (the person with facebook,twitter.. account )

How It Works?

I have supposed a scenario where a website(stackoverflow) needs to add login with facebook feature. Thus facebook is oAuth Provider and the stackoverflow is oAuth Client.

  1. This step is done by app's developer. At the very beginning facebook (oAuth Provider) has no idea about the stackoverflow(oAuth Client) because there is no link between them. So the very first step is to register stackoverflow with facebook developers site. This is done manually where developers need to give app's information to facebook like app's name, website, logo, redirect Url(important one). Then stackoverflow is successfully registered, has got client Id, client secret etc from facebook and is up and running with OAUTH. enter image description here

    2.Now when stackoverflow's user clicks login with fb button. Stackoverflow requests facebook with ClientId(fb use it to recognize the client) and redirectUrl(fb will return back to this url after success).Thus the user gets redirected to facebook login page. This is the best part user(owner) is not giving thier facebook credential to stackoverflow.

enter image description here

enter image description here

  1. After Owner allow Stackoverflow to access the information. Then Facebook redirects back to stackoverflow, along with authcode using the redirectUrl provided at step 2.
  2. Then Stackoverflow contacts with facebook along with the obtained authcode to make sure everything is okay.
  3. Only then facebook will give access token to stackoverflow. Then access token is used by stackoverflow to retrive owner's information without using password. This is the whole motive of oAuth, where acutal credentails in never exposed to third party applications.

For More:

Quick video

Web link

Which exception should I raise on bad/illegal argument combinations in Python?

I'm not sure I agree with inheritance from ValueError -- my interpretation of the documentation is that ValueError is only supposed to be raised by builtins... inheriting from it or raising it yourself seems incorrect.

Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

-- ValueError documentation

Android soft keyboard covers EditText field

Why not try to add a ScrollView to wrap whatever it is you want to scroll. Here is how I have done it, where I actually leave a header on top which does not scroll, while the dialog widgets (in particular the EditTexts) scroll when you open soft keypad.

<LinearLayout android:id="@+id/HeaderLayout" >
  <!-- Here add a header or whatever will not be scrolled. -->
</LinearLayout>
<ScrollView android:id="@+id/MainForm" >
  <!-- Here add your edittexts or whatever will scroll. -->
</ScrollView>

I would typically have a LinearLayout inside the ScrollView, but that is up to you. Also, setting Scrollbar style to outsideInset helps, at least on my devices.

Is there a regular expression to detect a valid regular expression?

/
^                                             # start of string
(                                             # first group start
  (?:
    (?:[^?+*{}()[\]\\|]+                      # literals and ^, $
     | \\.                                    # escaped characters
     | \[ (?: \^?\\. | \^[^\\] | [^\\^] )     # character classes
          (?: [^\]\\]+ | \\. )* \]
     | \( (?:\?[:=!]|\?<[=!]|\?>)? (?1)?? \)  # parenthesis, with recursive content
     | \(\? (?:R|[+-]?\d+) \)                 # recursive matching
     )
    (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )?   # quantifiers
  | \|                                        # alternative
  )*                                          # repeat content
)                                             # end first group
$                                             # end of string
/

This is a recursive regex, and is not supported by many regex engines. PCRE based ones should support it.

Without whitespace and comments:

/^((?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>)?(?1)??\)|\(\?(?:R|[+-]?\d+)\))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*)$/

.NET does not support recursion directly. (The (?1) and (?R) constructs.) The recursion would have to be converted to counting balanced groups:

^                                         # start of string
(?:
  (?: [^?+*{}()[\]\\|]+                   # literals and ^, $
   | \\.                                  # escaped characters
   | \[ (?: \^?\\. | \^[^\\] | [^\\^] )   # character classes
        (?: [^\]\\]+ | \\. )* \]
   | \( (?:\?[:=!]
         | \?<[=!]
         | \?>
         | \?<[^\W\d]\w*>
         | \?'[^\W\d]\w*'
         )?                               # opening of group
     (?<N>)                               #   increment counter
   | \)                                   # closing of group
     (?<-N>)                              #   decrement counter
   )
  (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers
| \|                                      # alternative
)*                                        # repeat content
$                                         # end of string
(?(N)(?!))                                # fail if counter is non-zero.

Compacted:

^(?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>|\?<[^\W\d]\w*>|\?'[^\W\d]\w*')?(?<N>)|\)(?<-N>))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*$(?(N)(?!))

From the comments:

Will this validate substitutions and translations?

It will validate just the regex part of substitutions and translations. s/<this part>/.../

It is not theoretically possible to match all valid regex grammars with a regex.

It is possible if the regex engine supports recursion, such as PCRE, but that can't really be called regular expressions any more.

Indeed, a "recursive regular expression" is not a regular expression. But this an often-accepted extension to regex engines... Ironically, this extended regex doesn't match extended regexes.

"In theory, theory and practice are the same. In practice, they're not." Almost everyone who knows regular expressions knows that regular expressions does not support recursion. But PCRE and most other implementations support much more than basic regular expressions.

using this with shell script in the grep command , it shows me some error.. grep: Invalid content of {} . I am making a script that could grep a code base to find all the files that contain regular expressions

This pattern exploits an extension called recursive regular expressions. This is not supported by the POSIX flavor of regex. You could try with the -P switch, to enable the PCRE regex flavor.

Regex itself "is not a regular language and hence cannot be parsed by regular expression..."

This is true for classical regular expressions. Some modern implementations allow recursion, which makes it into a Context Free language, although it is somewhat verbose for this task.

I see where you're matching []()/\. and other special regex characters. Where are you allowing non-special characters? It seems like this will match ^(?:[\.]+)$, but not ^abcdefg$. That's a valid regex.

[^?+*{}()[\]\\|] will match any single character, not part of any of the other constructs. This includes both literal (a - z), and certain special characters (^, $, .).

How to safely open/close files in python 2.4

See docs.python.org:

When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.

Hence use close() elegantly with try/finally:

f = open('file.txt', 'r')

try:
    # do stuff with f
finally:
    f.close()

This ensures that even if # do stuff with f raises an exception, f will still be closed properly.

Note that open should appear outside of the try. If open itself raises an exception, the file wasn't opened and does not need to be closed. Also, if open raises an exception its result is not assigned to f and it is an error to call f.close().

How to generate random positive and negative numbers in Java

Generate numbers between 0 and 65535 then just subtract 32768

Optional args in MATLAB functions

A simple way of doing this is via nargin (N arguments in). The downside is you have to make sure that your argument list and the nargin checks match.

It is worth remembering that all inputs are optional, but the functions will exit with an error if it calls a variable which is not set. The following example sets defaults for b and c. Will exit if a is not present.

function [ output_args ] = input_example( a, b, c )
if nargin < 1
  error('input_example :  a is a required input')
end

if nargin < 2
  b = 20
end

if nargin < 3
  c = 30
end
end

How to get file creation date/time in Bash/Debian?

ls -i menus.xml

94490 menus.xml Here the number 94490 represents inode

Then do a:

df -h

Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/vg-root   4.0G  3.4G  408M  90% /
tmpfs                 1.9G     0  1.9G   0% /dev/shm
/dev/sda1             124M   27M   92M  23% /boot
/dev/mapper/vg-var    7.9G  1.1G  6.5G  15% /var

To find the mounting point of the root "/" filesystem, because the file menus.xml is on '/' that is '/dev/mapper/vg-root'

debugfs -R 'stat <94490>' /dev/mapper/vg-root

The output may be like the one below:

debugfs -R 'stat <94490>' /dev/mapper/vg-root

debugfs 1.41.12 (17-May-2010)
Inode: 94490   Type: regular    Mode:  0644   Flags: 0x0
Generation: 2826123170    Version: 0x00000000
User:     0   Group:     0   Size: 4441
File ACL: 0    Directory ACL: 0
Links: 1   Blockcount: 16
Fragment:  Address: 0    Number: 0    Size: 0
ctime: 0x5266e438 -- Wed Oct 23 09:46:48 2013
atime: 0x5266e47b -- Wed Oct 23 09:47:55 2013
mtime: 0x5266e438 -- Wed Oct 23 09:46:48 2013
Size of extra inode fields: 4
Extended attributes stored in inode body: 
  selinux = "unconfined_u:object_r:usr_t:s0\000" (31)
BLOCKS:
(0-1):375818-375819
TOTAL: 2

Where you can see the creation time:

ctime: 0x5266e438 -- Wed Oct 23 09:46:48 2013

Combine two arrays

https://www.php.net/manual/en/function.array-merge.php

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

How to test if a string contains one of the substrings in a list, in pandas?

Here is a one line lambda that also works:

df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)

Input:

searchfor = ['og', 'at']

df = pd.DataFrame([('cat', 1000.0), ('hat', 2000000.0), ('dog', 1000.0), ('fog', 330000.0),('pet', 330000.0)], columns=['col1', 'col2'])

   col1  col2
0   cat 1000.0
1   hat 2000000.0
2   dog 1000.0
3   fog 330000.0
4   pet 330000.0

Apply Lambda:

df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)

Output:

    col1    col2        TrueFalse
0   cat     1000.0      1
1   hat     2000000.0   1
2   dog     1000.0      1
3   fog     330000.0    1
4   pet     330000.0    0

Multiline strings in VB.NET

Use vbCrLf or vbNewLine. It works with MessageBoxes and many other controls I tested.

Dim str As String
str = "First line" & vbCrLf & "Second line"
MsgBox(str)
str = "First line" & vbNewLine & "Second line"
MsgBox(str)

It will show two identical MessageBoxes with 2 lines.

Python reshape list to ndim array

You can specify the interpretation order of the axes using the order parameter:

np.reshape(arr, (2, -1), order='F')

How to iterate through table in Lua?

For those wondering why ipairs doesn't print all the values of the table all the time, here's why (I would comment this, but I don't have enough good boy points).

The function ipairs only works on tables which have an element with the key 1. If there is an element with the key 1, ipairs will try to go as far as it can in a sequential order, 1 -> 2 -> 3 -> 4 etc until it cant find an element with a key that is the next in the sequence. The order of the elements does not matter.

Tables that do not meet those requirements will not work with ipairs, use pairs instead.

Examples:

ipairsCompatable = {"AAA", "BBB", "CCC"}
ipairsCompatable2 = {[1] = "DDD", [2] = "EEE", [3] = "FFF"}
ipairsCompatable3 = {[3] = "work", [2] = "does", [1] = "this"}

notIpairsCompatable = {[2] = "this", [3] = "does", [4] = "not"}
notIpairsCompatable2 = {[2] = "this", [5] = "doesn't", [24] = "either"}

ipairs will go as far as it can with it's iterations but won't iterate over any other element in the table.

kindofIpairsCompatable = {[2] = 2, ["cool"] = "bro", [1] = 1, [3] = 3, [5] = 5 }

When printing these tables, these are the outputs. I've also included pairs outputs for comparison.

ipairs + ipairsCompatable
1       AAA
2       BBB
3       CCC

ipairs + ipairsCompatable2
1       DDD
2       EEE
3       FFF

ipairs + ipairsCompatable3
1       this
2       does
3       work

ipairs + notIpairsCompatable

pairs + notIpairsCompatable
2       this
3       does
4       not

ipairs + notIpairsCompatable2

pairs + notIpairsCompatable2
2       this
5       doesnt
24      either

ipairs + kindofIpairsCompatable
1       1
2       2
3       3

pairs + kindofIpairsCompatable
1       1
2       2
3       3
5       5
cool    bro

What is the advantage of using REST instead of non-REST HTTP?

Query-strings can be ignored by search engines.

Animate a custom Dialog

First, you have to create two animation resources in res/anim dir

slide_up.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
    android:duration="@android:integer/config_mediumAnimTime"
    android:fromYDelta="100%"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toXDelta="0">
</translate>
</set>

slide_bottom.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate 
    android:duration="@android:integer/config_mediumAnimTime" 
    android:fromYDelta="0%p" 
    android:interpolator="@android:anim/accelerate_interpolator" 
    android:toYDelta="100%p">
</translate>
</set>

then you have to create a style

<style name="DialogAnimation">
    <item name="android:windowEnterAnimation">@anim/slide_up</item>
    <item name="android:windowExitAnimation">@anim/slide_bottom</item>
</style>

and add this line to your class

dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //style id

Based in http://www.devexchanges.info/2015/10/showing-dialog-with-animation-in-android.html

Difference between FetchType LAZY and EAGER in Java Persistence API?

The main difference between the two types of fetching is a moment when data gets loaded into a memory.
I have attached 2 photos to help you understand this.

Eager fetch
 Eager fetch

Lazy fetch Lazy fetch

Write bytes to file

Try this:

private byte[] Hex2Bin(string hex) 
{
 if ((hex == null) || (hex.Length < 1)) {
  return new byte[0];
 }
 int num = hex.Length / 2;
 byte[] buffer = new byte[num];
 num *= 2;
 for (int i = 0; i < num; i++) {
  int num3 = int.Parse(hex.Substring(i, 2), NumberStyles.HexNumber);
  buffer[i / 2] = (byte) num3;
  i++;
 }
 return buffer;
}

private string Bin2Hex(byte[] binary) 
{
 StringBuilder builder = new StringBuilder();
 foreach(byte num in binary) {
  if (num > 15) {
   builder.AppendFormat("{0:X}", num);
  } else {
   builder.AppendFormat("0{0:X}", num); /////// ?? 15 ???? 0
  }
 }
 return builder.ToString();
}

Where is localhost folder located in Mac or Mac OS X?

If you use apachectl to start or stop, then you can find it with this command

apachectl -t -D DUMP_RUN_CFG

missing private key in the distribution certificate on keychain

I got into this situation ("Missing private key.") after Xcode failed to create new distribution certificate - an unknown error occurred.

Then, I struggled to obtain the private key or to generate new certificate. From the certificate manager in Xcode I got strange errors like "The passphrase you entered is wrong". But it did not even ask me for any passphrase.

What helped me was:

  1. Revoke all not-working distribution certificates at developer.apple.com
  2. Restart my Mac

After that, Xcode was able to create new distribution certificate and no private key was missing.

Lesson learned: Restart your Mac as much as your Windows ;)

Generating random whole numbers in JavaScript in a specific range?

function randomRange(min, max) {
  return ~~(Math.random() * (max - min + 1)) + min
}

Alternative if you are using Underscore.js you can use

_.random(min, max)

Python convert csv to xlsx

How I do it with openpyxl lib:

import csv
from openpyxl import Workbook

def convert_csv_to_xlsx(self):
    wb = Workbook()
    sheet = wb.active

    CSV_SEPARATOR = "#"

    with open("my_file.csv") as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader):
            for c, col in enumerate(row):
                for idx, val in enumerate(col.split(CSV_SEPARATOR)):
                    cell = sheet.cell(row=r+1, column=idx+1)
                    cell.value = val

    wb.save("my_file.xlsx")

What is the meaning of "POSIX"?

POSIX is a set of standards put forth by IEEE and The Open Group that describes how an ideal Unix would operate. Programmers, users, and administrators can all become familiar with the POSIX document, and expect a POSIX-complaint Unix to provide all of the standard facilities mentioned.

Since every Unix does things a little differently -- Solaris, Mac OS X, IRIX, BSD, and Linux all have their quirks -- POSIX is especially useful to those in the industry as it defines a standard environment to operate in. For example, most of the functions in the C library are based in POSIX; a programmer can, therefore, use one in his application and expect it to behave the same across most Unices.

However, the divergent areas of Unix are typically the focus, rather than the standard ones.

The great thing about POSIX is that you're welcome to read it yourself:

The Open Group Base Specifications Issue 7

Issue 7 is known as POSIX.1-2008, and there are new things in there -- however, Google-fu for POSIX.1 and such will allow you to see the entire history behind what Unix is.

C++ Dynamic Shared Library on Linux

Basically, you should include the class' header file in the code where you want to use the class in the shared library. Then, when you link, use the '-l' flag to link your code with the shared library. Of course, this requires the .so to be where the OS can find it. See 3.5. Installing and Using a Shared Library

Using dlsym is for when you don't know at compile time which library you want to use. That doesn't sound like it's the case here. Maybe the confusion is that Windows calls the dynamically loaded libraries whether you do the linking at compile or run-time (with analogous methods)? If so, then you can think of dlsym as the equivalent of LoadLibrary.

If you really do need to dynamically load the libraries (i.e., they're plug-ins), then this FAQ should help.

How to initialize an array's length in JavaScript?

[...Array(6)].map(x => 0);
// [0, 0, 0, 0, 0, 0]

OR

Array(6).fill(0);
// [0, 0, 0, 0, 0, 0]

Note: you can't loop empty slots i.e. Array(4).forEach(() => …)


OR

( typescript safe )

Array(6).fill(null).map((_, i) => i);
// [0, 1, 2, 3, 4, 5]

OR

Classic method using a function ( works in any browser )

function NewArray(size) {
    var x = [];
    for (var i = 0; i < size; ++i) {
        x[i] = i;
    }
    return x;
}

var a = NewArray(10);
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Creating nested arrays

When creating a 2D array with the fill intuitively should create new instances. But what actually going to happen is the same array will be stored as a reference.

var a = Array(3).fill([6]);
// [  [6], [6], [6]  ]

a[0].push(9);
// [  [6, 9], [6, 9], [6, 9]  ]

Solution

var a = [...Array(3)].map(x => []);

a[0].push(4, 2);
// [  [4, 2], [], []  ]

So a 3x2 Array will look something like this:

[...Array(3)].map(x => Array(2).fill(0));
// [  [0, 0], [0, 0], [0, 0]  ]

N-dimensional array

function NArray(...dimensions) {
    var index = 0;
    function NArrayRec(dims) {
        var first = dims[0], next = dims.slice().splice(1); 
        if(dims.length > 1) 
            return Array(dims[0]).fill(null).map((x, i) => NArrayRec(next ));
        return Array(dims[0]).fill(null).map((x, i) => (index++));
    }
    return NArrayRec(dimensions);
}

var arr = NArray(3, 2, 4);
// [   [  [ 0,  1,  2,  3 ] , [  4,  5,  6,  7]  ],
//     [  [ 8,  9,  10, 11] , [ 12, 13, 14, 15]  ],
//     [  [ 16, 17, 18, 19] , [ 20, 21, 22, 23]  ]   ]

Initialize a chessboard

var Chessboard = [...Array(8)].map((x, j) => {
    return Array(8).fill(null).map((y, i) => {
        return `${String.fromCharCode(65 + i)}${8 - j}`;
    });
});

// [ [A8, B8, C8, D8, E8, F8, G8, H8],
//   [A7, B7, C7, D7, E7, F7, G7, H7],
//   [A6, B6, C6, D6, E6, F6, G6, H6],
//   [A5, B5, C5, D5, E5, F5, G5, H5],
//   [A4, B4, C4, D4, E4, F4, G4, H4],
//   [A3, B3, C3, D3, E3, F3, G3, H3],
//   [A2, B2, C2, D2, E2, F2, G2, H2],
//   [A1, B1, C1, D1, E1, F1, G1, H1] ]

Math filled values

handy little method overload when working with math


function NewArray( size , method, linear )
{
    method = method || ( i => i ); 
    linear = linear || false;
    var x = [];
    for( var i = 0; i < size; ++i )
        x[ i ] = method( linear ? i / (size-1) : i );
    return x;
}

NewArray( 4 ); 
// [ 0, 1, 2, 3 ]

NewArray( 4, Math.sin ); 
// [ 0, 0.841, 0.909, 0.141 ]

NewArray( 4, Math.sin, true );
// [ 0, 0.327, 0.618, 0.841 ]

var pow2 = ( x ) => x * x;

NewArray( 4, pow2 ); 
// [ 0, 1, 4, 9 ]

NewArray( 4, pow2, true ); 
// [ 0, 0.111, 0.444, 1 ]

How to change Tkinter Button state from disabled to normal?

You simply have to set the state of the your button self.x to normal:

self.x['state'] = 'normal'

or

self.x.config(state="normal")

This code would go in the callback for the event that will cause the Button to be enabled.


Also, the right code should be:

self.x = Button(self.dialog, text="Download", state=DISABLED, command=self.download)
self.x.pack(side=LEFT)

The method pack in Button(...).pack() returns None, and you are assigning it to self.x. You actually want to assign the return value of Button(...) to self.x, and then, in the following line, use self.x.pack().

How to use && in EL boolean expressions in Facelets?

Facelets is a XML based view technology. The & is a special character in XML representing the start of an entity like &amp; which ends with the ; character. You'd need to either escape it, which is ugly:

rendered="#{beanA.prompt == true &amp;&amp; beanB.currentBase != null}"

or to use the and keyword instead, which is preferred as to readability and maintainability:

rendered="#{beanA.prompt == true and beanB.currentBase != null}"

See also:


Unrelated to the concrete problem, comparing booleans with booleans makes little sense when the expression expects a boolean outcome already. I'd get rid of == true:

rendered="#{beanA.prompt and beanB.currentBase != null}"

Making Maven run all tests, even when some fail

Try to add the following configuration for surefire plugin in your pom.xml of root project:

<project>
  [...]
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <testFailureIgnore>true</testFailureIgnore>
        </configuration>
      </plugin>
    </plugins>
  </build>
  [...]
</project>

C++ - how to find the length of an integer

Would this be an efficient approach? Converting to a string and finding the length property?

int num = 123  
string strNum = to_string(num); // 123 becomes "123"
int length = strNum.length(); // length = 3
char array[3]; // or whatever you want to do with the length

How to set a value for a span using jQuery

You can use this:

$("#submittername").html(submitter_name);

How does numpy.histogram() work?

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

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

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

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

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

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


But a picture is worth a thousand words:

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

enter image description here

How to get old Value with onchange() event in text box

element.defaultValue will give you the original value.

Please note that this only works on the initial value.

If you are needing this to persist the "old" value every time it changes, an expando property or similar method will meet your needs

How to round the minute of a datetime object

Here is a simpler generalized solution without floating point precision issues and external library dependencies:

import datetime

def time_mod(time, delta, epoch=None):
    if epoch is None:
        epoch = datetime.datetime(1970, 1, 1, tzinfo=time.tzinfo)
    return (time - epoch) % delta

def time_round(time, delta, epoch=None):
    mod = time_mod(time, delta, epoch)
    if mod < (delta / 2):
       return time - mod
    return time + (delta - mod)

In your case:

>>> tm = datetime.datetime(2010, 6, 10, 3, 56, 23)
>>> time_round(tm, datetime.timedelta(minutes=10))
datetime.datetime(2010, 6, 10, 4, 0)

How to find the mime type of a file in python?

13 year later...
Most of the answers for python 3 on this page are either outdated or incomplete.
To get the mime type of a file on python3 I normally use:

import mimetypes
mt = mimetypes.guess_type("file.ext")[0]

From Python docs:

mimetypes.guess_type(url, strict=True)

Guess the type of a file based on its filename, path or URL, given by url. URL can be a string or a path-like object.

The return value is a tuple (type, encoding) where type is None if the type can’t be guessed (missing or unknown suffix) or a string of the form 'type/subtype', usable for a MIME content-type header.

encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The encoding is suitable for use as a Content-Encoding header, not as a Content-Transfer-Encoding header. The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitively, then case insensitively.

The optional strict argument is a flag specifying whether the list of known MIME types is limited to only the official types registered with IANA. When strict is True (the default), only the IANA types are supported; when strict is False, some additional non-standard but commonly used MIME types are also recognized.

Changed in version 3.8: Added support for url being a path-like object.

Add a list item through javascript

I was recently presented with this same challenge and stumbled on this thread but found a simpler solution using append...

var firstname = $('#firstname').val();

$('ol').append( '<li>' + firstname + '</li>' );

Store the firstname value and then use append to add that value as an li to the ol. I hope this helps :)

How do you receive a url parameter with a spring controller mapping

You have a lot of variants for using @RequestParam with additional optional elements, e.g.

@RequestParam(required = false, defaultValue = "someValue", value="someAttr") String someAttr

If you don't put required = false - param will be required by default.

defaultValue = "someValue" - the default value to use as a fallback when the request parameter is not provided or has an empty value.

If request and method param are the same - you don't need value = "someAttr"

How to add a tooltip to an svg graphic?

On svg, the right way to write the title

<svg>
  <title id="unique-id">Checkout</title>
</svg>

check here for more details https://css-tricks.com/svg-title-vs-html-title-attribute/

Selecting Values from Oracle Table Variable / Array?

In Oracle, the PL/SQL and SQL engines maintain some separation. When you execute a SQL statement within PL/SQL, it is handed off to the SQL engine, which has no knowledge of PL/SQL-specific structures like INDEX BY tables.

So, instead of declaring the type in the PL/SQL block, you need to create an equivalent collection type within the database schema:

CREATE OR REPLACE TYPE array is table of number;
/

Then you can use it as in these two examples within PL/SQL:

SQL> l
  1  declare
  2    p  array := array();
  3  begin
  4    for i in (select level from dual connect by level < 10) loop
  5      p.extend;
  6      p(p.count) := i.level;
  7    end loop;
  8    for x in (select column_value from table(cast(p as array))) loop
  9       dbms_output.put_line(x.column_value);
 10    end loop;
 11* end;
SQL> /
1
2
3
4
5
6
7
8
9

PL/SQL procedure successfully completed.

SQL> l
  1  declare
  2    p  array := array();
  3  begin
  4    select level bulk collect into p from dual connect by level < 10;
  5    for x in (select column_value from table(cast(p as array))) loop
  6       dbms_output.put_line(x.column_value);
  7    end loop;
  8* end;
SQL> /
1
2
3
4
5
6
7
8
9

PL/SQL procedure successfully completed.

Additional example based on comments

Based on your comment on my answer and on the question itself, I think this is how I would implement it. Use a package so the records can be fetched from the actual table once and stored in a private package global; and have a function that returns an open ref cursor.

CREATE OR REPLACE PACKAGE p_cache AS
  FUNCTION get_p_cursor RETURN sys_refcursor;
END p_cache;
/

CREATE OR REPLACE PACKAGE BODY p_cache AS

  cache_array  array;

  FUNCTION get_p_cursor RETURN sys_refcursor IS
    pCursor  sys_refcursor;
  BEGIN
    OPEN pCursor FOR SELECT * from TABLE(CAST(cache_array AS array));
    RETURN pCursor;
  END get_p_cursor;

  -- Package initialization runs once in each session that references the package
  BEGIN
    SELECT level BULK COLLECT INTO cache_array FROM dual CONNECT BY LEVEL < 10;
  END p_cache;
/

Java JDBC connection status

You also can use

public boolean isDbConnected(Connection con) {
    try {
        return con != null && !con.isClosed();
    } catch (SQLException ignored) {}

    return false;
}

Find all controls in WPF Window by type

Do note that using the VisualTreeHelper does only work on controls that derive from Visual or Visual3D. If you also need to inspect other elements (e.g. TextBlock, FlowDocument etc.), using VisualTreeHelper will throw an exception.

Here's an alternative that falls back to the logical tree if necessary:

http://www.hardcodet.net/2009/06/finding-elements-in-wpf-tree-both-ways

enum - getting value of enum on string conversion

You are printing the enum object. Use the .value attribute if you wanted just to print that:

print(D.x.value)

See the Programmatic access to enumeration members and their attributes section:

If you have an enum member and need its name or value:

>>>
>>> member = Color.red
>>> member.name
'red'
>>> member.value
1

You could add a __str__ method to your enum, if all you wanted was to provide a custom string representation:

class D(Enum):
    def __str__(self):
        return str(self.value)

    x = 1
    y = 2

Demo:

>>> from enum import Enum
>>> class D(Enum):
...     def __str__(self):
...         return str(self.value)
...     x = 1
...     y = 2
... 
>>> D.x
<D.x: 1>
>>> print(D.x)
1

Variably modified array at file scope

It is also possible to use enumeration.

typedef enum {
    typeNo1 = 1,
    typeNo2,
    typeNo3,
    typeNo4,
    NumOfTypes = typeNo4
}  TypeOfSomething;

Creating the Singleton design pattern in PHP5

/**
 * Singleton class
 *
 */
final class UserFactory
{
    /**
     * Call this method to get singleton
     *
     * @return UserFactory
     */
    public static function Instance()
    {
        static $inst = null;
        if ($inst === null) {
            $inst = new UserFactory();
        }
        return $inst;
    }

    /**
     * Private ctor so nobody else can instantiate it
     *
     */
    private function __construct()
    {

    }
}

To use:

$fact = UserFactory::Instance();
$fact2 = UserFactory::Instance();

$fact == $fact2;

But:

$fact = new UserFactory()

Throws an error.

See http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static to understand static variable scopes and why setting static $inst = null; works.

Using LINQ to group by multiple properties and sum

Use the .Select() after grouping:

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyContractID, // required by your view model. should be omited
                                            // in most cases because group by primary key
                                            // makes no sense.
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyContractID = ac.Key.AgencyContractID,
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Amount = ac.Sum(acs => acs.Amount),
                       Fee = ac.Sum(acs => acs.Fee)
                   });

What are .tpl files? PHP, web design

In this specific case it is Smarty, but it could also be Jinja2 templates. They usually also have a .tpl extension.

Angular ng-if not true

you are not using the $scope you must use $ctrl.area or $scope.area instead of area

Initializing a list to a known number of elements in Python

Wanting to initalize an array of fixed size is a perfectly acceptable thing to do in any programming language; it isn't like the programmer wants to put a break statement in a while(true) loop. Believe me, especially if the elements are just going to be overwritten and not merely added/subtracted, like is the case of many dynamic programming algorithms, you don't want to mess around with append statements and checking if the element hasn't been initialized yet on the fly (that's a lot of code gents).

object = [0 for x in range(1000)]

This will work for what the programmer is trying to achieve.

Sorting data based on second column of a file

For tab separated values the code below can be used

sort -t$'\t' -k2 -n

-r can be used for getting data in descending order.
-n for numerical sort
-k, --key=POS1[,POS2] where k is column in file
For descending order below is the code

sort -t$'\t' -k2 -rn

How to break out of nested loops?

I think goto will solve the problem

for(int i = 0; i < 1000; i++) {
    for(int j = 0; j < 1000; j++) {
        if (condition) {
            goto end;
        }
    }
}

end:
stmt2 

 

How to get number of rows inserted by a transaction

In case you need further info for your log/audit you can OUTPUT clause: This way, not only you keep the number of rows affected, but also what records.

As an example of the Output Clause during inserts: SQL Server list of insert identities

DECLARE @InsertedIDs table(ID int);

INSERT INTO YourTable
    OUTPUT INSERTED.ID
        INTO @InsertedIDs 
    SELECT ...

HTH

Should I use PATCH or PUT in my REST API?

The R in REST stands for resource

(Which isn't true, because it stands for Representational, but it's a good trick to remember the importance of Resources in REST).

About PUT /groups/api/v1/groups/{group id}/status/activate: you are not updating an "activate". An "activate" is not a thing, it's a verb. Verbs are never good resources. A rule of thumb: if the action, a verb, is in the URL, it probably is not RESTful.

What are you doing instead? Either you are "adding", "removing" or "updating" an activation on a Group, or if you prefer: manipulating a "status"-resource on a Group. Personally, I'd use "activations" because they are less ambiguous than the concept "status": creating a status is ambiguous, creating an activation is not.

  • POST /groups/{group id}/activation Creates (or requests the creation of) an activation.
  • PATCH /groups/{group id}/activation Updates some details of an existing activation. Since a group has only one activation, we know what activation-resource we are referring to.
  • PUT /groups/{group id}/activation Inserts-or-replaces the old activation. Since a group has only one activation, we know what activation-resource we are referring to.
  • DELETE /groups/{group id}/activation Will cancel, or remove the activation.

This pattern is useful when the "activation" of a Group has side-effects, such as payments being made, mails being sent and so on. Only POST and PATCH may have such side-effects. When e.g. a deletion of an activation needs to, say, notify users over mail, DELETE is not the right choice; in that case you probably want to create a deactivation resource: POST /groups/{group_id}/deactivation.

It is a good idea to follow these guidelines, because this standard contract makes it very clear for your clients, and all the proxies and layers between the client and you, know when it is safe to retry, and when not. Let's say the client is somewhere with flaky wifi, and its user clicks on "deactivate", which triggers a DELETE: If that fails, the client can simply retry, until it gets a 404, 200 or anything else it can handle. But if it triggers a POST to deactivation it knows not to retry: the POST implies this.
Any client now has a contract, which, when followed, will protect against sending out 42 emails "your group has been deactivated", simply because its HTTP-library kept retrying the call to the backend.

Updating a single attribute: use PATCH

PATCH /groups/{group id}

In case you wish to update an attribute. E.g. the "status" could be an attribute on Groups that can be set. An attribute such as "status" is often a good candidate to limit to a whitelist of values. Examples use some undefined JSON-scheme:

PATCH /groups/{group id} { "attributes": { "status": "active" } }
response: 200 OK

PATCH /groups/{group id} { "attributes": { "status": "deleted" } }
response: 406 Not Acceptable

Replacing the resource, without side-effects use PUT.

PUT /groups/{group id}

In case you wish to replace an entire Group. This does not necessarily mean that the server actually creates a new group and throws the old one out, e.g. the ids might remain the same. But for the clients, this is what PUT can mean: the client should assume he gets an entirely new item, based on the server's response.

The client should, in case of a PUT request, always send the entire resource, having all the data that is needed to create a new item: usually the same data as a POST-create would require.

PUT /groups/{group id} { "attributes": { "status": "active" } }
response: 406 Not Acceptable

PUT /groups/{group id} { "attributes": { "name": .... etc. "status": "active" } }
response: 201 Created or 200 OK, depending on whether we made a new one.

A very important requirement is that PUT is idempotent: if you require side-effects when updating a Group (or changing an activation), you should use PATCH. So, when the update results in e.g. sending out a mail, don't use PUT.

How to uncommit my last commit in Git

Be careful with that.

But you can use the rebase command

git rebase -i HEAD~2

A vi will open and all you have to do is delete the line with the commit. Also can read instructions that were shown in proper edition @ vi. A couple of things can be performed on this mode.

Add Items to ListView - Android

public OnClickListener moreListener = new OnClickListener() {

    @Override
      public void onClick(View v) {
          adapter.add("aaaa")
      }
}

How to set focus to a button widget programmatically?

Try this:

btn.requestFocusFromTouch();

How can I drop a "not null" constraint in Oracle when I don't know the name of the constraint?

To discover any constraints used, use the code below:

-- Set the long data type for display purposes to 500000.

SET LONG 500000

-- Define a session scope variable.

VARIABLE output CLOB

-- Query the table definition through the <code>DBMS_METADATA</code> package.

SELECT dbms_metadata.get_ddl('TABLE','[Table Described]') INTO :output FROM dual;

This essentially shows a create statement for how the referenced table is made. By knowing how the table is created, you can see all of the table constraints.

Answer taken from Michael McLaughlin's blog: http://michaelmclaughlin.info/db1/lesson-5-querying-data/lab-5-querying-data/ From his Database Design I class.

What linux shell command returns a part of a string?

expr(1) has a substr subcommand:

expr substr <string> <start-index> <length>

This may be useful if you don't have bash (perhaps embedded Linux) and you don't want the extra "echo" process you need to use cut(1).

Application_Start not firing?

I have just the same problem. I have made a lot of renaming in my solution. After it I got two not working web-applications and several another web-applications were all right. I got error that I have wrong routes. When I have tried to setup break point in Application_Start method, and then restart IIS, VS didn't break execution. With workable web-applications break was working. Then I have recalled that "clean solution" and "rebuild" doesn't delete assemblies that left after renaming. And that was solution! I have manually cleaned bin directories of my buggy-web-applications and then saw new error in Global.asax Inherits="" attribute was referenced old dll. I have changed it on new and break began to work. Suppose that, during renaming Global.asax wasn't updated, and IIS took old assembly (with wrong routes) to start application.

Why I can't change directories using "cd"?

When you fire a shell script, it runs a new instance of that shell (/bin/bash). Thus, your script just fires up a shell, changes the directory and exits. Put another way, cd (and other such commands) within a shell script do not affect nor have access to the shell from which they were launched.

Overflow:hidden dots at the end

Yes, via the text-overflow property in CSS 3. Caveat: it is not universally supported yet in browsers.

Android SQLite Example

Sqlite helper class helps us to manage database creation and version management. SQLiteOpenHelper takes care of all database management activities. To use it,
1.Override onCreate(), onUpgrade() methods of SQLiteOpenHelper. Optionally override onOpen() method.
2.Use this subclass to create either a readable or writable database and use the SQLiteDatabase's four API methods insert(), execSQL(), update(), delete() to create, read, update and delete rows of your table.

Example to create a MyEmployees table and to select and insert records:

public class MyDatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "DBName";

    private static final int DATABASE_VERSION = 2;

    // Database creation sql statement
    private static final String DATABASE_CREATE = "create table MyEmployees
                                 ( _id integer primary key,name text not null);";

    public MyDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Method is called during creation of the database
    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
    }

    // Method is called during an upgrade of the database,
    @Override
    public void onUpgrade(SQLiteDatabase database,int oldVersion,int newVersion){
        Log.w(MyDatabaseHelper.class.getName(),
                         "Upgrading database from version " + oldVersion + " to "
                         + newVersion + ", which will destroy all old data");
        database.execSQL("DROP TABLE IF EXISTS MyEmployees");
        onCreate(database);
    }
}

Now you can use this class as below,

public class MyDB{  

    private MyDatabaseHelper dbHelper;  

    private SQLiteDatabase database;  

    public final static String EMP_TABLE="MyEmployees"; // name of table 

    public final static String EMP_ID="_id"; // id value for employee
    public final static String EMP_NAME="name";  // name of employee

    /** 
     * 
     * @param context 
     */  
    public MyDB(Context context){  
        dbHelper = new MyDatabaseHelper(context);  
        database = dbHelper.getWritableDatabase();  
    }


    public long createRecords(String id, String name){  
        ContentValues values = new ContentValues();  
        values.put(EMP_ID, id);  
        values.put(EMP_NAME, name);  
        return database.insert(EMP_TABLE, null, values);  
    }    

    public Cursor selectRecords() {
        String[] cols = new String[] {EMP_ID, EMP_NAME};  
        Cursor mCursor = database.query(true, EMP_TABLE,cols,null  
            , null, null, null, null, null);  
        if (mCursor != null) {  
            mCursor.moveToFirst();  
        }  
        return mCursor; // iterate to get each value.
    }
}

Now you can use MyDB class in you activity to have all the database operations. The create records will help you to insert the values similarly you can have your own functions for update and delete.

Android Studio and Gradle build error

If you are using the Gradle Wrapper (the recommended option in Android Studio), you enable stacktrace by running gradlew compileDebug --stacktrace from the command line in the root folder of your project (where the gradlew file is).

If you are not using the gradle wrapper, you use gradle compileDebug --stacktrace instead (presumably).

You don't really need to run with --stacktrace though, running gradlew compileDebug by itself, from the command line, should tell you where the error is.

I based this information on this comment:

Android Studio new project can not run, throwing error

Forcing Internet Explorer 9 to use standards document mode

I tried with an alternate method:

Hit F12 key Then, at right hand side in the drop down menu, select internet explorer version 9.

That's it and it worked for me.

Drop-down menu that opens up/upward with pure css

Add bottom:100% to your #menu:hover ul li:hover ul rule

Demo 1

#menu:hover ul li:hover ul {
    position: absolute;
    margin-top: 1px;
    font: 10px;
    bottom: 100%; /* added this attribute */
}

Or better yet to prevent the submenus from having the same effect, just add this rule

Demo 2

#menu>ul>li:hover>ul { 
    bottom:100%;
}

Demo 3

source: http://jsfiddle.net/W5FWW/4/

And to get back the border you can add the following attribute

#menu>ul>li:hover>ul { 
    bottom:100%;
    border-bottom: 1px solid transparent
}

What is the time complexity of indexing, inserting and removing from common data structures?

Red-Black trees:

  • Insert - O(log n)
  • Retrieve - O(log n)
  • Delete - O(log n)

Document Root PHP

Yes, on the server side $_SERVER['DOCUMENT_ROOT'] is equivalent to / on the client side.

For example: the value of "{$_SERVER['DOCUMENT_ROOT']}/images/thumbnail.png" will be the string /var/www/html/images/thumbnail.png on a server where it's local file at that path can be reached from the client side at the url http://example.com/images/thumbnail.png

No, in other words the value of $_SERVER['DOCUMENT_ROOT'] is not / rather it is the server's local path to what the server shows the client at example.com/

note: $_SERVER['DOCUMENT_ROOT'] does not include a trailing /

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

Make sure you're not telling IIS to check and see if a file exists before serving it up. This one has bitten me a couple times. Do the following:

Open IIS manager. Right click on your MVC website and click properties. Open the Virtual Directory tab. Click the Configuration... button. Under Wildcard application maps, make sure you have a mapping to c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll. MAKE SURE "Verify the file exists" IS NOT CHECKED!

How to resolve cURL Error (7): couldn't connect to host?

This issue can also be caused by making curl calls to https when it is not configured on the remote device. Calling over http can resolve this problem in these situations, at least until you configure ssl on the remote.

Calculating Page Load Time In JavaScript

Don't ever use the setInterval or setTimeout functions for time measuring! They are unreliable, and it is very likely that the JS execution scheduling during a documents parsing and displaying is delayed.

Instead, use the Date object to create a timestamp when you page began loading, and calculate the difference to the time when the page has been fully loaded:

<doctype html>
<html>
    <head>
        <script type="text/javascript">
            var timerStart = Date.now();
        </script>
        <!-- do all the stuff you need to do -->
    </head>
    <body>
        <!-- put everything you need in here -->

        <script type="text/javascript">
             $(document).ready(function() {
                 console.log("Time until DOMready: ", Date.now()-timerStart);
             });
             $(window).load(function() {
                 console.log("Time until everything loaded: ", Date.now()-timerStart);
             });
        </script>
    </body>
</html>

How to for each the hashmap?

Lambda Expression Java 8

In Java 1.8 (Java 8) this has become lot easier by using forEach method from Aggregate operations(Stream operations) that looks similar to iterators from Iterable Interface.

Just copy paste below statement to your code and rename the HashMap variable from hm to your HashMap variable to print out key-value pair.

HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
/*
 *     Logic to put the Key,Value pair in your HashMap hm
 */

// Print the key value pair in one line.
hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));

Here is an example where a Lambda Expression is used:

    HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
    Random rand = new Random(47);
    int i=0;
    while(i<5){
        i++;
        int key = rand.nextInt(20);
        int value = rand.nextInt(50);
        System.out.println("Inserting key: "+key+" Value: "+value);
        Integer imap =hm.put(key,value);
        if( imap == null){
            System.out.println("Inserted");
        }
        else{
            System.out.println("Replaced with "+imap);
        }               
    }

    hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));

Output:

Inserting key: 18 Value: 5
Inserted
Inserting key: 13 Value: 11
Inserted
Inserting key: 1 Value: 29
Inserted
Inserting key: 8 Value: 0
Inserted
Inserting key: 2 Value: 7
Inserted
key: 1 value:29
key: 18 value:5
key: 2 value:7
key: 8 value:0
key: 13 value:11

Also one can use Spliterator for the same.

Spliterator sit = hm.entrySet().spliterator();

UPDATE


Including documentation links to Oracle Docs. For more on Lambda go to this link and must read Aggregate Operations and for Spliterator go to this link.

php resize image on upload

I followed the steps at https://www.w3schools.com/php/php_file_upload.asp and http://www.w3bees.com/2013/03/resize-image-while-upload-using-php.html to produce this solution:

In my view (I am using the MVC paradigm, but it could be your .html or .php file, or the technology that you use for your front-end):

<form action="../../photos/upload.php" method="post" enctype="multipart/form-data">
<label for="quantity">Width:</label>
  <input type="number" id="picture_width" name="picture_width" min="10" max="800" step="1" value="500">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

My upload.php:

<?php
/* Get original image x y*/
list($w, $h) = getimagesize($_FILES['fileToUpload']['tmp_name']);
$new_height=$h*$_POST['picture_width']/$w;
/* calculate new image size with ratio */
$ratio = max($_POST['picture_width']/$w, $new_height/$h);
$h = ceil($new_height / $ratio);
$x = ($w - $_POST['picture_width'] / $ratio) / 2;
$w = ceil($_POST['picture_width'] / $ratio);
/* new file name */
//$path = 'uploads/'.$_POST['picture_width'].'x'.$new_height.'_'.basename($_FILES['fileToUpload']['name']);
$path = 'uploads/'.basename($_FILES['fileToUpload']['name']);
/* read binary data from image file */
$imgString = file_get_contents($_FILES['fileToUpload']['tmp_name']);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($_POST['picture_width'], $new_height);
imagecopyresampled($tmp, $image,
    0, 0,
    $x, 0,
    $_POST['picture_width'], $new_height,
    $w, $h);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($path,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        //echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        //echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($path)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
} else {
    /* Save image */
    switch ($_FILES['fileToUpload']['type']) {
        case 'image/jpeg':
            imagejpeg($tmp, $path, 100);
            break;
        case 'image/png':
            imagepng($tmp, $path, 0);
            break;
        case 'image/gif':
            imagegif($tmp, $path);
            break;
        default:
            exit;
            break;
    }
    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    /* cleanup memory */
    imagedestroy($image);
    imagedestroy($tmp);
}
?>

The name of the folder where pictures are stored is called 'uploads/'. You need to have that folder previously created and that is where you will see your pictures. It works great for me.

NOTE: This is my form:

enter image description here

The code is uploading and resizing pictures properly. I used this link as a guide: http://www.w3bees.com/2013/03/resize-image-while-upload-using-php.html. I modified it because in that code they specify both width and height of resized pictures. In my case, I only wanted to specify width. The height I automatically calculated it proportionally, just keeping proper picture proportions. Everything works perfectly. I hope this helps.

SQL Server: Get data for only the past year

The other suggestions are good if you have "SQL only".

However I suggest, that - if possible - you calculate the date in your program and insert it as string in the SQL query.

At least for for big tables (i.e. several million rows, maybe combined with joins) that will give you a considerable speed improvement as the optimizer can work with that much better.

How should I call 3 functions in order to execute them one after the other?

I believe the async library will provide you a very elegant way to do this. While promises and callbacks can get a little hard to juggle with, async can give neat patterns to streamline your thought process. To run functions in serial, you would need to put them in an async waterfall. In async lingo, every function is called a task that takes some arguments and a callback; which is the next function in the sequence. The basic structure would look something like:

async.waterfall([
  // A list of functions
  function(callback){
      // Function no. 1 in sequence
      callback(null, arg);
  },
  function(arg, callback){
      // Function no. 2 in sequence
      callback(null);
  }
],    
function(err, results){
   // Optional final callback will get results for all prior functions
});

I've just tried to briefly explain the structure here. Read through the waterfall guide for more information, it's pretty well written.

jQuery post() with serialize and extra data

An alternative solution, in case you are needing to do this on an ajax file upload:

var data = new FormData( $('#form')[0] ).append( 'name' , value );

OR even simpler.

$('form').on('submit',function(e){

    e.preventDefault();
    var data = new FormData( this ).append('name', value );

    // ... your ajax code here ...

    return false;

});

Setting an int to Infinity in C++

Integers are inherently finite. The closest you can get is by setting a to int's maximum value:

#include <limits>

// ...

int a = std::numeric_limits<int>::max();

Which would be 2^31 - 1 (or 2 147 483 647) if int is 32 bits wide on your implementation.

If you really need infinity, use a floating point number type, like float or double. You can then get infinity with:

double a = std::numeric_limits<double>::infinity();

How to get a property value based on the name

In addition other guys answer, its Easy to get property value of any object by use Extension method like:

public static class Helper
    {
        public static object GetPropertyValue(this object T, string PropName)
        {
            return T.GetType().GetProperty(PropName) == null ? null : T.GetType().GetProperty(PropName).GetValue(T, null);
        }

    }

Usage is:

Car foo = new Car();
var balbal = foo.GetPropertyValue("Make");

RegEx pattern any two letters followed by six numbers

You could try something like this:

[a-zA-Z]{2}[0-9]{6}

Here is a break down of the expression:

[a-zA-Z]    # Match a single character present in the list below
               # A character in the range between “a” and “z”
               # A character in the range between “A” and “Z”
   {2}         # Exactly 2 times
[0-9]       # Match a single character in the range between “0” and “9”
   {6}         # Exactly 6 times

This will match anywhere in a subject. If you need boundaries around the subject then you could do either of the following:

^[a-zA-Z]{2}[0-9]{6}$

Which ensures that the whole subject matches. I.e there is nothing before or after the subject.

or

\b[a-zA-Z]{2}[0-9]{6}\b

which ensures there is a word boundary on each side of the subject.

As pointed out by @Phrogz, you could make the expression more terse by replacing the [0-9] for a \d as in some of the other answers.

[a-zA-Z]{2}\d{6}

How to stop a goroutine

EDIT: I wrote this answer up in haste, before realizing that your question is about sending values to a chan inside a goroutine. The approach below can be used either with an additional chan as suggested above, or using the fact that the chan you have already is bi-directional, you can use just the one...

If your goroutine exists solely to process the items coming out of the chan, you can make use of the "close" builtin and the special receive form for channels.

That is, once you're done sending items on the chan, you close it. Then inside your goroutine you get an extra parameter to the receive operator that shows whether the channel has been closed.

Here is a complete example (the waitgroup is used to make sure that the process continues until the goroutine completes):

package main

import "sync"
func main() {
    var wg sync.WaitGroup
    wg.Add(1)

    ch := make(chan int)
    go func() {
        for {
            foo, ok := <- ch
            if !ok {
                println("done")
                wg.Done()
                return
            }
            println(foo)
        }
    }()
    ch <- 1
    ch <- 2
    ch <- 3
    close(ch)

    wg.Wait()
}

Global Variable from a different file Python

Importing file2 in file1.py makes the global (i.e., module level) names bound in file2 available to following code in file1 -- the only such name is SomeClass. It does not do the reverse: names defined in file1 are not made available to code in file2 when file1 imports file2. This would be the case even if you imported the right way (import file2, as @nate correctly recommends) rather than in the horrible, horrible way you're doing it (if everybody under the Sun forgot the very existence of the construct from ... import *, life would be so much better for everybody).

Apparently you want to make global names defined in file1 available to code in file2 and vice versa. This is known as a "cyclical dependency" and is a terrible idea (in Python, or anywhere else for that matter).

So, rather than showing you the incredibly fragile, often unmaintainable hacks to achieve (some semblance of) a cyclical dependency in Python, I'd much rather discuss the many excellent way in which you can avoid such terrible structure.

For example, you could put global names that need to be available to both modules in a third module (e.g. file3.py, to continue your naming streak;-) and import that third module into each of the other two (import file3 in both file1 and file2, and then use file3.foo etc, that is, qualified names, for the purpose of accessing or setting those global names from either or both of the other modules, not barenames).

Of course, more and more specific help could be offered if you clarified (by editing your Q) exactly why you think you need a cyclical dependency (just one easy prediction: no matter what makes you think you need a cyclical dependency, you're wrong;-).

Python: SyntaxError: keyword can't be an expression

It's python source parser failure on sum.up=False named argument as sum.up is not valid argument name (you can't use dots -- only alphanumerics and underscores in argument names).

How to create a MySQL hierarchical recursive query?

Based on the @trincot answer, very good explained, I use WITH RECURSIVE () statement to create a breadcrumb using id of the current page and go backwards in the hierarchy to find the every parent in my route table.

So, the @trincot solution is adapted here in the opposite direction to find parents instead of descendants.

I also added depth value which is usefull to invert result order (otherwise the breadcrumb would be upside down).

WITH RECURSIVE cte (
    `id`,
    `title`,
    `url`,
    `icon`,
    `class`,
    `parent_id`,
    `depth`
) AS (
    SELECT   
        `id`,
        `title`,
        `url`,
        `icon`,
        `class`,
        `parent_id`,
        1 AS `depth` 
    FROM     `route`
    WHERE    `id` = :id
      
    UNION ALL 
    SELECT 
        P.`id`,
        P.`title`,
        P.`url`,
        P.`icon`,
        P.`class`,
        P.`parent_id`,
        `depth` + 1
    FROM `route` P
        
    INNER JOIN cte
        ON P.`id` = cte.`parent_id`
)
SELECT * FROM cte ORDER BY `depth` DESC;

Before upgrade to mySQL 8+, I was using vars but it's deprecated and no more working on my 8.0.22 version !

EDIT 2021-02-19 : Example for hierarchical menu

After @david comment I decided to try to make a full hierarchical menu with all nodes and sorted as I want (with sorting column which sort items in each depth). Very usefull for my user/authorization matrix page.

This really simplifies my old version with one query on each depth (PHP loops).

ERP authroization Matrix

This example intergrates an INNER JOIN with url table to filter route by website (multi-websites CMS system).

You can see the essential path column that contains CONCAT() function to sort the menu in the right way.

SELECT R.* FROM (
    WITH RECURSIVE cte (
        `id`,
        `title`,
        `url`,
        `icon`,
        `class`,
        `parent`,
        `depth`,
        `sorting`,
        `path`
    ) AS (
        SELECT 
            `id`,
            `title`,
            `url`,
            `icon`,
            `class`,
            `parent`,
            1 AS `depth`,
            `sorting`,
            CONCAT(`sorting`, ' ' , `title`) AS `path`
        FROM `route`
        WHERE `parent` = 0
        UNION ALL SELECT 
            D.`id`,
            D.`title`,
            D.`url`,
            D.`icon`,
            D.`class`,
            D.`parent`,
            `depth` + 1,
            D.`sorting`,
            CONCAT(cte.`path`, ' > ', D.`sorting`, ' ' , D.`title`)
        FROM `route` D
        INNER JOIN cte
            ON cte.`id` = D.`parent`
    )
    SELECT * FROM cte
) R

INNER JOIN `url` U
    ON R.`id` = U.`route_id`
    AND U.`site_id` = 1

ORDER BY `path` ASC  

How do I use $rootScope in Angular to store variables?

angular.module('myApp').controller('myCtrl', function($scope, $rootScope) {
   var a = //something in the scope
   //put it in the root scope
    $rootScope.test = "TEST";
 });

angular.module('myApp').controller('myCtrl2', function($scope, $rootScope) {
   var b = //get var a from root scope somehow
   //use var b

   $scope.value = $rootScope.test;
   alert($scope.value);

 //    var b = $rootScope.test;
 //  alert(b);
 });

DEMO

Changing SqlConnection timeout

I found an excellent blogpost on this subject: https://improve.dk/controlling-sqlconnection-timeouts/

Basically, you either set Connect Timeout in the connection string, or you set ConnectionTimeout on the command object.

Be aware that the timeout time is in seconds.

ListView item background via custom selector

I always use the same method and it works every time, every where: I simply use a selector like this

<item android:state_activated="true"  android:color="@color/your_selected_color" />
<item android:state_pressed="true" android:color="@color/your_pressed_color" />
<item android:color="@color/your_normal_color"></item>

and set on the ListView (THIS IS VERY IMPORTANT TO MAKE IT WORKING) the attribute

android:choiceMode="singleChoice"

for the textColor just put in the color folder(IMPORTANT, not drawable folder!) a selector like this

<item android:state_activated="true"  android:color="@color/your_selected_textColor" />
<item android:state_pressed="true" android:color="@color/your_pressed_textColor" />
<item android:color="@color/your_normal_textColor"></item>

this a sample row template

<ImageView
    android:id="@+skinMenu/lblIcon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:src="@drawable/menu_catalog" />

<TextView
    android:id="@+skinMenu/lblTitle"
    style="@style/superlabelStyle"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_marginLeft="20dp"
    android:gravity="center_vertical"
    android:text="test menu testo"
    android:textColor="@color/menu_textcolor_selector"
    android:textSize="20dp"
    android:textStyle="bold" />

everything showld work without tedious workarounds. hope this help

Sort a list by multiple attributes?

Here's one way: You basically re-write your sort function to take a list of sort functions, each sort function compares the attributes you want to test, on each sort test, you look and see if the cmp function returns a non-zero return if so break and send the return value. You call it by calling a Lambda of a function of a list of Lambdas.

Its advantage is that it does single pass through the data not a sort of a previous sort as other methods do. Another thing is that it sorts in place, whereas sorted seems to make a copy.

I used it to write a rank function, that ranks a list of classes where each object is in a group and has a score function, but you can add any list of attributes. Note the un-lambda-like, though hackish use of a lambda to call a setter. The rank part won't work for an array of lists, but the sort will.

#First, here's  a pure list version
my_sortLambdaLst = [lambda x,y:cmp(x[0], y[0]), lambda x,y:cmp(x[1], y[1])]
def multi_attribute_sort(x,y):
    r = 0
    for l in my_sortLambdaLst:
        r = l(x,y)
        if r!=0: return r #keep looping till you see a difference
    return r

Lst = [(4, 2.0), (4, 0.01), (4, 0.9), (4, 0.999),(4, 0.2), (1, 2.0), (1, 0.01), (1, 0.9), (1, 0.999), (1, 0.2) ]
Lst.sort(lambda x,y:multi_attribute_sort(x,y)) #The Lambda of the Lambda
for rec in Lst: print str(rec)

Here's a way to rank a list of objects

class probe:
    def __init__(self, group, score):
        self.group = group
        self.score = score
        self.rank =-1
    def set_rank(self, r):
        self.rank = r
    def __str__(self):
        return '\t'.join([str(self.group), str(self.score), str(self.rank)]) 


def RankLst(inLst, group_lambda= lambda x:x.group, sortLambdaLst = [lambda x,y:cmp(x.group, y.group), lambda x,y:cmp(x.score, y.score)], SetRank_Lambda = lambda x, rank:x.set_rank(rank)):
    #Inner function is the only way (I could think of) to pass the sortLambdaLst into a sort function
    def multi_attribute_sort(x,y):
        r = 0
        for l in sortLambdaLst:
            r = l(x,y)
            if r!=0: return r #keep looping till you see a difference
        return r

    inLst.sort(lambda x,y:multi_attribute_sort(x,y))
    #Now Rank your probes
    rank = 0
    last_group = group_lambda(inLst[0])
    for i in range(len(inLst)):
        rec = inLst[i]
        group = group_lambda(rec)
        if last_group == group: 
            rank+=1
        else:
            rank=1
            last_group = group
        SetRank_Lambda(inLst[i], rank) #This is pure evil!! The lambda purists are gnashing their teeth

Lst = [probe(4, 2.0), probe(4, 0.01), probe(4, 0.9), probe(4, 0.999), probe(4, 0.2), probe(1, 2.0), probe(1, 0.01), probe(1, 0.9), probe(1, 0.999), probe(1, 0.2) ]

RankLst(Lst, group_lambda= lambda x:x.group, sortLambdaLst = [lambda x,y:cmp(x.group, y.group), lambda x,y:cmp(x.score, y.score)], SetRank_Lambda = lambda x, rank:x.set_rank(rank))
print '\t'.join(['group', 'score', 'rank']) 
for r in Lst: print r

How do you do a ‘Pause’ with PowerShell 2.0?

I think it is worthwhile to recap/summarize the choices here for clarity... then offer a new variation that I believe provides the best utility.

<1> ReadKey (System.Console)

write-host "Press any key to continue..."
[void][System.Console]::ReadKey($true)
  • Advantage: Accepts any key but properly excludes Shift, Alt, Ctrl modifier keys.
  • Disadvantage: Does not work in PS-ISE.

<2> ReadKey (RawUI)

Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  • Disadvantage: Does not work in PS-ISE.
  • Disadvantage: Does not exclude modifier keys.

<3> cmd

cmd /c Pause | Out-Null
  • Disadvantage: Does not work in PS-ISE.
  • Disadvantage: Visibly launches new shell/window on first use; not noticeable on subsequent use but still has the overhead

<4> Read-Host

Read-Host -Prompt "Press Enter to continue"
  • Advantage: Works in PS-ISE.
  • Disadvantage: Accepts only Enter key.

<5> ReadKey composite

This is a composite of <1> above with the ISE workaround/kludge extracted from the proposal on Adam's Tech Blog (courtesy of Nick from earlier comments on this page). I made two slight improvements to the latter: added Test-Path to avoid an error if you use Set-StrictMode (you do, don't you?!) and the final Write-Host to add a newline after your keystroke to put the prompt in the right place.

Function Pause ($Message = "Press any key to continue . . . ") {
    if ((Test-Path variable:psISE) -and $psISE) {
        $Shell = New-Object -ComObject "WScript.Shell"
        $Button = $Shell.Popup("Click OK to continue.", 0, "Script Paused", 0)
    }
    else {     
        Write-Host -NoNewline $Message
        [void][System.Console]::ReadKey($true)
        Write-Host
    }
}
  • Advantage: Accepts any key but properly excludes Shift, Alt, Ctrl modifier keys.
  • Advantage: Works in PS-ISE (though only with Enter or mouse click)
  • Disadvantage: Not a one-liner!

How to find common elements from multiple vectors?

A good answer already, but there are a couple of other ways to do this:

unique(c[c%in%a[a%in%b]])

or,

tst <- c(unique(a),unique(b),unique(c))
tst <- tst[duplicated(tst)]
tst[duplicated(tst)]

You can obviously omit the unique calls if you know that there are no repeated values within a, b or c.

@font-face src: local - How to use the local font if the user already has it?

If you want to check for local files first do:

@font-face {
font-family: 'Green Sans Web';
src:
    local('Green Web'),
    local('GreenWeb-Regular'),
    url('GreenWeb.ttf');
}

There is a more elaborate description of what to do here.

Get the cell value of a GridView row

Try changing your code to

// Get the currently selected row using the SelectedRow property.
GridViewRow row = dgCustomer.SelectedRow;

// And you respective cell's value
TextBox1.Text = row.Cells[1].Text

UPDATE: (based on my comment) If all what you are trying to get is the primary key value for the selected row then an alternate approach is to set

datakeynames="yourprimarykey"

for the gridview definition which can be accessed from the code behind like below.

TextBox1.Text = CustomersGridView.SelectedValue.ToString();

How to check if dropdown is disabled?

The legacy solution, before 1.6, was to use .attr and handle the returned value as a bool. The main problem is that the returned type of .attr has changed to string, and therefore the comparison with == true is broken (see http://jsfiddle.net/2vene/1/ (and switch the jquery-version)).

With 1.6 .prop was introduced, which returns a bool.

Nevertheless, I suggest to use .is(), as the returned type is intrinsically bool, like:

$('#dropUnit').is(':disabled');
$('#dropUnit').is(':enabled');

Furthermore .is() is much more natural (in terms of "natural language") and adds more conditions than a simple attribute-comparison (eg: .is(':last'), .is(':visible'), ... please see documentation on selectors).

Append a Lists Contents to another List C#

GlobalStrings.AddRange(localStrings);

Note: You cannot declare the list object using the interface (IList).
Documentation: List<T>.AddRange(IEnumerable<T>).

Set the location in iPhone Simulator

You can easily share any desired location from the macOS Maps application to the Xcode simulator.

  1. From Xcode run the application in the simulator as you usually do.
  2. Open the maps application on macOS (for convenience I usually make a new Desktop where I have both the simulator and the map application).
  3. Inside the maps (macOS), long click on any point on the map, or search for a place to let the map draw a pin where you need it.
  4. Click on the pin, then on the information (i) icon (see image).
  5. In the up right of the information view click on the share icon.
  6. Share the location with the simulator (see image).
  7. Confirm and enjoy :)

This let you test some locations quickly, having an understanding on where geographically the location is (e.g. for testing geofencing), and deciding at runtime where to go next (e.g. for debugging and fine-tuning stuff).

Tested this on MacOS Catalina 10.15.4 and Xcode 11.4.

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

For me, this problem was due to the fact that I had not appropriately sym-linked the cv2.so file in the~/.virtualenvs/cv/lib/python3.5/site-packages folder (the name of your virualenv may not be "cv", your version of python may not be 3.5--adjust accordingly).

If you go to the ~/.virtualenvs/cv/lib/python3.5/site-packages folder and ls, the cv2.so file should appear in light blue (Ubuntu 16.04) showing that it is linked. You can check the link location by typing: readlink cv2.so

If cv2.so appears in red (as mine did), rm the file and type: (for my install of python 3.5)

ln -s /usr/local/lib/python3.5/dist-packages/cv2.cpython-35m-x86_64-linux-gnu.so cv2.so

OR (if you have python 3.6)

ln -s /usr/local/lib/python3.6/dist-packages/cv2.cpython-36m-x86_64-linux-gnu.so cv2.so

If you are working in python 2.6 or python 2.7, you instead type:

ln -s /usr/local/lib/python2.7/dist-packages/cv2.so cv2.so

If the cv2.so or cv2.cpython-36m-x86_64-linux-gnu.so files do not exist in your /usr/local/lib/python***/dist-packages location, check to see if they're in a /usr/local/lib/python***/sites-packages folder. If so, adjust the path accordingly. If not, something has gone wrong with your opencv installation.

This answer was inspired by information here: https://www.pyimagesearch.com/2016/10/24/ubuntu-16-04-how-to-install-opencv/

m2eclipse not finding maven dependencies, artifacts not found

It sounds like your m2eclipse install is using the embedded Maven, which has its own repository (located under user home) and settings.

If you open up the Maven preferences (Window->Preferences->Maven->Installations, you can add your Maven installation by selecting Add... then browsing to the M2_HOME directory.

Preferences screenshot
(source: sonatype.com)

For more details see the m2eclipse book

Xcode is not currently available from the Software Update server

The command

xcode-select --install

proposes 3 options: Get Xcode; Not Now; Install.

When I choose to get full Xcode the command finished successfully. It took a while, but this way I was able to complete all macports migration instructions.

Retrieving Dictionary Value Best Practices

I imagine that trygetvalue is doing something more like:

if(myDict.ReallyOptimisedVersionofContains(someKey))
{ 
  someVal = myDict[someKey];
  return true;
}
return false;

So hopefully no try/catch anywhere.

I think it is just a method of convenience really. I generally use it as it saves a line of code or two.

Add spaces between the characters of a string in Java?

  • Create a char array from your string
  • Loop through the array, adding a space +" " after each item in the array(except the last one, maybe)
  • BOOM...done!!

xml.LoadData - Data at the root level is invalid. Line 1, position 1

At first I had problems escaping the "&" character, then diacritics and special letters were shown as question marks and ended up with the issue OP mentioned.

I looked at the answers and I used @Ringo's suggestion to try Load() method as an alternative. That made me realize that I can deal with my response in other ways not just as a string.

using System.IO.Stream instead of string solved all the issues for me.

var response = await this.httpClient.GetAsync(url);
var responseStream = await response.Content.ReadAsStreamAsync();
var xmlDocument = new XmlDocument();
xmlDocument.Load(responseStream);

The cool thing about Load() is that this method automatically detects the string format of the input XML (for example, UTF-8, ANSI, and so on). See more

How to check whether a file is empty or not?

>>> import os
>>> os.stat("file").st_size == 0
True

TLS 1.2 in .NET Framework 4.0

There are two possible scenarios,

  1. If your application runs on .net framework 4.5 or less, and you can easily deploy new code to the production then you can use of below solution.

    You can add the below line of code before making the API call,

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5
    ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // .NET 4.0
    
  2. If you cannot deploy new code and you want to resolve the issue with the same code which is present in the production, then you have two options.

Option 1 :

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001


then create a file with extension .reg and install.

Note : This setting will apply at registry level and is applicable to all application present on that machine and if you want to restrict to only single application then you can use Option 2

Option 2 : This can be done by changing some configuration setting in config file. You can add either in your config file.

<runtime>
    <AppContextSwitchOverrides value="Switch.System.Net.DontEnableSchUseStrongCrypto=false"/>
</runtime>

or

<runtime>
  <AppContextSwitchOverrides value="Switch.System.Net.DontEnableSystemDefaultTlsVersions=false"
</runtime>

Maven 3 and JUnit 4 compilation problem: package org.junit does not exist

my problem was a line inside my pom.xml i had the line <sourceDirectory>${basedir}/src</sourceDirectory> removing this line made maven use regular structure folders which solves my issue

How do I POST XML data to a webservice with Postman?

Send XML requests with the raw data type, then set the Content-Type to text/xml.


  1. After creating a request, use the dropdown to change the request type to POST.

    Set request type to POST

  2. Open the Body tab and check the data type for raw.

    Setting data type to raw

  3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

    Selecting content-type text/xml

  4. Enter your raw XML data into the input field below

    Example of XML request in Postman

  5. Click Send to submit your XML Request to the specified server.

    Clicking the Send button

Convert pem key to ssh-rsa format

I did with

ssh-keygen -i -f $sshkeysfile >> authorized_keys

Credit goes here

NPM doesn't install module dependencies

I think that I also faced this problem, and the best solution I found was to look at my console and figure out the error that was being thrown. So, I read it carefully and found that the problem was that I didn't specify my repo, description, and valid name in my package.json. I added those pieces of information and everything was okay.

ModalPopupExtender OK Button click event not firing?

Put into the Button-Control the Attribute "UseSubmitBehavior=false".

How do browser cookie domains work?

For an extensive coverage review the contents of RFC2965. Of course that doesn't necessarily mean that all browsers behave exactly the same way.

However in general the rule for default Path if none specified in the cookie is the path in the URL from which the Set-Cookie header arrived. Similarly the default for the Domain is the full host name in the URL from which the Set-Cookie arrived.

Matching rules for the domain require the cookie Domain to match the host to which the request is being made. The cookie can specify a wider domain match by include *. in the domain attribute of Set-Cookie (this one area that browsers may vary). Matching the path (assuming the domain matches) is a simple matter that the requested path must be inside the path specified on the cookie. Typically session cookies are set with path=/ or path=/applicationName/ so the cookie is available to all requests into the application.


Response to Added:

  • Will a cookie for .example.com be available for www.example.com? Yes
  • Will a cookie for .example.com be available for example.com? Don't Know
  • Will a cookie for example.com be available for www.example.com? Shouldn't but... *
  • Will a cookie for example.com be available for anotherexample.com? No
  • Will www.example.com be able to set cookie for example.com? Yes
  • Will www.example.com be able to set cookie for www2.example.com? No (Except via .example.com)
  • Will www.example.com be able to set cookie for .com? No (Can't set a cookie this high up the namespace nor can you set one for something like .co.uk).

* I'm unable to test this right now but I have an inkling that at least IE7/6 would treat the path example.com as if it were .example.com.

Virtual network interface in Mac OS X

ifconfig interfacename create will create a virtual interface,

How to add an UIViewController's view as subview

Change the frame size of viewcontroller.view.frame, and then add to subview. [viewcontrollerparent.view addSubview:viewcontroller.view]

How to check for null in Twig?

you can use the following code to check whether

{% if var is defined %}

var is variable is SET

{% endif %}

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

ORA-03113: end-of-file on communication channel

Is the database letting you know that the network connection is no more. This could be because:

  1. A network issue - faulty connection, or firewall issue
  2. The server process on the database that is servicing you died unexpectedly.

For 1) (firewall) search tahiti.oracle.com for SQLNET.EXPIRE_TIME. This is a sqlnet.ora parameter that will regularly send a network packet at a configurable interval ie: setting this will make the firewall believe that the connection is live.

For 1) (network) speak to your network admin (connection could be unreliable)

For 2) Check the alert.log for errors. If the server process failed there will be an error message. Also a trace file will have been written to enable support to identify the issue. The error message will reference the trace file.

Support issues can be raised at metalink.oracle.com with a suitable Customer Service Identifier (CSI)

How to set up devices for VS Code for a Flutter emulator

You do not need to create a virtual device using android studio. You can use your android device running on android 8.0 or higher. All you have to do is to activate developer settings, then enable USB DEBUGGING in the developer settings. Your device will show at the bottom right side of the VS Code. Without enabling the USB debugging, the device may not show.enter image description here

Why can't I declare static methods in an interface?

An interface is used for polymorphism, which applies to Objects, not types. Therefore (as already noted) it makes no sense to have an static interface member.

Check if string contains \n Java

I'd rather trust JDK over System property. Following is a working snippet.

    private boolean checkIfStringContainsNewLineCharacters(String str){
        if(!StringUtils.isEmpty(str)){
            Scanner scanner = new Scanner(str);
            scanner.nextLine();
            boolean hasNextLine =  scanner.hasNextLine();
            scanner.close();
            return hasNextLine;
        }
        return false;
    }

How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

"N/A" is a string and cannot be converted to a number. Catch the exception and handle it. For example:

    String text = "N/A";
    int intVal = 0;
    try {
        intVal = Integer.parseInt(text);
    } catch (NumberFormatException e) {
        //Log it if needed
        intVal = //default fallback value;
    }

CSS word-wrapping in div

I'm a little surprised it doesn't just do that. Could there another element inside the div that has a width set to something greater than 250?

How do I add target="_blank" to a link within a specified div?

Non-jquery:

// Very old browsers
// var linkList = document.getElementById('link_other').getElementsByTagName('a');

// New browsers (IE8+)
var linkList = document.querySelectorAll('#link_other a');

for(var i in linkList){
 linkList[i].setAttribute('target', '_blank');
}

Java - Check Not Null/Empty else assign default value

If using JDK 9 +, use Objects.requireNonNullElse(T obj, T defaultObj)

How do I see active SQL Server connections?

Apart from sp_who, you can also use the "undocumented" sp_who2 system stored procedure which gives you more detailed information. See Difference between sp_who and sp_who2.

Eclipse reported "Failed to load JNI shared library"

First, ensure that your version of Eclipse and JDK match, either both 64-bit or both 32-bit (you can't mix-and-match 32-bit with 64-bit).

Second, the -vm argument in eclipse.ini should point to the java executable. See http://wiki.eclipse.org/Eclipse.ini for examples.

If you're unsure of what version (64-bit or 32-bit) of Eclipse you have installed, you can determine that a few different ways. See How to find out if an installed Eclipse is 32 or 64 bit version?

Simplest way to set image as JPanel background

I am trying to set a JPanel's background using an image, however, every example I find seems to suggest extending the panel with its own class

yes you will have to extend JPanel and override the paintcomponent(Graphics g) function to do so.

@Override
  protected void paintComponent(Graphics g) {

    super.paintComponent(g);
        g.drawImage(bgImage, 0, 0, null);
}

I have been looking for a way to simply add the image without creating a whole new class and within the same method (trying to keep things organized and simple).

You can use other component which allows to add image as icon directly e.g. JLabel if you want.

ImageIcon icon = new ImageIcon(imgURL); 
JLabel thumb = new JLabel();
thumb.setIcon(icon);

But again in the bracket trying to keep things organized and simple !! what makes you to think that just creating a new class will lead you to a messy world ?

Xcode error - Thread 1: signal SIGABRT

You are trying to load a XIB named DetailViewController, but no such XIB exists or it's not member of your current target.

Can I access a form in the controller?

Bit late for an answer but came with following option. It is working for me but not sure if it is the correct way or not.

In my view I'm doing this:

<form name="formName">
    <div ng-init="setForm(formName);"></div>
</form>

And in the controller:

$scope.setForm = function (form) {
    $scope.myForm = form;
}

Now after doing this I have got my form in my controller variable which is $scope.myForm

How to show "if" condition on a sequence diagram?

In Visual Studio UML sequence this can also be described as fragments which is nicely documented here: https://msdn.microsoft.com/en-us/library/dd465153.aspx

How to use Python's pip to download and keep the zipped files for a package?

The --download-cache option should do what you want:

pip install --download-cache="/pth/to/downloaded/files" package

However, when I tested this, the main package downloaded, saved and installed ok, but the the dependencies were saved with their full url path as the name - a bit annoying, but all the tar.gz files were there.

The --download option downloads the main package and its dependencies and does not install any of them. (Note that prior to version 1.1 the --download option did not download dependencies.)

pip install package --download="/pth/to/downloaded/files"

The pip documentation outlines using --download for fast & local installs.

How to drop all user tables?

The simplest way is to drop the user that owns the objects with the cascade command.

DROP USER username CASCADE

Java - Opposite of .contains (does not contain)

It seems that Luiggi Mendoza and joey rohan both already answered this, but I think it can be clarified a little.

You can write it as a single if statement:

if (inventory.contains("bread") && !inventory.contains("water")) {
    // do something
}

How to send and retrieve parameters using $state.go toParams and $stateParams?

None of these examples on this page worked for me. This is what I used and it worked well. Some solutions said you cannot combine url with $state.go() but this is not true. The awkward thing is you must define the params for the url and also list the params. Both must be present. Tested on Angular 1.4.8 and UI Router 0.2.15.

In the state add your params to end of state and define the params:

url: 'view?index&anotherKey',
params: {'index': null, 'anotherKey': null}

In your controller your go statement will look like this:

$state.go('view', { 'index': 123, 'anotherKey': 'This is a test' });

Then to pull the params out and use them in your new state's controller (don't forget to pass in $stateParams to your controller function):

var index = $stateParams.index;
var anotherKey = $stateParams.anotherKey;
console.log(anotherKey); //it works!

Bridged networking not working in Virtualbox under Windows 10

WINDOWS FIX: Ive' Fixed it by downloading a new VMbox installer from the Official Website Here.

  • Just run the installer and install it to override your current VMBox version, that should fix it.

Dont worry about your VM's they will not disappear if you override your current installation.

NOTE: If you already have the latest version, you need to export all your VM's, unninstall your current VMBox and install it from new installer.

How to search all loaded scripts in Chrome Developer Tools?

Search All Files with Control+Shift+F or Console->[Search tab]

enter image description here

NOTE: Global Search shows up next to the CONSOLE menu

BigDecimal to string

To archive the necessary result with double constructor you need to round the BigDecimal before convert it to String e.g.

new java.math.BigDecimal(10.0001).round(new java.math.MathContext(6, java.math.RoundingMode.HALF_UP)).toString()

will print the "10.0001"

html table cell width for different rows

You can't have cells of arbitrarily different widths, this is generally a standard behaviour of tables from any space, e.g. Excel, otherwise it's no longer a table but just a list of text.

You can however have cells span multiple columns, such as:

<table>
    <tr>
        <td>25</td>
        <td>50</td>
        <td>25</td>
    </tr>
    <tr>
        <td colspan="2">75</td>
        <td>20</td>
    </tr>
</table>

As an aside, you should avoid using style attributes like border and bgcolor and prefer CSS for those.

Insert ellipsis (...) into HTML tag if content too wide

Just like @acSlater I couldn't find something for what I needed so I rolled my own. Sharing in case anyone else can use:

Method:
ellipsisIfNecessary(mystring,maxlength);
Usage:
trimmedString = ellipsisIfNecessary(mystring,50);
Code and Demo Link: https://gist.github.com/cemerson/10368014

How to check what version of jQuery is loaded?

Go to the developer's Tool > console and write one of the following command jQuery.fn.jquery console.log(jQuery().jquery);

CMake unable to determine linker language with C++

I want to add another solution in case a library without any source files shall be build. Such libraries are also known as header only libraries. By default add_library expects at least one source file added or otherwise the mentioned error occurs. Since header only libraries are quite common, cmake has the INTERFACE keyword to build such libraries. The INTERFACE keyword is used as shown below and it eliminates the need for empty source files added to the library.

add_library(myLibrary INTERFACE)
target_include_directories(myLibrary INTERFACE {CMAKE_CURRENT_SOURCE_DIR})

The example above would build a header only library including all header files in the same directory as the CMakeLists.txt. Replace {CMAKE_CURRENT_SOURCE_DIR} with a path in case your header files are in a different directory than the CMakeLists.txt file.

Have a look at this blog post or the cmake documentation for further info regarding header only libraries and cmake.

Creating JSON on the fly with JObject

Simple way of creating newtonsoft JObject from Properties.

This is a Sample User Properties

public class User
{
    public string Name;
    public string MobileNo;
    public string Address;
}

and i want this property in newtonsoft JObject is:

JObject obj = JObject.FromObject(new User()
{
    Name = "Manjunath",
    MobileNo = "9876543210",
    Address = "Mumbai, Maharashtra, India",
});

Output will be like this:

{"Name":"Manjunath","MobileNo":"9876543210","Address":"Mumbai, Maharashtra, India"}

How to convert array values to lowercase in PHP?

use array_map():

$yourArray = array_map('strtolower', $yourArray);

In case you need to lowercase nested array (by Yahya Uddin):

$yourArray = array_map('nestedLowercase', $yourArray);

function nestedLowercase($value) {
    if (is_array($value)) {
        return array_map('nestedLowercase', $value);
    }
    return strtolower($value);
}

Java generics - ArrayList initialization

A lot of this has to do with polymorphism. When you assign

X = new Y();

X can be much less 'specific' than Y, but not the other way around. X is just the handle you are accessing Y with, Y is the real instantiated thing,

You get an error here because Integer is a Number, but Number is not an Integer.

ArrayList<Integer> a = new ArrayList<Number>(); // compile-time error

As such, any method of X that you call must be valid for Y. Since X is more generally it probably shares some, but not all of Y's methods. Still, any arguments given must be valid for Y.

In your examples with add, an int (small i) is not a valid Object or Integer.

ArrayList<?> a = new ArrayList<?>();

This is no good because you can't actually instantiate an array list containing ?'s. You can declare one as such, and then damn near anything can follow in new ArrayList<Whatever>();

Simulating ENTER keypress in bash script

Here is sample usage using expect:

#!/usr/bin/expect
set timeout 360
spawn my_command # Replace with your command.
expect "Do you want to continue?" { send "\r" }

Check: man expect for further information.

Accessing elements by type in javascript

In plain-old JavaScript you can do this:

var inputs = document.getElementsByTagName('input');

for(var i = 0; i < inputs.length; i++) {
    if(inputs[i].type.toLowerCase() == 'text') {
        alert(inputs[i].value);
    }
}

In jQuery, you would just do:

// select all inputs of type 'text' on the page
$("input:text")

// hide all text inputs which are descendants of div class="foo"
$("div.foo input:text").hide();

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

Maybe you can simply make header view background transparent:

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    view.tintColor = [UIColor clearColor];
}

Or apply it globally:

    [UITableViewHeaderFooterView appearance].tintColor = [UIColor clearColor];

Javascript callback when IFRAME is finished loading?

Using onload attrbute will solve your problem.

Here is an example.

_x000D_
_x000D_
function a() {_x000D_
alert("Your iframe has been loaded");_x000D_
}
_x000D_
<iframe src="https://stackoverflow.com" onload="a()"></iframe>
_x000D_
_x000D_
_x000D_

Is this what you want?

Click here for more information.

rsync: how can I configure it to create target directory on server?

If you have more than the last leaf directory to be created, you can either run a separate ssh ... mkdir -p first, or use the --rsync-path trick as explained here :

rsync -a --rsync-path="mkdir -p /tmp/x/y/z/ && rsync" $source user@remote:/tmp/x/y/z/

Or use the --relative option as suggested by Tony. In that case, you only specify the root of the destination, which must exist, and not the directory structure of the source, which will be created:

rsync -a --relative /new/x/y/z/ user@remote:/pre_existing/dir/

This way, you will end up with /pre_existing/dir/new/x/y/z/

And if you want to have "y/z/" created, but not inside "new/x/", you can add ./ where you want --relativeto begin:

rsync -a --relative /new/x/./y/z/ user@remote:/pre_existing/dir/

would create /pre_existing/dir/y/z/.

Iterating through populated rows

It looks like you just hard-coded the row and column; otherwise, a couple of small tweaks, and I think you're there:

Dim sh As Worksheet
Dim rw As Range
Dim RowCount As Integer

RowCount = 0

Set sh = ActiveSheet
For Each rw In sh.Rows

  If sh.Cells(rw.Row, 1).Value = "" Then
    Exit For
  End If

  RowCount = RowCount + 1

Next rw

MsgBox (RowCount)

C - determine if a number is prime

  1. Build a table of small primes, and check if they divide your input number.
  2. If the number survived to 1, try pseudo primality tests with increasing basis. See Miller-Rabin primality test for example.
  3. If your number survived to 2, you can conclude it is prime if it is below some well known bounds. Otherwise your answer will only be "probably prime". You will find some values for these bounds in the wiki page.

Google Maps API v2: How to make markers clickable?

setTag(position) while adding marker to map.

Marker marker =  map.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude)));
marker.setTag(position);

getTag() on setOnMarkerClickListener listener

map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                @Override
                public boolean onMarkerClick(Marker marker) {
                    int position = (int)(marker.getTag());
                   //Using position get Value from arraylist 
                    return false;
                }
            });

Removing all script tags from html with JS Regular Expression

jQuery uses a regex to remove script tags in some cases and I'm pretty sure its devs had a damn good reason to do so. Probably some browser does execute scripts when inserting them using innerHTML.

Here's the regex:

/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi

And before people start crying "but regexes for HTML are evil": Yes, they are - but for script tags they are safe because of the special behaviour - a <script> section may not contain </script> at all unless it should end at this position. So matching it with a regex is easily possible. However, from a quick look the regex above does not account for trailing whitespace inside the closing tag so you'd have to test if </script    etc. will still work.

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

You can use npm i y-websockets-server and then use the below command

y-websockets-server --port 11000

and here in my case, the port No is 11000.

Excel vba - convert string to number

If, for example, x = 5 and is stored as string, you can also just:

x = x + 0

and the new x would be stored as a numeric value.

How do I fit an image (img) inside a div and keep the aspect ratio?

You will need some JavaScript to prevent cropping if you don't know the dimension of the image at the time you're writing the css.

HTML & JavaScript

<div id="container">
    <img src="something.jpg" alt="" />
</div>

<script type="text/javascript">
(function() {

var img = document.getElementById('container').firstChild;
img.onload = function() {
    if(img.height > img.width) {
        img.height = '100%';
        img.width = 'auto';
    }
};

}());
</script>

CSS

#container {
   width: 48px;
   height: 48px;
}

#container img {
   width: 100%;
}

If you use a JavaScript Library you might want to take advantage of it.

What does "&" at the end of a linux command mean?

I don’t know for sure but I’m reading a book right now and what I am getting is that a program need to handle its signal ( as when I press CTRL-C). Now a program can use SIG_IGN to ignore all signals or SIG_DFL to restore the default action.

Now if you do $ command & then this process running as background process simply ignores all signals that will occur. For foreground processes these signals are not ignored.

Is there a difference between PhoneGap and Cordova commands?

Late answer but I think this might be useful.

There are differences between the two cli, phonegapis a command that encapsulates cordova. In the create case the only difference is an overriden default app

In some other cases the difference is much more significant. For instance phonegap build comes with a remote build functionality while cordova build only supports local builds.

A big limitation I found to PhoneGap is that, AFAIK, you can only build a release APK using the PhoneGap Build service. On Cordova you can build with cordova build android --release.

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

For PHP, put this line of code before you start printing your XML:

while(ob_get_level()) ob_end_clean();

UIView with rounded corners and drop shadow?

Swift 3 & IBInspectable solution:
Inspired by Ade's solution

First, create an UIView extension:

//
//  UIView-Extension.swift
//  

import Foundation
import UIKit

@IBDesignable
extension UIView {
     // Shadow
     @IBInspectable var shadow: Bool {
          get {
               return layer.shadowOpacity > 0.0
          }
          set {
               if newValue == true {
                    self.addShadow()
               }
          }
     }

     fileprivate func addShadow(shadowColor: CGColor = UIColor.black.cgColor, shadowOffset: CGSize = CGSize(width: 3.0, height: 3.0), shadowOpacity: Float = 0.35, shadowRadius: CGFloat = 5.0) {
          let layer = self.layer
          layer.masksToBounds = false

          layer.shadowColor = shadowColor
          layer.shadowOffset = shadowOffset
          layer.shadowRadius = shadowRadius
          layer.shadowOpacity = shadowOpacity
          layer.shadowPath = UIBezierPath(roundedRect: layer.bounds, cornerRadius: layer.cornerRadius).cgPath

          let backgroundColor = self.backgroundColor?.cgColor
          self.backgroundColor = nil
          layer.backgroundColor =  backgroundColor
     }


     // Corner radius
     @IBInspectable var circle: Bool {
          get {
               return layer.cornerRadius == self.bounds.width*0.5
          }
          set {
               if newValue == true {
                    self.cornerRadius = self.bounds.width*0.5
               }
          }
     }

     @IBInspectable var cornerRadius: CGFloat {
          get {
               return self.layer.cornerRadius
          }

          set {
               self.layer.cornerRadius = newValue
          }
     }


     // Borders
     // Border width
     @IBInspectable
     public var borderWidth: CGFloat {
          set {
               layer.borderWidth = newValue
          }

          get {
               return layer.borderWidth
          }
     }

     // Border color
     @IBInspectable
     public var borderColor: UIColor? {
          set {
               layer.borderColor = newValue?.cgColor
          }

          get {
               if let borderColor = layer.borderColor {
                    return UIColor(cgColor: borderColor)
               }
               return nil
          }
     }
}

Then, simply select your UIView in interface builder setting shadow ON and corner radius, like below:

Selecting your UIView

Setting shadow ON & corner radius

The result!

Result

How to run Gradle from the command line on Mac bash

Also, if you don't have the gradlew file in your current directory:

You can install gradle with homebrew with the following command:

$ brew install gradle

As mentioned in this answer. Then, you are not going to need to include it in your path (homebrew will take care of that) and you can just run (from any directory):

$ gradle test 

LIMIT 10..20 in SQL Server

select * from (select id,name,ROW_NUMBER() OVER (ORDER BY id  asc) as row
from tableName1) tbl1
where tbl1.row>=10 and tbl1.row<=15

Will print rows from 10 to 15.

Remove useless zero digits from decimals in PHP

This is a simple one line function using rtrim, save separator and decimal point :

function myFormat($num,$dec)
 {
 return rtrim(rtrim(number_format($num,$dec),'0'),'.');
 }

How to load html string in a webview?

I had the same requirement and I have done this in following way.You also can try out this..

Use loadData method

web.loadData("<p style='text-align:center'><img class='aligncenter size-full wp-image-1607' title='' src="+movImage+" alt='' width='240px' height='180px' /></p><p><center><U><H2>"+movName+"("+movYear+")</H2></U></center></p><p><strong>Director : </strong>"+movDirector+"</p><p><strong>Producer : </strong>"+movProducer+"</p><p><strong>Character : </strong>"+movActedAs+"</p><p><strong>Summary : </strong>"+movAnecdotes+"</p><p><strong>Synopsis : </strong>"+movSynopsis+"</p>\n","text/html", "UTF-8");

movDirector movProducer like all are my string variable.

In short i retain custom styling for my url.

Moving from one activity to another Activity in Android

public void onClick(View v)
{
 startActivity(new Intent(getApplicationContext(), Next.class));

}

it is direct way to move second activity and there is no need for call intent

Graph implementation C++

It really depends on what algorithms you need to implement, there is no silver bullet (and that's shouldn't be a surprise... the general rule about programming is that there's no general rule ;-) ).

I often end up representing directed multigraphs using node/edge structures with pointers... more specifically:

struct Node
{
    ... payload ...
    Link *first_in, *last_in, *first_out, *last_out;
};

struct Link
{
    ... payload ...
    Node *from, *to;
    Link *prev_same_from, *next_same_from,
         *prev_same_to, *next_same_to;
};

In other words each node has a doubly-linked list of incoming links and a doubly-linked list of outgoing links. Each link knows from and to nodes and is at the same time in two different doubly-linked lists: the list of all links coming out from the same from node and the list of all links arriving at the same to node.

The pointers prev_same_from and next_same_from are used when following the chain of all the links coming out from the same node; the pointers prev_same_to and next_same_to are instead used when managing the chain of all the links pointing to the same node.

Data structure diagram

It's a lot of pointer twiddling (so unless you love pointers just forget about this) but query and update operations are efficient; for example adding a node or a link is O(1), removing a link is O(1) and removing a node x is O(deg(x)).

Of course depending on the problem, payload size, graph size, graph density this approach can be way overkilling or too much demanding for memory (in addition to payload you've 4 pointers per node and 6 pointers per link).

A similar structure full implementation can be found here.

Input type DateTime - Value format?

For what it's worth, with iOS7 dropping support for datetime you need to use datetime-local which doesn't accept timezone portion (which makes sense).

Doesn't work (iOS anyway):

 <input type="datetime-local" value="2000-01-01T00:00:00+05:00" />

Works:

<input type="datetime-local" value="2000-01-01T00:00:00" />

PHP for value (windows safe):

strftime('%Y-%m-%dT%H:%M:%S', strtotime($my_datetime_input))