Programs & Examples On #Jakarta mail

A Java API to send and receive emails. JavaMail is part of Java EE, but can also be used in Java SE via a separate download.

Base64: java.lang.IllegalArgumentException: Illegal character

The Base64.Encoder.encodeToString method automatically uses the ISO-8859-1 character set.

For an encryption utility I am writing, I took the input string of cipher text and Base64 encoded it for transmission, then reversed the process. Relevant parts shown below. NOTE: My file.encoding property is set to ISO-8859-1 upon invocation of the JVM so that may also have a bearing.

static String getBase64EncodedCipherText(String cipherText) {
    byte[] cText = cipherText.getBytes();
    // return an ISO-8859-1 encoded String
    return Base64.getEncoder().encodeToString(cText);
}

static String getBase64DecodedCipherText(String encodedCipherText) throws IOException {
    return new String((Base64.getDecoder().decode(encodedCipherText)));
}

public static void main(String[] args) {
    try {
        String cText = getRawCipherText(null, "Hello World of Encryption...");

        System.out.println("Text to encrypt/encode: Hello World of Encryption...");
        // This output is a simple sanity check to display that the text
        // has indeed been converted to a cipher text which 
        // is unreadable by all but the most intelligent of programmers.
        // It is absolutely inhuman of me to do such a thing, but I am a
        // rebel and cannot be trusted in any way.  Please look away.
        System.out.println("RAW CIPHER TEXT: " + cText);
        cText = getBase64EncodedCipherText(cText);
        System.out.println("BASE64 ENCODED: " + cText);
        // There he goes again!!
        System.out.println("BASE64 DECODED:  " + getBase64DecodedCipherText(cText));
        System.out.println("DECODED CIPHER TEXT: " + decodeRawCipherText(null, getBase64DecodedCipherText(cText)));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

The output looks like:

Text to encrypt/encode: Hello World of Encryption...
RAW CIPHER TEXT: q$;?C?l??<8??U???X[7l
BASE64 ENCODED: HnEPJDuhQ+qDbInUCzw4gx0VDqtVwef+WFs3bA==
BASE64 DECODED:  q$;?C?l??<8??U???X[7l``
DECODED CIPHER TEXT: Hello World of Encryption...

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

My complete code as below is working well:

package ripon.java.mail;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class SendEmail
{
public static void main(String [] args)
{    
    // Sender's email ID needs to be mentioned
     String from = "[email protected]";
     String pass ="test123";
    // Recipient's email ID needs to be mentioned.
   String to = "[email protected]";

   String host = "smtp.gmail.com";

   // Get system properties
   Properties properties = System.getProperties();
   // Setup mail server
   properties.put("mail.smtp.starttls.enable", "true");
   properties.put("mail.smtp.host", host);
   properties.put("mail.smtp.user", from);
   properties.put("mail.smtp.password", pass);
   properties.put("mail.smtp.port", "587");
   properties.put("mail.smtp.auth", "true");

   // Get the default Session object.
   Session session = Session.getDefaultInstance(properties);

   try{
      // Create a default MimeMessage object.
      MimeMessage message = new MimeMessage(session);

      // Set From: header field of the header.
      message.setFrom(new InternetAddress(from));

      // Set To: header field of the header.
      message.addRecipient(Message.RecipientType.TO,
                               new InternetAddress(to));

      // Set Subject: header field
      message.setSubject("This is the Subject Line!");

      // Now set the actual message
      message.setText("This is actual message");

      // Send message
      Transport transport = session.getTransport("smtp");
      transport.connect(host, from, pass);
      transport.sendMessage(message, message.getAllRecipients());
      transport.close();
      System.out.println("Sent message successfully....");
   }catch (MessagingException mex) {
      mex.printStackTrace();
   }
}
}

Error - trustAnchors parameter must be non-empty

I had this issue when trying to use Maven 3, after upgrading from Ubuntu 16.04 LTS (Xenial Xerus) to Ubuntu 18.04 LTS (Bionic Beaver).

Checking /usr/lib/jvm/java-8-oracle/jre/lib/security showed that my cacerts file was a symbolic link pointing to /etc/ssl/certs/java/cacerts.

I also had a file suspiciously named cacerts.original.

I renamed cacerts.original to cacerts, and that fixed the issue.

Solve error javax.mail.AuthenticationFailedException

The solution that works for me has two steps.

  1. First step

    package com.student.mail;
    
    import java.util.Properties;
    
    import javax.mail.Authenticator;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    
    /**
     *
     * @author jorge santos
     */
    public class GoogleMail {
        public static void main(String[] args) {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465"); 
            Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("[email protected]","Silueta95#");
                }
            });
    
        try {
    
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("[email protected]"));
            message.setSubject("Testing Subject");
            message.setText("Test Mail");
    
            Transport.send(message);
    
            System.out.println("Done");
    
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
    
    }
    
  2. Enable the gmail security

    https://myaccount.google.com/u/2/lesssecureapps?pli=1&pageId=none
    

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

Try to create an javax.mail.Authenticator Object, and send that in with the properties object to the Session object.

Authenticator edit:

You can modify this to accept a username and password and you can store them there, or where ever you want.

public class SmtpAuthenticator extends Authenticator {
public SmtpAuthenticator() {

    super();
}

@Override
public PasswordAuthentication getPasswordAuthentication() {
 String username = "user";
 String password = "password";
    if ((username != null) && (username.length() > 0) && (password != null) 
      && (password.length   () > 0)) {

        return new PasswordAuthentication(username, password);
    }

    return null;
}

In your class where you send the email:

SmtpAuthenticator authentication = new SmtpAuthenticator();
javax.mail.Message msg = new MimeMessage(Session
                    .getDefaultInstance(emailProperties, authenticator));

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail

I use the following maven dependencies to get java mail working. The first one includes the javax.mail API (with no implementation) and the second one is the SUN implementation of the javax.mail API.

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>javax.mail-api</artifactId>
    <version>1.5.5</version>
</dependency>
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.5.5</version>
</dependency>

java.lang.NoClassDefFoundError: javax/mail/Authenticator, whats wrong?

I once ran into this situation and I had the dependencies in classpath. The solution was to include javax.mail and javax.activation libraries in the container's (eg. tomcat) lib folder. Using maven -set them to provided scope and it should work. You will have shared email libs in classpath for all projects.

Useful source: http://haveacafe.wordpress.com/2008/09/26/113/

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

Maybe useful for anyone else running into this issue: When setting the port on the properties:

props.put("mail.smtp.port", smtpPort);

..make sure to use a string object. Using a numeric (ie Long) object will cause this statement to seemingly have no effect.

How to resolve javax.mail.AuthenticationFailedException issue?

Just wanted to share with you:
I happened to get this error after changing Digital Ocean machine (IP address). Apparently Gmail recognized it as a hacking attack. After following their directions, and approving the new IP address the code is back and running.

Using JavaMail with TLS

The settings from the example above didn't work for the server I was using (authsmtp.com). I kept on getting this error:

javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?

I removed the mail.smtp.socketFactory settings and everything worked. The final settings were this (SMTP auth was not used and I set the port elsewhere):

java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.starttls.enable", "true");

Illegal access: this web application instance has been stopped already

Restarting Your Server Can Resolve this problem.

I was getting the same error while Using Dynamic Jasper Reporting , When i deploy my Application for first use to Create Reports, the Report creation works fine, But Once I Do Hot Deployment of some code changes To the Server, I was getting This Error.

Sending Email in Android using JavaMail API without using the default/built-in app

For those who want to use JavaMail with Kotlin in 2020:

First: Add these dependencies to your build.gradle file (official JavaMail Maven Dependencies)

implementation 'com.sun.mail:android-mail:1.6.5'

implementation 'com.sun.mail:android-activation:1.6.5'

implementation "org.bouncycastle:bcmail-jdk15on:1.65"

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7"

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7"

BouncyCastle is for security reasons.

Second: Add these permissions to your AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Third: When using SMTP, create a Config file

object Config {
    const val EMAIL_FROM = "[email protected]"
    const val PASS_FROM = "Your_Sender_Password"

    const val EMAIL_TO = "[email protected]"
}

Fourth: Create your Mailer Object

object Mailer {

init {
    Security.addProvider(BouncyCastleProvider())
}

private fun props(): Properties = Properties().also {
        // Smtp server
        it["mail.smtp.host"] = "smtp.gmail.com"
        // Change when necessary
        it["mail.smtp.auth"] = "true"
        it["mail.smtp.port"] = "465"
        // Easy and fast way to enable ssl in JavaMail
        it["mail.smtp.ssl.enable"] = true
    }

// Dont ever use "getDefaultInstance" like other examples do!
private fun session(emailFrom: String, emailPass: String): Session = Session.getInstance(props(), object : Authenticator() {
    override fun getPasswordAuthentication(): PasswordAuthentication {
        return PasswordAuthentication(emailFrom, emailPass)
    }
})

private fun builtMessage(firstName: String, surName: String): String {
    return """
            <b>Name:</b> $firstName  <br/>
            <b>Surname:</b> $surName <br/>
        """.trimIndent()
}

private fun builtSubject(issue: String, firstName: String, surName: String):String {
    return """
            $issue | $firstName, $surName
        """.trimIndent()
}

private fun sendMessageTo(emailFrom: String, session: Session, message: String, subject: String) {
    try {
        MimeMessage(session).let { mime ->
            mime.setFrom(InternetAddress(emailFrom))
            // Adding receiver
            mime.addRecipient(Message.RecipientType.TO, InternetAddress(Config.EMAIL_TO))
            // Adding subject
            mime.subject = subject
            // Adding message
            mime.setText(message)
            // Set Content of Message to Html if needed
            mime.setContent(message, "text/html")
            // send mail
            Transport.send(mime)
        }

    } catch (e: MessagingException) {
        Log.e("","") // Or use timber, it really doesn't matter
    }
}

fun sendMail(firstName: String, surName: String) {
        // Open a session
        val session = session(Config.EMAIL_FROM, Config.PASSWORD_FROM)

        // Create a message
        val message = builtMessage(firstName, surName)

        // Create subject
        val subject = builtSubject(firstName, surName)

        // Send Email
        CoroutineScope(Dispatchers.IO).launch { sendMessageTo(Config.EMAIL_FROM, session, message, subject) }
}

Note

How do I send an HTML email?

I found this way not sure it works for all the CSS primitives

By setting the header property "Content-Type" to "text/html"

mimeMessage.setHeader("Content-Type", "text/html");

now I can do stuff like

mimeMessage.setHeader("Content-Type", "text/html");

mimeMessage.setText ("`<html><body><h1 style =\"color:blue;\">My first Header<h1></body></html>`")

Regards

How to set MimeBodyPart ContentType to "text/html"?

Call MimeMessage.saveChanges() on the enclosing message, which will update the headers by cascading down the MIME structure into a call to MimeBodyPart.updateHeaders() on your body part. It's this updateHeaders call that transfers the content type from the DataHandler to the part's MIME Content-Type header.

When you set the content of a MimeBodyPart, JavaMail internally (and not obviously) creates a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated immediately.

There's no straightforward way to do it in your test program, since you don't have a containing MimeMessage and MimeBodyPart.updateHeaders() isn't public.


Here's a working example that illuminates expected and unexpected outputs:

public class MailTest {

  public static void main( String[] args ) throws Exception {
    Session mailSession = Session.getInstance( new Properties() );
    Transport transport = mailSession.getTransport();

    String text = "Hello, World";
    String html = "<h1>" + text + "</h1>";

    MimeMessage message = new MimeMessage( mailSession );
    Multipart multipart = new MimeMultipart( "alternative" );

    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setText( text, "utf-8" );

    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent( html, "text/html; charset=utf-8" );

    multipart.addBodyPart( textPart );
    multipart.addBodyPart( htmlPart );
    message.setContent( multipart );

    // Unexpected output.
    System.out.println( "HTML = text/html : " + htmlPart.isMimeType( "text/html" ) );
    System.out.println( "HTML Content Type: " + htmlPart.getContentType() );

    // Required magic (violates principle of least astonishment).
    message.saveChanges();

    // Output now correct.    
    System.out.println( "TEXT = text/plain: " + textPart.isMimeType( "text/plain" ) );
    System.out.println( "HTML = text/html : " + htmlPart.isMimeType( "text/html" ) );
    System.out.println( "HTML Content Type: " + htmlPart.getContentType() );
    System.out.println( "HTML Data Handler: " + htmlPart.getDataHandler().getContentType() );
  }
}

Send Mail to multiple Recipients in java

String[] mailAddressTo = new String[3];    
mailAddressTo[0] = emailId_1;    
mailAddressTo[1] = emailId_2;    
mailAddressTo[2] = "[email protected]";

InternetAddress[] mailAddress_TO = new InternetAddress[mailAddressTo.length];

for (int i = 0; i < mailAddressTo.length; i++)
{
    mailAddress_TO[i] = new InternetAddress(mailAddressTo[i]);
}

message.addRecipients(Message.RecipientType.TO, mailAddress_TO);ress_TO = new InternetAddress[mailAddressTo.length]; 

Javamail Could not convert socket to TLS GMail

In my case the problem was solved by deleting the line

prop.put("mail.smtp.starttls.enable", "true");

It may be because of some ssl configuration errors on email server, I'm not sure. Email server administrators never admit it and always blame hosting provider :)

How to customize a Spinner in Android

This worked for me :

ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),R.layout.simple_spinner_item,areas);
            Spinner areasSpinner = (Spinner) view.findViewById(R.id.area_spinner);
            areasSpinner.setAdapter(adapter);

and in my layout folder I created simple_spinner_item:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
// add custom fields here 
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingLeft="?android:attr/listPreferredItemPaddingLeft"
android:paddingRight="?android:attr/listPreferredItemPaddingRight" />

Reset C int array to zero : the fastest way?

You can use memset, but only because our selection of types is restricted to integral types.

In general case in C it makes sense to implement a macro

#define ZERO_ANY(T, a, n) do{\
   T *a_ = (a);\
   size_t n_ = (n);\
   for (; n_ > 0; --n_, ++a_)\
     *a_ = (T) { 0 };\
} while (0)

This will give you C++-like functionality that will let you to "reset to zeros" an array of objects of any type without having to resort to hacks like memset. Basically, this is a C analog of C++ function template, except that you have to specify the type argument explicitly.

On top of that you can build a "template" for non-decayed arrays

#define ARRAY_SIZE(a) (sizeof (a) / sizeof *(a))
#define ZERO_ANY_A(T, a) ZERO_ANY(T, (a), ARRAY_SIZE(a))

In your example it would be applied as

int a[100];

ZERO_ANY(int, a, 100);
// or
ZERO_ANY_A(int, a);

It is also worth noting that specifically for objects of scalar types one can implement a type-independent macro

#define ZERO(a, n) do{\
   size_t i_ = 0, n_ = (n);\
   for (; i_ < n_; ++i_)\
     (a)[i_] = 0;\
} while (0)

and

#define ZERO_A(a) ZERO((a), ARRAY_SIZE(a))

turning the above example into

 int a[100];

 ZERO(a, 100);
 // or
 ZERO_A(a);

Implement a loading indicator for a jQuery AJAX call

I'm guessing you're using jQuery.get or some other jQuery ajax function to load the modal. You can show the indicator before the ajax call, and hide it when the ajax completes. Something like

$('#indicator').show();
$('#someModal').get(anUrl, someData, function() { $('#indicator').hide(); });

Select element by exact match of its content

I found a way that works for me. It is not 100% exact but it eliminates all strings that contain more than just the word I am looking for because I check for the string not containing individual spaces too. By the way you don't need these " ". jQuery knows you are looking for a string. Make sure you only have one space in the :contains( ) part otherwise it won't work.

<p>hello</p>
<p>hello world</p>
$('p:contains(hello):not(:contains( ))').css('font-weight', 'bold');

And yes I know it won't work if you have stuff like <p>helloworld</p>

is it possible to get the MAC address for machine using nmap

With the recent version of nmap 6.40, it will automatically show you the MAC address. example:

nmap 192.168.0.1-255

this command will scan your network from 192.168.0.1 to 255 and will display the hosts with their MAC address on your network.

in case you want to display the mac address for a single client, use this command make sure you are on root or use "sudo"

sudo nmap -Pn 192.168.0.1

this command will display the host MAC address and the open ports.

hope that is helpful.

img tag displays wrong orientation

It happens since original orientation of image is not as we see in image viewer. In such cases image is displayed vertical to us in image viewer but it is horizontal in actual.

To resolve this do following:

  1. Open image in image editor like paint ( in windows ) or ImageMagick ( in linux).

  2. Rotate image left/right.

  3. Save the image.

This should resolve the issue permanently.

How to update Ruby with Homebrew?

To upgrade Ruby with rbenv: Per the rbenv README

  • Update first: brew upgrade rbenv ruby-build
  • See list of Ruby versions: versions available: rbenv install -l
  • Install: rbenv install <selected version>

How to join two tables by multiple columns in SQL?

You should only need to do a single join:

SELECT e.Grade, v.Score, e.CaseNum, e.FileNum, e.ActivityNum
FROM Evaluation e
INNER JOIN Value v ON e.CaseNum = v.CaseNum AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum

Is there a function to make a copy of a PHP array to another?

PHP will copy the array by default. References in PHP have to be explicit.

$a = array(1,2);
$b = $a; // $b will be a different array
$c = &$a; // $c will be a reference to $a

How can I trim leading and trailing white space?

Ad 1) To see white spaces you could directly call print.data.frame with modified arguments:

print(head(iris), quote=TRUE)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width  Species
# 1        "5.1"       "3.5"        "1.4"       "0.2" "setosa"
# 2        "4.9"       "3.0"        "1.4"       "0.2" "setosa"
# 3        "4.7"       "3.2"        "1.3"       "0.2" "setosa"
# 4        "4.6"       "3.1"        "1.5"       "0.2" "setosa"
# 5        "5.0"       "3.6"        "1.4"       "0.2" "setosa"
# 6        "5.4"       "3.9"        "1.7"       "0.4" "setosa"

See also ?print.data.frame for other options.

adb command for getting ip address assigned by operator

download this app from here it will help you to rum all commands. I have run netcfg and it gives the result as attached in screen.

output screen

How to dismiss keyboard iOS programmatically when pressing return

SWIFT 4:

self.view.endEditing(true)

or

Set text field's delegate to current viewcontroller and then:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    textField.resignFirstResponder()

    return true

}

Objective-C:

[self.view endEditing:YES];

or

Set text field's delegate to current viewcontroller and then:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];

    return YES;
}

sql query distinct with Row_Number

Try this:

;WITH CTE AS (
               SELECT DISTINCT id FROM table WHERE fid = 64
             )
SELECT id, ROW_NUMBER() OVER (ORDER BY  id) AS RowNum
  FROM cte
 WHERE fid = 64

C# Threading - How to start and stop a thread

This is how I do it...

public class ThreadA {
    public ThreadA(object[] args) {
        ...
    }
    public void Run() {
        while (true) {
            Thread.sleep(1000); // wait 1 second for something to happen.
            doStuff();
            if(conditionToExitReceived) // what im waiting for...
                break;
        }
        //perform cleanup if there is any...
    }
}

Then to run this in its own thread... ( I do it this way because I also want to send args to the thread)

private void FireThread(){
    Thread thread = new Thread(new ThreadStart(this.startThread));
    thread.start();
}
private void (startThread){
    new ThreadA(args).Run();
}

The thread is created by calling "FireThread()"

The newly created thread will run until its condition to stop is met, then it dies...

You can signal the "main" with delegates, to tell it when the thread has died.. so you can then start the second one...

Best to read through : This MSDN Article

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

I have solved this issue by below steps:

Right click the Maven Project -> Build Path -> Configure Build Path In Order and Export tab, you can see the message like '2 build path entries are missing' Now select 'JRE System Library' and 'Maven Dependencies' checkbox Click OK Now you can see below in all type of Explorers (Package or Project or Navigator)

Nginx: Permission denied for nginx on Ubuntu

just because you don't have the right to acess the file , use

chmod -R 755 /var/log/nginx;

or you can change to sudo then it

Resize iframe height according to content height in it

I just spent the better part of 3 days wrestling with this. I'm working on an application that loads other applications into itself while maintaining a fixed header and a fixed footer. Here's what I've come up with. (I also used EasyXDM, with success, but pulled it out later to use this solution.)

Make sure to run this code AFTER the <iframe> exists in the DOM. Put it into the page that pulls in the iframe (the parent).

// get the iframe
var theFrame = $("#myIframe");
// set its height to the height of the window minus the combined height of fixed header and footer
theFrame.height(Number($(window).height()) - 80);

function resizeIframe() {
    theFrame.height(Number($(window).height()) - 80);
}

// setup a resize method to fire off resizeIframe.
// use timeout to filter out unnecessary firing.
var TO = false;
$(window).resize(function() {
    if (TO !== false) clearTimeout(TO);
    TO = setTimeout(resizeIframe, 500); //500 is time in miliseconds
});

Count unique values in a column in Excel

try - =SUM(IF(FREQUENCY(MATCH(COLUMNRANGE,COLUMNRANGE,0),MATCH(COLUMNRANGE,COLUMNRANGE,0))>0,1))

where COLUMNRANGE = the range where you have these values.

e.g. - =SUM(IF(FREQUENCY(MATCH(C12:C26,C12:C26,0),MATCH(C12:C26,C12:C26,0))>0,1))

Press Ctrl+Shift+Enter to make the formula an array (won't calculate correctly otherwise)

how to add json library

You can also install simplejson.

If you have pip (see https://pypi.python.org/pypi/pip) as your Python package manager you can install simplejson with:

 pip install simplejson

This is similar to the comment of installing with easy_install, but I prefer pip to easy_install as you can easily uninstall in pip with "pip uninstall package".

Play audio file from the assets directory

player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());

Your version would work if you had only one file in the assets directory. The asset directory contents are not actually 'real files' on disk. All of them are put together one after another. So, if you do not specify where to start and how many bytes to read, the player will read up to the end (that is, will keep playing all the files in assets directory)

How to use curl in a shell script?

url=”http://shahkrunalm.wordpress.com“
content=”$(curl -sLI “$url” | grep HTTP/1.1 | tail -1 | awk {‘print $2'})”
if [ ! -z $content ] && [ $content -eq 200 ]
then
echo “valid url”
else
echo “invalid url”
fi

Setting initial values on load with Select2 with Ajax

Change the value after the page loads

$('#data').val('').change();

How to modify a specified commit?

I solved this,

1) by creating new commit with changes i want..

r8gs4r commit 0

2) i know which commit i need to merge with it. which is commit 3.

so, git rebase -i HEAD~4 # 4 represents recent 4 commit (here commit 3 is in 4th place)

3) in interactive rebase recent commit will located at bottom. it will looks alike,

pick q6ade6 commit 3
pick vr43de commit 2
pick ac123d commit 1
pick r8gs4r commit 0

4) here we need to rearrange commit if you want to merge with specific one. it should be like,

parent
|_child

pick q6ade6 commit 3
f r8gs4r commit 0
pick vr43de commit 2
pick ac123d commit 1

after rearrange you need to replace p pick with f (fixup will merge without commit message) or s (squash merge with commit message can change in run time)

and then save your tree.

now merge done with existing commit.

Note: Its not preferable method unless you're maintain on your own. if you have big team size its not a acceptable method to rewrite git tree will end up in conflicts which you know other wont. if you want to maintain you tree clean with less commits can try this and if its small team otherwise its not preferable.....

How to change owner of PostgreSql database?

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

IMPORTANT EDIT!

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


First, connect to admin database and update DB ownership:

psql
postgres=# REASSIGN OWNED BY old_name TO new_name;

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

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

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

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

How to run Unix shell script from Java code?

Yes, it is possible and you have answered it! About good practises, I think it is better to launch commands from files and not directly from your code. So you have to make Java execute the list of commands (or one command) in an existing .bat, .sh , .ksh ... files. Here is an example of executing a list of commands in a file MyFile.sh:

    String[] cmd = { "sh", "MyFile.sh", "\pathOfTheFile"};
    Runtime.getRuntime().exec(cmd);

Android, How to read QR code in my application?

Use a QR library like ZXing... I had very good experience with it, QrDroid is much buggier. If you must rely on an external reader, rely on a standard one like Google Goggles!

SimpleDateFormat and locale based format string

SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE dd MMM yyyy", Locale.ENGLISH);
String formatted = dateFormat.format(the_date_you_want_here);

In LaTeX, how can one add a header/footer in the document class Letter?

Just before your "Content of the letter" line, add \thispagestyle{fancy} and it should show the headers you defined. (It worked for me.)

Here's the full document that I used to test:

\documentclass[12pt]{letter}

\usepackage{fontspec}% font selecting commands 
\usepackage{xunicode}% unicode character macros 
\usepackage{xltxtra} % some fixes/extras 

% page counting, header/footer
\usepackage{fancyhdr}
\usepackage{lastpage}

\pagestyle{fancy}
\lhead{\footnotesize \parbox{11cm}{Draft 1} }
\lfoot{\footnotesize \parbox{11cm}{\textit{2}}}
\cfoot{}
\rhead{\footnotesize 3}
\rfoot{\footnotesize Page \thepage\ of \pageref{LastPage}}
\renewcommand{\headheight}{24pt}
\renewcommand{\footrulewidth}{0.4pt}

\usepackage{lipsum}% provides filler text

\begin{document}
\name{ Joe Laroo }
\signature{ Joe Laroo }
\begin{letter}{ To-Address }
\renewcommand{\today}{ February 16, 2009 }
\opening{ Opening }

\thispagestyle{fancy}% sets the current page style to 'fancy' -- must occur *after* \opening
\lipsum[1-10]% just dumps ten paragraphs of filler text

\closing{ Yours truly, }
\end{letter}
\end{document}

The \opening command sets the page style to firstpage or empty, so you have to use \thispagestyle after that command.

HTML code for INR

Here is one more example based on Intl.NumberFormat native api.

_x000D_
_x000D_
var number = 123456.789;_x000D_
_x000D_
// India uses thousands/lakh/crore separators_x000D_
console.log(new Intl.NumberFormat('en-IN', {_x000D_
  style: 'currency',_x000D_
  currency: 'INR',_x000D_
  // limit to six significant digits (Possible values are from 1 to 21)._x000D_
  maximumSignificantDigits: 6_x000D_
}).format(number));
_x000D_
_x000D_
_x000D_

Invalid hook call. Hooks can only be called inside of the body of a function component

If all the above doesn't work, especially if having big size dependency (like my case), both building and loading were taking a minimum of 15 seconds, so it seems the delay gave a false message "Invalid hook call." So what you can do is give some time to ensure the build is completed before testing.

Get most recent file in a directory on Linux

I needed to do it too, and I found these commands. these work for me:

If you want last file by its date of creation in folder(access time) :

ls -Aru | tail -n 1  

And if you want last file that has changes in its content (modify time) :

ls -Art | tail -n 1  

What does body-parser do with express?

Yes we can work without body-parser. When you don't use that you get the raw request, and your body and headers are not in the root object of request parameter . You will have to individually manipulate all the fields.

Or you can use body-parser, as the express team is maintaining it .

What body-parser can do for you: It simplifies the request.
How to use it: Here is example:

Install npm install body-parser --save

This how to use body-parser in express:

const express = require('express'),
      app = express(),
      bodyParser = require('body-parser');

// support parsing of application/json type post data
app.use(bodyParser.json());

//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));

Link.

https://github.com/expressjs/body-parser.

And then you can get body and headers in root request object . Example

app.post("/posturl",function(req,res,next){
    console.log(req.body);
    res.send("response");
})

How do I include a JavaScript file in another JavaScript file?

Most of solutions shown here imply dynamical loading. I was searching instead for a compiler which assemble all the depended files into a single output file. The same as Less/Sass preprocessors deal with the CSS @import at-rule. Since I didn't find anything decent of this sort, I wrote a simple tool solving the issue.

So here is the compiler, https://github.com/dsheiko/jsic, which replaces $import("file-path") with the requested file content securely. Here is the corresponding Grunt plugin: https://github.com/dsheiko/grunt-jsic.

On the jQuery master branch, they simply concatenate atomic source files into a single one starting with intro.js and ending with outtro.js. That doesn't suits me as it provides no flexibility on the source code design. Check out how it works with jsic:

src/main.js

var foo = $import("./Form/Input/Tel");

src/Form/Input/Tel.js

function() {
    return {
          prop: "",
          method: function(){}
    }
}

Now we can run the compiler:

node jsic.js src/main.js build/mail.js

And get the combined file

build/main.js

var foo = function() {
    return {
          prop: "",
          method: function(){}
    }
};

Why does Java have an "unreachable statement" compiler error?

There is no definitive reason why unreachable statements must be not be allowed; other languages allow them without problems. For your specific need, this is the usual trick:

if (true) return;

It looks nonsensical, anyone who reads the code will guess that it must have been done deliberately, not a careless mistake of leaving the rest of statements unreachable.

Java has a little bit support for "conditional compilation"

http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.21

if (false) { x=3; }

does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.

The rationale for this differing treatment is to allow programmers to define "flag variables" such as:

static final boolean DEBUG = false;

and then write code such as:

if (DEBUG) { x=3; }

The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.

Error in if/while (condition) {: missing Value where TRUE/FALSE needed

I ran into this when checking on a null or empty string

if (x == NULL || x == '') {

changed it to

if (is.null(x) || x == '') {

Adding headers to requests module

From http://docs.python-requests.org/en/latest/user/quickstart/

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get or .post method.

So more specific to your question:

headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)

Using PUT method in HTML form

According to the HTML standard, you can not. The only valid values for the method attribute are get and post, corresponding to the GET and POST HTTP methods. <form method="put"> is invalid HTML and will be treated like <form>, i.e. send a GET request.

Instead, many frameworks simply use a POST parameter to tunnel the HTTP method:

<form method="post" ...>
  <input type="hidden" name="_method" value="put" />
...

Of course, this requires server-side unwrapping.

Reactjs setState() with a dynamic key name?

this.setState({ [`${event.target.id}`]: event.target.value}, () => {
      console.log("State updated: ", JSON.stringify(this.state[event.target.id]));
    });

Please mind the quote character.

How do I instantiate a JAXBElement<String> object?

When you imported the WSDL, you should have an ObjectFactory class which should have bunch of methods for creating various input parameters.

ObjectFactory factory = new ObjectFactory();
JAXBElement<String> createMessageDescription = factory.createMessageDescription("description");
message.setDescription(createMessageDescription);

save a pandas.Series histogram plot to file

Use the Figure.savefig() method, like so:

ax = s.hist()  # s is an instance of Series
fig = ax.get_figure()
fig.savefig('/path/to/figure.pdf')

It doesn't have to end in pdf, there are many options. Check out the documentation.

Alternatively, you can use the pyplot interface and just call the savefig as a function to save the most recently created figure:

import matplotlib.pyplot as plt
s.hist()
plt.savefig('path/to/figure.pdf')  # saves the current figure

How can I connect to a Tor hidden service using cURL in PHP?

Try to add this:

curl_setopt($ch, CURLOPT_HEADER, 1); 
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); 

Can someone explain the dollar sign in Javascript?

In your example the $ has no special significance other than being a character of the name.

However, in ECMAScript 6 (ES6) the $ may represent a Template Literal

var user = 'Bob'
console.log(`We love ${user}.`); //Note backticks
// We love Bob.

Oracle query execution time

One can issue the SQL*Plus command SET TIMING ON to get wall-clock times, but one can't take, for example, fetch time out of that trivially.

The AUTOTRACE setting, when used as SET AUTOTRACE TRACEONLY will suppress output, but still perform all of the work to satisfy the query and send the results back to SQL*Plus, which will suppress it.

Lastly, one can trace the SQL*Plus session, and manually calculate the time spent waiting on events which are client waits, such as "SQL*Net message to client", "SQL*Net message from client".

no operator "<<" matches these operands

It looks like you're comparing strings incorrectly. To compare a string to another, use the std::string::compare function.

Example

     while ((wrong < MAX_WRONG) && (soFar.compare(THE_WORD) != 0)) 

How to ignore the first line of data when processing CSV data?

just add [1:]

example below:

data = pd.read_csv("/Users/xyz/Desktop/xyxData/xyz.csv", sep=',', header=None)**[1:]**

that works for me in iPython

Getting values from JSON using Python

There's a Py library that has a module that facilitates access to Json-like dictionary key-values as attributes: https://github.com/asuiu/pyxtension You can use it as:

j = Json('{"lat":444, "lon":555}')
j.lat + ' ' + j.lon

How to bind inverse boolean properties in WPF?

This one also works for nullable bools.

 [ValueConversion(typeof(bool?), typeof(bool))]
public class InverseBooleanConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (targetType != typeof(bool?))
        {
            throw new InvalidOperationException("The target must be a nullable boolean");
        }
        bool? b = (bool?)value;
        return b.HasValue && !b.Value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return !(value as bool?);
    }

    #endregion
}

Dealing with nginx 400 "The plain HTTP request was sent to HTTPS port" error

According to wikipedia article on status codes. Nginx has a custom error code when http traffic is sent to https port(error code 497)

And according to nginx docs on error_page, you can define a URI that will be shown for a specific error.
Thus we can create a uri that clients will be sent to when error code 497 is raised.

nginx.conf

#lets assume your IP address is 89.89.89.89 and also 
#that you want nginx to listen on port 7000 and your app is running on port 3000

server {
    listen 7000 ssl;
 
    ssl_certificate /path/to/ssl_certificate.cer;
    ssl_certificate_key /path/to/ssl_certificate_key.key;
    ssl_client_certificate /path/to/ssl_client_certificate.cer;

    error_page 497 301 =307 https://89.89.89.89:7000$request_uri;

    location / {
        proxy_pass http://89.89.89.89:3000/;

        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Protocol $scheme;
    }
}

However if a client makes a request via any other method except a GET, that request will be turned into a GET. Thus to preserve the request method that the client came in via; we use error processing redirects as shown in nginx docs on error_page

And thats why we use the 301 =307 redirect.

Using the nginx.conf file shown here, we are able to have http and https listen in on the same port

Easier way to create circle div than using an image?

I have 4 solution to finish this task:

  1. border-radius
  2. clip-path
  3. pseudo elements
  4. radial-gradient

_x000D_
_x000D_
#circle1 {
  background-color: #B90136;
  width: 100px;
  height: 100px;
  border-radius: 50px;/* specify the radius */
}

#circle2 {
  background-color: #B90136;
  width: 100px;/* specify the radius */
  height: 100px;/* specify the radius */
  clip-path: circle();
}

#circle3::before {
  content: "";
  display: block;
  width: 100px;
  height: 100px;
  border-radius: 50px;/* specify the radius */
  background-color: #B90136;
}

#circle4 {
  background-image: radial-gradient(#B90136 70%, transparent 30%);
  height: 100px;/* specify the radius */
  width: 100px;/* specify the radius */
}
_x000D_
<h3>1 border-radius</h3>
<div id="circle1"></div>
<hr/>
<h3>2 clip-path</h3>
<div id="circle2"></div>
<hr/>
<h3>3 pseudo element</h3>
<div id="circle3"></div>
<hr/>
<h3>4 radial-gradient</h3>
<div id="circle4"></div>
_x000D_
_x000D_
_x000D_

Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)

If everything worked just fine and you just started seeing this error, before you do anything else, make sure you're not out of disk space:

df -h

If the volume where the mysql.sock is being created is at 100% use, MySql won't be able to create it and this will be the cause of this error. All you need to do is delete something that's not needed, like old log files.

How can I wait for a thread to finish with .NET?

Add

t1.Join();    // Wait until thread t1 finishes

after you start it, but that won't accomplish much as it's essentialy the same result as running on the main thread!

I can highly recommended reading Joe Albahari's Threading in C# free e-book, if you want to gain an understanding of threading in .NET.

Mock a constructor with parameter

To my knowledge, you can't mock constructors with mockito, only methods. But according to the wiki on the Mockito google code page there is a way to mock the constructor behavior by creating a method in your class which return a new instance of that class. then you can mock out that method. Below is an excerpt directly from the Mockito wiki:

Pattern 1 - using one-line methods for object creation

To use pattern 1 (testing a class called MyClass), you would replace a call like

   Foo foo = new Foo( a, b, c );

with

   Foo foo = makeFoo( a, b, c );

and write a one-line method

   Foo makeFoo( A a, B b, C c ) { 
        return new Foo( a, b, c );
   }

It's important that you don't include any logic in the method; just the one line that creates the object. The reason for this is that the method itself is never going to be unit tested.

When you come to test the class, the object that you test will actually be a Mockito spy, with this method overridden, to return a mock. What you're testing is therefore not the class itself, but a very slightly modified version of it.

Your test class might contain members like

  @Mock private Foo mockFoo;
  private MyClass toTest = spy(new MyClass());

Lastly, inside your test method you mock out the call to makeFoo with a line like

  doReturn( mockFoo )
      .when( toTest )
      .makeFoo( any( A.class ), any( B.class ), any( C.class ));

You can use matchers that are more specific than any() if you want to check the arguments that are passed to the constructor.

If you're just wanting to return a mocked object of your class I think this should work for you. In any case you can read more about mocking object creation here:

http://code.google.com/p/mockito/wiki/MockingObjectCreation

How to skip "are you sure Y/N" when deleting files in batch files

I just want to add that this nearly identical post provides the very useful alternative of using an echo pipe if no force or quiet switch is available. For instance, I think it's the only way to bypass the Y/N prompt in this example.

Echo y|NETDOM COMPUTERNAME WorkComp /Add:Work-Comp

In a general sense you should first look at your command switches for /f, /q, or some variant thereof (for example, Netdom RenameComputer uses /Force, not /f). If there is no switch available, then use an echo pipe.

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.

console.writeline and System.out.println

Here are the primary differences between using System.out/.err/.in and System.console():

  • System.console() returns null if your application is not run in a terminal (though you can handle this in your application)
  • System.console() provides methods for reading password without echoing characters
  • System.out and System.err use the default platform encoding, while the Console class output methods use the console encoding

This latter behaviour may not be immediately obvious, but code like this can demonstrate the difference:

public class ConsoleDemo {
  public static void main(String[] args) {
    String[] data = { "\u250C\u2500\u2500\u2500\u2500\u2500\u2510", 
        "\u2502Hello\u2502",
        "\u2514\u2500\u2500\u2500\u2500\u2500\u2518" };
    for (String s : data) {
      System.out.println(s);
    }
    for (String s : data) {
      System.console().writer().println(s);
    }
  }
}

On my Windows XP which has a system encoding of windows-1252 and a default console encoding of IBM850, this code will write:

???????
?Hello?
???????
+-----+
¦Hello¦
+-----+

Note that this behaviour depends on the console encoding being set to a different encoding to the system encoding. This is the default behaviour on Windows for a bunch of historical reasons.

How to change the data type of a column without dropping the column with query?

ALTER TABLE table_name
MODIFY (column_name data_type);

Google Chrome "window.open" workaround?

menubar must no, or 0, for Google Chrome to open in new window instead of tab.

Bad Request - Invalid Hostname IIS7

If working on local server or you haven't got domain name, delete "Host Name:" field. enter image description here

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

Ajax request returns 200 OK, but an error event is fired instead of success

Use the following code to ensure the response is in JSON format (PHP version)...

header('Content-Type: application/json');
echo json_encode($return_vars);
exit;

Using command line arguments in VBscript

If you need direct access:

WScript.Arguments.Item(0)
WScript.Arguments.Item(1)
...

How to open port in Linux

First, you should disable selinux, edit file /etc/sysconfig/selinux so it looks like this:

SELINUX=disabled
SELINUXTYPE=targeted

Save file and restart system.

Then you can add the new rule to iptables:

iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT

and restart iptables with /etc/init.d/iptables restart

If it doesn't work you should check other network settings.

Adding <script> to WordPress in <head> element

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

check out these two pages on WordPress Codex:

wp_enqueue_script

wp_enqueue_style

How to initailize byte array of 100 bytes in java with all 0's

A new byte array will automatically be initialized with all zeroes. You don't have to do anything.

The more general approach to initializing with other values, is to use the Arrays class.

import java.util.Arrays;

byte[] bytes = new byte[100];
Arrays.fill( bytes, (byte) 1 );

Check/Uncheck all the checkboxes in a table

This will select and deselect all checkboxes:

function checkAll()
{
     var checkboxes = document.getElementsByTagName('input'), val = null;    
     for (var i = 0; i < checkboxes.length; i++)
     {
         if (checkboxes[i].type == 'checkbox')
         {
             if (val === null) val = checkboxes[i].checked;
             checkboxes[i].checked = val;
         }
     }
 }

Demo

Update:

You can use querySelectAll directly on the table to get the list of checkboxes instead of searching the whole document, but It might not be compatible with old browsers so you need to check that first:

 function checkAll()
 {
     var table = document.getElementById ('dataTable');
     var checkboxes = table.querySelectorAll ('input[type=checkbox]');
     var val = checkboxes[0].checked;
     for (var i = 0; i < checkboxes.length; i++) checkboxes[i].checked = val;
 }

Or to be more specific for the provided html structure in the OP question, this would be more efficient when selecting the checkboxes as it will access them directly instead of searching for them:

function checkAll (tableID)
{
    var table = document.getElementById (tableID);
    var val = table.rows[0].cells[0].children[0].checked;
    for (var i = 1; i < table.rows.length; i++)
    {
        table.rows[i].cells[0].children[0].checked = val;
    }
}

Demo

What is the difference between min SDK version/target SDK version vs. compile SDK version?

The min sdk version is the minimum version of the Android operating system required to run your application.

The target sdk version is the version of Android that your app was created to run on.

The compile sdk version is the the version of Android that the build tools uses to compile and build the application in order to release, run, or debug.

Usually the compile sdk version and the target sdk version are the same.

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

From SQLServer 2012 more elegant alter role:

use mydb
go

ALTER ROLE db_datareader
  ADD MEMBER MYUSER 
go
ALTER ROLE db_datawriter
  ADD MEMBER MYUSER 
go

Lambda expression to convert array/List of String to array/List of Integers

For List :

List<Integer> intList 
 = stringList.stream().map(Integer::valueOf).collect(Collectors.toList());

For Array :

int[] intArray = Arrays.stream(stringArray).mapToInt(Integer::valueOf).toArray();

Saving image from PHP URL

$img_file='http://www.somedomain.com/someimage.jpg'

$img_file=file_get_contents($img_file);

$file_loc=$_SERVER['DOCUMENT_ROOT'].'/some_dir/test.jpg';

$file_handler=fopen($file_loc,'w');

if(fwrite($file_handler,$img_file)==false){
    echo 'error';
}

fclose($file_handler);

Response Content type as CSV

Just Use like that

Response.Clear();
Response.ContentType = "application/CSV";
Response.AddHeader("content-disposition", "attachment; filename=\"" + filename + ".csv\"");
Response.Write(t.ToString());
Response.End();

SQL Server 2008 can't login with newly created user

You'll likely need to check the SQL Server error logs to determine the actual state (it's not reported to the client for security reasons.) See here for details.

Repeat rows of a data.frame

If you can repeat the whole thing, or subset it first then repeat that, then this similar question may be helpful. Once again:

library(mefa)
rep(mtcars,10) 

or simply

mefa:::rep.data.frame(mtcars)

Show history of a file?

The main question for me would be, what are you actually trying to find out? Are you trying to find out, when a certain set of changes was introduced in that file?

You can use git blame for this, it will anotate each line with a SHA1 and a date when it was changed. git blame can also tell you when a certain line was deleted or where it was moved if you are interested in that.

If you are trying to find out, when a certain bug was introduced, git bisect is a very powerfull tool. git bisect will do a binary search on your history. You can use git bisect start to start bisecting, then git bisect bad to mark a commit where the bug is present and git bisect good to mark a commit which does not have the bug. git will checkout a commit between the two and ask you if it is good or bad. You can usually find the faulty commit within a few steps.

Since I have used git, I hardly ever found the need to manually look through patch histories to find something, since most often git offers me a way to actually look for the information I need.

If you try to think less of how to do a certain workflow, but more in what information you need, you will probably many workflows which (in my opinion) are much more simple and faster.

Is there a cross-browser onload event when clicking the back button?

I thought this would be for "onunload", not page load, since aren't we talking about firing an event when hitting "Back"? $document.ready() is for events desired on page load, no matter how you get to that page (i.e. redirect, opening the browser to the URL directly, etc.), not when clicking "Back", unless you're talking about what to fire on the previous page when it loads again. And I'm not sure the page isn't getting cached as I've found that Javascripts still are, even when $document.ready() is included in them. We've had to hit Ctrl+F5 when editing our scripts that have this event whenever we revise them and we want test the results in our pages.

$(window).unload(function(){ alert('do unload stuff here'); }); 

is what you'd want for an onunload event when hitting "Back" and unloading the current page, and would also fire when a user closes the browser window. This sounded more like what was desired, even if I'm outnumbered with the $document.ready() responses. Basically the difference is between an event firing on the current page while it's closing or on the one that loads when clicking "Back" as it's loading. Tested in IE 7 fine, can't speak for the other browsers as they aren't allowed where we are. But this might be another option.

Shortcut for echo "<pre>";print_r($myarray);echo "</pre>";

If you are using XDebug simply use

var_dump($variable);

This will dump the variable like print_r does - but nicely formatted and in a <pre>.

(If you don't use XDebug then var_dump will be as badly formated as print_r without <pre>.)

Best way to "push" into C# array

As said before, List provides functionality to add elements in a clean way, to do the same with arrays, you have to resize them to accomodate extra elements, see code below:

int[] arr = new int[2];
arr[0] = 1;
arr[1] = 2;
//without this line we'd get a exception
Array.Resize(ref arr, 3);
arr[2] = 3;

Regarding your idea with loop:

elements of an array are set to their default values when array is initialized. So your approach would be good, if you want to fill "blanks" in array holding reference types (which have default value null).

But it wouldn't work with value types, as they are initialized with 0!

SQL Server insert if not exists best practice

Another option is to left join your Results table with your existing competitors Table and find the new competitors by filtering the distinct records that don´t match int the join:

INSERT Competitors (cName)
SELECT  DISTINCT cr.Name
FROM    CompResults cr left join
        Competitors c on cr.Name = c.cName
where   c.cName is null

New syntax MERGE also offer a compact, elegant and efficient way to do that:

MERGE INTO Competitors AS Target
USING (SELECT DISTINCT Name FROM CompResults) AS Source ON Target.Name = Source.Name
WHEN NOT MATCHED THEN
    INSERT (Name) VALUES (Source.Name);

How can I run specific migration in laravel

use this command php artisan migrate --path=/database/migrations/my_migration.php it worked for me..

XAMPP on Windows - Apache not starting

I spent over 3 hours to find out solution. Actually port 80 was being used by "system" service so I tried to change port from 80 to 8080 in "httpd" file but same problem raised "port 80 is used by system". It had driven me mad for 3 hours as every thing was changed like port , localhost server etc pointing to 8080.

At last I found mistake that was server root. Basically "Server Root" in "httpd" should be pointing to apache foler of xampp. In my case that's was

ServerRoot "xampp/apache"

I just changed it as follows:

ServerRoot "C:/xampp/apache" 

It has worked successfully and now everything is running with OK status.

append option to select menu?

You can also use insertAdjacentHTML function:

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

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

Makefile, header dependencies

Here's a two-liner:

CPPFLAGS = -MMD
-include $(OBJS:.c=.d)

This works with the default make recipe, as long as you have a list of all your object files in OBJS.

Entity Framework Join 3 Tables

I think it will be easier using syntax-based query:

var entryPoint = (from ep in dbContext.tbl_EntryPoint
                 join e in dbContext.tbl_Entry on ep.EID equals e.EID
                 join t in dbContext.tbl_Title on e.TID equals t.TID
                 where e.OwnerID == user.UID
                 select new {
                     UID = e.OwnerID,
                     TID = e.TID,
                     Title = t.Title,
                     EID = e.EID
                 }).Take(10);

And you should probably add orderby clause, to make sure Top(10) returns correct top ten items.

How do you Change a Package's Log Level using Log4j?

Which app server are you using? Each one puts its logging config in a different place, though most nowadays use Commons-Logging as a wrapper around either Log4J or java.util.logging.

Using Tomcat as an example, this document explains your options for configuring logging using either option. In either case you need to find or create a config file that defines the log level for each package and each place the logging system will output log info (typically console, file, or db).

In the case of log4j this would be the log4j.properties file, and if you follow the directions in the link above your file will start out looking like:

log4j.rootLogger=DEBUG, R 
log4j.appender.R=org.apache.log4j.RollingFileAppender 
log4j.appender.R.File=${catalina.home}/logs/tomcat.log 
log4j.appender.R.MaxFileSize=10MB 
log4j.appender.R.MaxBackupIndex=10 
log4j.appender.R.layout=org.apache.log4j.PatternLayout 
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

Simplest would be to change the line:

log4j.rootLogger=DEBUG, R

To something like:

log4j.rootLogger=WARN, R

But if you still want your own DEBUG level output from your own classes add a line that says:

log4j.category.com.mypackage=DEBUG

Reading up a bit on Log4J and Commons-Logging will help you understand all this.

How to clear all inputs, selects and also hidden fields in a form using jQuery?

To clear all inputs, including hidden fields, using JQuery:

// Behold the power of JQuery.
$('input').val('');

Selects are harder, because they have a fixed list. Do you want to clear that list, or just the selection.

Could be something like

$('option').attr('selected', false);

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

To remove the blue overlay on mobiles, you can use one of the following:

-webkit-tap-highlight-color: transparent; /* transparent with keyword */
-webkit-tap-highlight-color: rgba(0,0,0,0); /* transparent with rgba */
-webkit-tap-highlight-color: hsla(0,0,0,0); /* transparent with hsla */
-webkit-tap-highlight-color: #00000000; /* transparent with hex with alpha */
-webkit-tap-highlight-color: #0000; /* transparent with short hex with alpha */

However, unlike other properties, you can't use

-webkit-tap-highlight-color: none; /* none keyword */

In DevTools, this will show up as an 'invalid property value' or something.


To remove the blue/black/orange outline when focused, use this:

:focus {
    outline: none; /* no outline - for most browsers */
    box-shadow: none; /* no box shadow - for some browsers or if you are using Bootstrap */
}

The reason why I removed the box-shadow is because Bootsrap (and some browsers) sometimes add it to focused elements, so you can remove it using this.

But if anyone is navigating with a keyboard, they will get very confused indeed, because they rely on this outline to navigate. So you can replace it instead

:focus {
    outline: 100px dotted #f0f; /* 100px dotted pink outline */
}

You can target taps on mobile using :hover or :active, so you could use those to help, possibly. Or it could get confusing.


Full code:

element {
    -webkit-tap-highlight-color: transparent; /* remove tap highlight */
}
element:focus {
    outline: none; /* remove outline */
    box-shadow: none; /* remove box shadow */
}

Other information:

  • If you would like to customise the -webkit-tap-highlight-color then you should set it to a semi-transparent color so the element underneath doesn't get hidden when tapped
  • Please don't remove the outline from focused elements, or add some more styles for them.
  • -webkit-tap-highlight-color has not got great browser support and is not standard. You can still use it, but watch out!

How can I execute a python script from an html button?

you could use text files to trasfer the data using PHP and reading the text file in python

Add common prefix to all cells in Excel

Type this in cell B1, and copy down...

="X"&A1

This would also work:

=CONCATENATE("X",A1)

And here's one of many ways to do this in VBA (Disclaimer: I don't code in VBA very often!):

Sub AddX()
    Dim i As Long

    With ActiveSheet
    For i = 1 To .Range("A65536").End(xlUp).Row Step 1
        .Cells(i, 2).Value = "X" & Trim(Str(.Cells(i, 1).Value))
    Next i
    End With
End Sub

How to center form in bootstrap 3

The total columns in a row has to add up to 12. So you can do col-md-4 col-md-offset-4. So your breaking up your columns into 3 groups of 4 columns each. Right now you have a 4 column form with an offset by 6 so you are only getting 2 columns to the right side of your form. You can also do col-md-8 col-md-offset-2 which would give you a 8 column form with 2 columns each of space left and right or col-md-6 col-md-offset-3 (6 column form with 3 columns space on each side), etc.

Replace all particular values in a data frame

Here are a couple dplyr options:

library(dplyr)

# all columns:
df %>% 
  mutate_all(~na_if(., ''))

# specific column types:
df %>% 
  mutate_if(is.factor, ~na_if(., ''))

# specific columns:  
df %>% 
  mutate_at(vars(A, B), ~na_if(., ''))

# or:
df %>% 
  mutate(A = replace(A, A == '', NA))

# replace can be used if you want something other than NA:
df %>% 
  mutate(A = as.character(A)) %>% 
  mutate(A = replace(A, A == '', 'used to be empty'))

How to start MySQL server on windows xp

You also need to configure and start the MySQL server. This will probably help

How to achieve ripple animation using support library?

It's very simple ;-)

First you must create two drawable file one for old api version and another one for newest version, Of course! if you create the drawable file for newest api version android studio suggest you to create old one automatically. and finally set this drawable to your background view.

Sample drawable for new api version (res/drawable-v21/ripple.xml):

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:colorControlHighlight">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/colorPrimary" />
            <corners android:radius="@dimen/round_corner" />
        </shape>
    </item>
</ripple>

Sample drawable for old api version (res/drawable/ripple.xml)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/colorPrimary" />
    <corners android:radius="@dimen/round_corner" />
</shape>

For more info about ripple drawable just visit this: https://developer.android.com/reference/android/graphics/drawable/RippleDrawable.html

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

TL;DR

Just returning response()->json($promotion) won't solve the issue in this question. $promotion is an Eloquent object, which Laravel will automatically json_encode for the response. The json encoding is failing because of the img property, which is a PHP stream resource, and cannot be encoded.

Details

Whatever you return from your controller, Laravel is going to attempt to convert to a string. When you return an object, the object's __toString() magic method will be invoked to make the conversion.

Therefore, when you just return $promotion from your controller action, Laravel is going to call __toString() on it to convert it to a string to display.

On the Model, __toString() calls toJson(), which returns the result of json_encode. Therefore, json_encode is returning false, meaning it is running into an error.

Your dd shows that your img attribute is a stream resource. json_encode cannot encode a resource, so this is probably causing the failure. You should add your img attribute to the $hidden property to remove it from the json_encode.

class Promotion extends Model
{
    protected $hidden = ['img'];

    // rest of class
}

What is the meaning of {...this.props} in Reactjs

It is ES-6 feature. It means you extract all the properties of props in div.{... }

operator is used to extract properties of an object.

Get lengths of a list in a jinja2 template

<span>You have {{products|length}} products</span>

You can also use this syntax in expressions like

{% if products|length > 1 %}

jinja2's builtin filters are documented here; and specifically, as you've already found, length (and its synonym count) is documented to:

Return the number of items of a sequence or mapping.

So, again as you've found, {{products|count}} (or equivalently {{products|length}}) in your template will give the "number of products" ("length of list")

How do I use WebRequest to access an SSL encrypted site using https?

You're doing it the correct way but users may be providing urls to sites that have invalid SSL certs installed. You can ignore those cert problems if you put this line in before you make the actual web request:

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

where AcceptAllCertifications is defined as

public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    return true;
}

.htaccess rewrite to redirect root URL to subdirectory

I have found that in order to avoid circular redirection, it is important to limit the scope of redirection to root directory. I would have used:

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/$
RewriteRule (.*) http://www.example.com/store [R=301,L]

jQuery click event on radio button doesn't get fired

put ur js code under the form html or use $(document).ready(function(){}) and try this.

$('#inline_content input[type="radio"]').click(function(){
                if($(this).val() == "walk_in"){
                    alert('ok');
                }
});

Remove a specific character using awk or sed

tr can be more concise for removing characters than sed or awk, especially when you want to remove different characters from a string.

Removing double quotes:

echo '"Hi"' | tr -d \"
# Produces Hi without quotes

Removing different kinds of brackets:

echo '[{Hi}]' | tr -d {}[]
# Produces Hi without brackets

-d stands for "delete".

scp via java

I ended up using Jsch- it was pretty straightforward, and seemed to scale up pretty well (I was grabbing a few thousand files every few minutes).

org.apache.jasper.JasperException: Unable to compile class for JSP:

This line of yours:

<%@ page import="pageNumber.*, java.util.*, java.io.*" %>

Requires an @ symbol before % like this:

<%@ page import="pageNumber.*, java.util.*, java.io.*" @%>

Iterate through pairs of items in a Python list

You can zip the list with itself sans the first element:

a = [5, 7, 11, 4, 5]

for previous, current in zip(a, a[1:]):
    print(previous, current)

This works even if your list has no elements or only 1 element (in which case zip returns an empty iterable and the code in the for loop never executes). It doesn't work on generators, only sequences (tuple, list, str, etc).

Namespace not recognized (even though it is there)

The question has already been awarded, but there are additional details not yet described that need to be checked.

I too was having this behavior, where project B was referenced in project A, but the namespace of project B was not recognized in project A. After some digging, I found my path was too long. By reducing the path of the projects (both A and B) the references became visible and available.

I tested this theory by creating project C at a much lesser path depth. I referenced project C in project A. The references worked correctly as expected. I then removed project C from the solution, merely moved project C to a deep path, the same as project B, and added project C back to the solution, and tried to compile. I then had no visibility to project C objects any longer.

Pandas - replacing column values

Yes, you are using it incorrectly, Series.replace() is not inplace operation by default, it returns the replaced dataframe/series, you need to assign it back to your dataFrame/Series for its effect to occur. Or if you need to do it inplace, you need to specify the inplace keyword argument as True Example -

data['sex'].replace(0, 'Female',inplace=True)
data['sex'].replace(1, 'Male',inplace=True)

Also, you can combine the above into a single replace function call by using list for both to_replace argument as well as value argument , Example -

data['sex'].replace([0,1],['Female','Male'],inplace=True)

Example/Demo -

In [10]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

In [11]: data['sex'].replace([0,1],['Female','Male'],inplace=True)

In [12]: data
Out[12]:
      sex  split
0    Male      0
1  Female      1
2    Male      0
3  Female      1

You can also use a dictionary, Example -

In [15]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

In [16]: data['sex'].replace({0:'Female',1:'Male'},inplace=True)

In [17]: data
Out[17]:
      sex  split
0    Male      0
1  Female      1
2    Male      0
3  Female      1

How to POST a JSON object to a JAX-RS service

I faced the same 415 http error when sending objects, serialized into JSON, via PUT/PUSH requests to my JAX-rs services, in other words my server was not able to de-serialize the objects from JSON. In my case, the server was able to serialize successfully the same objects in JSON when sending them into its responses.

As mentioned in the other responses I have correctly set the Accept and Content-Type headers to application/json, but it doesn't suffice.

Solution

I simply forgot a default constructor with no parameters for my DTO objects. Yes this is the same reasoning behind @Entity objects, you need a constructor with no parameters for the ORM to instantiate objects and populate the fields later.

Adding the constructor with no parameters to my DTO objects solved my issue. Here follows an example that resembles my code:

Wrong

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

Right

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {

    public NumberDTO() {
    }

    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

I lost hours, I hope this'll save yours ;-)

How to get text with Selenium WebDriver in Python

This is the correct answer. It worked!!

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome("E:\\Python\\selenium\\webdriver\\chromedriver.exe")
driver.get("https://www.tatacliq.com/global-desi-navy-embroidered-kurta/p-mp000000000876745")
driver.set_page_load_timeout(45)
driver.maximize_window()
driver.implicitly_wait(2)
driver.get_screenshot_as_file("E:\\Python\\Tatacliq.png")
print ("Executed Successfully")
driver.find_element_by_xpath("//div[@class='pdp-promo-title pdp-title']").click()
SpecialPrice = driver.find_element_by_xpath("//div[@class='pdp-promo-title pdp-title']").text
print(SpecialPrice)

Adding value to input field with jQuery

You have to escape [ and ]. Try this:

$('.button').click(function(){
    var fieldID = $(this).prev().attr("id");
    fieldID = fieldID.replace(/([\[\]]+)/g, "\\$1");
    $('#' + fieldID).val("hello world");
});

Demo: http://jsfiddle.net/7RJtf/1/

Is there any way to delete local commits in Mercurial?

As everyone else is pointing out you should probably just pull and then merge the heads, but if you really want to get rid of your commits without any of the EditingHistory tools then you can just hg clone -r your repo to get all but those changes.

This doesn't delete them from the original repository, but it creates a new clone that doesn't have them. Then you can delete the repo you modified (if you'd like).

Extend a java class from one file in another java file

Java doesn't use includes the way C does. Instead java uses a concept called the classpath, a list of resources containing java classes. The JVM can access any class on the classpath by name so if you can extend classes and refer to types simply by declaring them. The closes thing to an include statement java has is 'import'. Since classes are broken up into namespaces like foo.bar.Baz, if you're in the qux package and you want to use the Baz class without having to use its full name of foo.bar.Baz, then you need to use an import statement at the beginning of your java file like so: import foo.bar.Baz

Multiple left-hand assignment with JavaScript

Try this:

var var1=42;
var var2;

alert(var2 = var1); //show result of assignment expression is assigned value
alert(var2); // show assignment did occur.

Note the single '=' in the first alert. This will show that the result of an assignment expression is the assigned value, and the 2nd alert will show you that assignment did occur.

It follows logically that assignment must have chained from right to left. However, since this is all atomic to the javascript (there's no threading) a particular engine may choose to actually optimize it a little differently.

git: fatal: Could not read from remote repository

In your .git/config file

[remote "YOUR_APP_NAME"]
    url = [email protected]:YOUR_APP_NAME.git
    fetch = +refs/heads/*:refs/remotes/YOUR_APP_NAME/*

And simply

git push YOUR_APP_NAME master:master 

Makefile If-Then Else and Loops

Have you tried the GNU make documentation? It has a whole section about conditionals with examples.

What is the curl error 52 "empty reply from server"?

This can happen if curl is asked to do plain HTTP on a server that does HTTPS.

Example:

$ curl http://google.com:443
curl: (52) Empty reply from server

How to round up a number to nearest 10?

Hey i modify Kenny answer and custom it not always round function now it can be ceil and floor function

function roundToTheNearestAnything($value, $roundTo,$type='round')
    {
        $mod = $value%$roundTo;
        if($type=='round'){
            return $value+($mod<($roundTo/2)?-$mod:$roundTo-$mod);
        }elseif($type=='floor'){
            return $value+($mod<($roundTo/2)?-$mod:-$mod);
        }elseif($type=='ceil'){
            return $value+($mod<($roundTo/2)?$roundTo-$mod:$roundTo-$mod);
        }

    }

echo roundToTheNearestAnything(1872,25,'floor'); // 1850<br>
echo roundToTheNearestAnything(1872,25,'ceil'); // 1875<br>
echo roundToTheNearestAnything(1872,25,'round'); // 1875

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

We were getting this issue even after updating to the latest Adobe Reader version.

Two different methods solved this issue for us:

  • Using the free version of Foxit Reader application in place of Adobe Reader
  • But, since most of our clients use Adobe Reader, so instead of requiring users to use Foxit Reader, we started using window.open(url) to open the pdf instead of window.location.href = url. Adobe was losing the file handle on for some reason in different iframes when the pdf was opened using the window.location.href method.

How can I limit possible inputs in a HTML5 "number" element?

I had this problem before and I solved it using a combination of html5 number type and jQuery.

<input maxlength="2" min="0" max="59" name="minutes" value="0" type="number"/>

script:

$("input[name='minutes']").on('keyup keypress blur change', function(e) {
    //return false if not 0-9
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
       return false;
    }else{
        //limit length but allow backspace so that you can still delete the numbers.
        if( $(this).val().length >= parseInt($(this).attr('maxlength')) && (e.which != 8 && e.which != 0)){
            return false;
        }
    }
});

I don't know if the events are a bit overkill but it solved my problem. JSfiddle

How can I resolve "Your requirements could not be resolved to an installable set of packages" error?

I use Windows 10 machine working with PHP 8 and Lavarel 8 and I got the same error, I used the following command :-

composer update --ignore-platform-reqs

to update all the packages regardless of the version conflicts.

How to push local changes to a remote git repository on bitbucket

Use git push origin master instead.

You have a repository locally and the initial git push is "pushing" to it. It's not necessary to do so (as it is local) and it shows everything as up-to-date. git push origin master specifies a a remote repository (origin) and the branch located there (master).

For more information, check out this resource.

How can I conditionally require form inputs with AngularJS?

For Angular2

<input type='email' 
    [(ngModel)]='contact.email'
    [required]='!contact.phone' >

When to use Comparable and Comparator

Comparable is the default natural sorting order provided for numerical values are ascending and for strings are alphabetical order. for eg:

Treeset t=new Treeset();
t.add(2);
t.add(1);
System.out.println(t);//[1,2]

Comparator is the custom sorting order implemented in custom myComparator class by overriding a compare method for eg:

Treeset t=new Treeset(new myComparator());
t.add(55);
t.add(56);
class myComparator implements Comparator{
public int compare(Object o1,Object o2){
//Descending Logic
}
}
System.out.println(t);//[56,55]

How to install CocoaPods?

Year 2020, Installing Cocoapods v1.9.1 in Mac OS Catalina

  1. First setup your Xcode version in your mac using terminal.

$ sudo xcode-select -switch /Applications/Xcode.app

  1. Next, Install cocoapods using terminal.

$ sudo gem install cocoapods

For More information, visit official website https://cocoapods.org/

angular2: how to copy object into another object

Try this.

Copy an Array :

const myCopiedArray  = Object.assign([], myArray);

Copy an object :

const myCopiedObject = Object.assign({}, myObject);

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

Open WSDL file and find:

<soap:operation soapAction="[actionNameIsHere]" style="document"/>

Add to the requests header [request send to service]:

'soapAction' : '[actionNameIsHere]'

This work for me.

For devs. using node-soap [ https://github.com/vpulim/node-soap ] - example:

var soap = require('soap');
var options = {
   ...your options...
   forceSoap12Headers: true
}
soap.createClient(
        wsdl, options,
            function(err, client) {
                if(err) {
                    return callBack(err, result);
                }
                client.addHttpHeader('soapAction', '[actionNameIsHere]');
                ...your code - request send...
            });

Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

For linux / ubuntu if the command

npm install -g <package_name>

npm WARN deprecated [email protected]: Please note that v5.0.1+ of superagent removes User-Agent header by default, therefore you may need to add it yourself (e.g. GitHub blocks requests without a User-Agent header).  This notice will go away with v5.0.2+ once it is released.

npm ERR! path ../lib/node_modules/<package_name>/bin/..

npm ERR! code EACCES

npm ERR! errno -13

npm ERR! syscall symlink

npm ERR! Error: EACCES: permission denied, symlink '../lib/node_modules
/<package_name>/bin/..' -> '/usr/local/bin/<package_name>'

npm ERR!  { [Error: EACCES: permission denied, symlink '../lib/node_modules/<package_name>/bin/..' -> '/usr/local/bin/<package_name>']

npm ERR!   cause:
npm ERR!    { Error: EACCES: permission denied, symlink '../lib/node_modules/<package_name>/bin/..' -> '/usr/local/bin/<package_name>'

npm ERR!      errno: -13,

npm ERR!      code: 'EACCES',

npm ERR!      syscall: 'symlink',

npm ERR!      path: '../lib/node_modules/<package_name>/bin/..',
npm ERR!      dest: '/usr/local/bin/ionic' },

npm ERR!   stack:
npm ERR!    'Error: EACCES: permission denied, symlink \'../lib/node_modules/ionic/bin/ionic\' -> \'/usr/local/bin/ionic\'',

npm ERR!   errno: -13,

npm ERR!   code: 'EACCES',

npm ERR!   syscall: 'symlink',

npm ERR!   path: '../lib/node_modules/<package-name>/bin/<package-name>',

npm ERR!   dest: '/usr/local/bin/<package-name>' }

npm ERR! 

npm ERR! The operation was rejected by your operating system.

npm ERR! It is likely you do not have the permissions to access this file as the current user

npm ERR! 

npm ERR! If you believe this might be a permissions issue, please double-check the

npm ERR! permissions of the file and its containing directories, or try running

npm ERR! the command again as root/Administrator (though this is not recommended).


npm ERR! A complete log of this run can be found in:

npm ERR!     /home/User/.npm/_logs/2019-07-29T01_20_10_566Z-debug.log

Fix : Install with root permissions

sudo npm install <package_name> -g

Magento addFieldToFilter: Two fields, match as OR, not AND

I also tried to get the field1 = 'a' OR field2 = 'b'

Your code didn't work for me.

Here is my solution

$results = Mage::getModel('xyz/abc')->getCollection();
$results->addFieldToSelect('name');
$results->addFieldToSelect('keywords');
$results->addOrder('name','ASC');
$results->setPageSize(5);

$results->getSelect()->where("keywords like '%foo%' or additional_keywords  like '%bar%'");

$results->load();

echo json_encode($results->toArray());

It gives me

SELECT name, keywords FROM abc WHERE keywords like '%foo%' OR additional_keywords like '%bar%'.

It is maybe not the "magento's way" but I was stuck 5 hours on that.

Hope it will help

Set environment variables on Mac OS X Lion

Simplified Explanation

This post/question is kind of old, so I will answer a simplified version for OS X Lion users. By default, OSX Lion does not have any of the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

At most, if you've done anything in the terminal you might see ~/.bash_history

What It Means

You must create the file to set your default bash commands (commonly in ~/.bashrc). To do this, use any sort of editor, though it's more simple to do it within the terminal:

  1. %> emacs .profile
  2. [from w/in emacs type:] source ~/.bashrc
  3. [from w/in emacs type:] Ctrl + x Ctrl + s (to save the file)
  4. [from w/in emacs type:] Ctrl + x Ctrl + c (to close emacs)
  5. %> emacs .bashrc
  6. [from w/in emacs type/paste all your bash commands, save, and exit]

The next time you quit and reload the terminal, it should load all your bash preferences. For good measure, it's usually a good idea to separate your commands into useful file names. For instance, from within ~/.bashrc, you should have a source ~/.bash_aliases and put all your alias commands in ~/.bash_aliases.

Linux/Unix command to determine if process is running?

While pidof and pgrep are great tools for determining what's running, they are both, unfortunately, unavailable on some operating systems. A definite fail safe would be to use the following: ps cax | grep command

The output on Gentoo Linux:

14484 ?        S      0:00 apache2
14667 ?        S      0:00 apache2
19620 ?        Sl     0:00 apache2
21132 ?        Ss     0:04 apache2

The output on OS X:

42582   ??  Z      0:00.00 (smbclient)
46529   ??  Z      0:00.00 (smbclient)
46539   ??  Z      0:00.00 (smbclient)
46547   ??  Z      0:00.00 (smbclient)
46586   ??  Z      0:00.00 (smbclient)
46594   ??  Z      0:00.00 (smbclient)

On both Linux and OS X, grep returns an exit code so it's easy to check if the process was found or not:

#!/bin/bash
ps cax | grep httpd > /dev/null
if [ $? -eq 0 ]; then
  echo "Process is running."
else
  echo "Process is not running."
fi

Furthermore, if you would like the list of PIDs, you could easily grep for those as well:

ps cax | grep httpd | grep -o '^[ ]*[0-9]*'

Whose output is the same on Linux and OS X:

3519 3521 3523 3524

The output of the following is an empty string, making this approach safe for processes that are not running:

echo ps cax | grep aasdfasdf | grep -o '^[ ]*[0-9]*'

This approach is suitable for writing a simple empty string test, then even iterating through the discovered PIDs.

#!/bin/bash
PROCESS=$1
PIDS=`ps cax | grep $PROCESS | grep -o '^[ ]*[0-9]*'`
if [ -z "$PIDS" ]; then
  echo "Process not running." 1>&2
  exit 1
else
  for PID in $PIDS; do
    echo $PID
  done
fi

You can test it by saving it to a file (named "running") with execute permissions (chmod +x running) and executing it with a parameter: ./running "httpd"

#!/bin/bash
ps cax | grep httpd
if [ $? -eq 0 ]; then
  echo "Process is running."
else
  echo "Process is not running."
fi

WARNING!!!

Please keep in mind that you're simply parsing the output of ps ax which means that, as seen in the Linux output, it is not simply matching on processes, but also the arguments passed to that program. I highly recommend being as specific as possible when using this method (e.g. ./running "mysql" will also match 'mysqld' processes). I highly recommend using which to check against a full path where possible.


References:

http://linux.about.com/od/commands/l/blcmdl1_ps.htm

http://linux.about.com/od/commands/l/blcmdl1_grep.htm

ESLint - "window" is not defined. How to allow global variables in package.json

There is a builtin environment: browser that includes window.

Example .eslintrc.json:

"env": {
    "browser": true,
    "node": true,
    "jasmine": true
  },

More information: http://eslint.org/docs/user-guide/configuring.html#specifying-environments

Also see the package.json answer by chevin99 below.

Authentication failed to bitbucket

Windows start up menu,Search for windows credential manager. Search for bitbucket url, Try updating password there.. and do git operation again. It should work.

Convert unix time to readable date in pandas dataframe

Assuming we imported pandas as pd and df is our dataframe

pd.to_datetime(df['date'], unit='s')

works for me.

Call break in nested if statements

You need that it breaks the outer if statement. Why do you use second else?

IF condition THEN  
    IF condition THEN 
        sequence 1
    // ELSE sequence 4
       // break //?  
    // ENDIF    
ELSE    
    sequence 3    
ENDIF

sequence 4

Send FormData and String Data Together Through JQuery AJAX?

You can try this:

var fd = new FormData();
var data = [];           //<---------------declare array here
var file_data = object.get(0).files[i];
var other_data = $('form').serialize();

data.push(file_data);  //<----------------push the data here
data.push(other_data); //<----------------and this data too

fd.append("file", data);  //<---------then append this data

Avoiding NullPointerException in Java

This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don't know or don't trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on returning nulls to indicate something thus requiring the caller to check for nulls.

To put this another way, there are two instances where null checking comes up:

  1. Where null is a valid response in terms of the contract; and

  2. Where it isn't a valid response.

(2) is easy. Either use assert statements (assertions) or allow failure (for example, NullPointerException). Assertions are a highly-underused Java feature that was added in 1.4. The syntax is:

assert <condition>

or

assert <condition> : <object>

where <condition> is a boolean expression and <object> is an object whose toString() method's output will be included in the error.

An assert statement throws an Error (AssertionError) if the condition is not true. By default, Java ignores assertions. You can enable assertions by passing the option -ea to the JVM. You can enable and disable assertions for individual classes and packages. This means that you can validate code with the assertions while developing and testing, and disable them in a production environment, although my testing has shown next to no performance impact from assertions.

Not using assertions in this case is OK because the code will just fail, which is what will happen if you use assertions. The only difference is that with assertions it might happen sooner, in a more-meaningful way and possibly with extra information, which may help you to figure out why it happened if you weren't expecting it.

(1) is a little harder. If you have no control over the code you're calling then you're stuck. If null is a valid response, you have to check for it.

If it's code that you do control, however (and this is often the case), then it's a different story. Avoid using nulls as a response. With methods that return collections, it's easy: return empty collections (or arrays) instead of nulls pretty much all the time.

With non-collections it might be harder. Consider this as an example: if you have these interfaces:

public interface Action {
  void doSomething();
}

public interface Parser {
  Action findAction(String userInput);
}

where Parser takes raw user input and finds something to do, perhaps if you're implementing a command line interface for something. Now you might make the contract that it returns null if there's no appropriate action. That leads the null checking you're talking about.

An alternative solution is to never return null and instead use the Null Object pattern:

public class MyParser implements Parser {
  private static Action DO_NOTHING = new Action() {
    public void doSomething() { /* do nothing */ }
  };

  public Action findAction(String userInput) {
    // ...
    if ( /* we can't find any actions */ ) {
      return DO_NOTHING;
    }
  }
}

Compare:

Parser parser = ParserFactory.getParser();
if (parser == null) {
  // now what?
  // this would be an example of where null isn't (or shouldn't be) a valid response
}
Action action = parser.findAction(someInput);
if (action == null) {
  // do nothing
} else {
  action.doSomething();
}

to

ParserFactory.getParser().findAction(someInput).doSomething();

which is a much better design because it leads to more concise code.

That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with a meaningful error message -- especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation.

try {
    ParserFactory.getParser().findAction(someInput).doSomething();
} catch(ActionNotFoundException anfe) {
    userConsole.err(anfe.getMessage());
}

Or if you think the try/catch mechanism is too ugly, rather than Do Nothing your default action should provide feedback to the user.

public Action findAction(final String userInput) {
    /* Code to return requested Action if found */
    return new Action() {
        public void doSomething() {
            userConsole.err("Action not found: " + userInput);
        }
    }
}

Chmod recursively

Give 0777 to all files and directories starting from the current path :

chmod -R 0777 ./

WordPress query single post by slug

How about?

<?php
   $queried_post = get_page_by_path('my_slug',OBJECT,'post');
?>

Explain the different tiers of 2 tier & 3 tier architecture?

Wikipedia explains it better then I could

From the article - Top is 1st Tier: alt text

How to position one element relative to another with jQuery?

You can use the jQuery plugin PositionCalculator

That plugin has also included collision handling (flip), so the toolbar-like menu can be placed at a visible position.

$(".placeholder").on('mouseover', function() {
    var $menu = $("#menu").show();// result for hidden element would be incorrect
    var pos = $.PositionCalculator( {
        target: this,
        targetAt: "top right",
        item: $menu,
        itemAt: "top left",
        flip: "both"
    }).calculate();

    $menu.css({
        top: parseInt($menu.css('top')) + pos.moveBy.y + "px",
        left: parseInt($menu.css('left')) + pos.moveBy.x + "px"
    });
});

for that markup:

<ul class="popup" id="menu">
    <li>Menu item</li>
    <li>Menu item</li>
    <li>Menu item</li>
</ul>

<div class="placeholder">placeholder 1</div>
<div class="placeholder">placeholder 2</div>

Here is the fiddle: http://jsfiddle.net/QrrpB/1657/

Remove all html tags from php string

For my this is best solution.

function strip_tags_content($string) { 
    // ----- remove HTML TAGs ----- 
    $string = preg_replace ('/<[^>]*>/', ' ', $string); 
    // ----- remove control characters ----- 
    $string = str_replace("\r", '', $string);
    $string = str_replace("\n", ' ', $string);
    $string = str_replace("\t", ' ', $string);
    // ----- remove multiple spaces ----- 
    $string = trim(preg_replace('/ {2,}/', ' ', $string));
    return $string; 

}

Large WCF web service request failing with (400) HTTP Bad Request

I found the answer to the Bad Request 400 problem.

It was the default server binding setting. You would need to add to server and client default setting.

binding name="" openTimeout="00:10:00" closeTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxReceivedMessageSize="2147483647" maxBufferPoolSize="2147483647" maxBufferSize="2147483647">

Select dropdown with fixed width cutting off content in IE

Simply you can use this plugin for jquery ;)

http://plugins.jquery.com/project/skinner

$(function(){
          $('.select1').skinner({'width':'200px'});
});

How to search for a file in the CentOS command line

CentOS is Linux, so as in just about all other Unix/Linux systems, you have the find command. To search for files within the current directory:

find -name "filename"

You can also have wildcards inside the quotes, and not just a strict filename. You can also explicitly specify a directory to start searching from as the first argument to find:

find / -name "filename"

will look for "filename" or all the files that match the regex expression in between the quotes, starting from the root directory. You can also use single quotes instead of double quotes, but in most cases you don't need either one, so the above commands will work without any quotes as well. Also, for example, if you're searching for java files and you know they are somewhere in your /home/username, do:

find /home/username -name *.java

There are many more options to the find command and you should do a:

man find

to learn more about it.

One more thing: if you start searching from / and are not root or are not sudo running the command, you might get warnings that you don't have permission to read certain directories. To ignore/remove those, do:

find / -name 'filename' 2>/dev/null

That just redirects the stderr to /dev/null.

How to automatically redirect HTTP to HTTPS on Apache servers?

Using mod_rewrite is not the recommended way instead use virtual host and redirect.

In case, if you are inclined to do using mod_rewrite:

RewriteEngine On
# This will enable the Rewrite capabilities

RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS

RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
# This rule will redirect users from their original location, to the same 
location but using HTTPS.
# i.e.  http://www.example.com/foo/ to https://www.example.com/foo/
# The leading slash is made optional so that this will work either in
# httpd.conf or .htaccess context

Reference: Httpd Wiki - RewriteHTTPToHTTPS

If you are looking for a 301 Permanent Redirect, then redirect flag should be as,

 R=301

so the RewriteRule will be like,

RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]

White space showing up on right side of page when background image should extend full length of page

After exploring some of the helpful strategies provided here, I found that I only needed to add iOS specific CSS (I put it at the bottom of my main css sheet.) Seems like hiding the overflow-x was the answer for me. I assume that stating the width at 100% helps in the event that my content goes wide. It should be noted that I was only having this issue in iOS. If it is also in Firefox, just the html and body block should probably be used as the @media is specifically targeting mobile devices.

@media
only screen and (-webkit-min-device-pixel-ratio: 1.5),
only screen and (-o-min-device-pixel-ratio: 3/2),
only screen and (min--moz-device-pixel-ratio: 1.5),
only screen and (min-device-pixel-ratio: 1.5){

  html,
  body{
    width:100%;
    overflow-x:hidden;
  }

}

Please hip me if this seems incorrect to anyone :)

A connection was successfully established with the server, but then an error occurred during the pre-login handshake

Solution

1) Clean your VS.Net Solution

2) Rebuild Project.

3) Reset IIS

4) Run the project again.

Basically that solved my problem, but in my case i was not getting this error and suddenly my local environment starts giving me above error, so may be that trick work for me.

slashes in url variables

You could easily replace the forward slashes / with something like an underscore _ such as Wikipedia uses for spaces. Replacing special characters with underscores, etc., is common practice.

When to throw an exception?

I agree with japollock way up there--throw an acception when you are uncertain about the outcome of an operation. Calls to APIs, accessing filesystems, database calls, etc. Anytime you are moving past the "boundaries" of your programming languages.

I'd like to add, feel free to throw a standard exception. Unless you are going to do something "different" (ignore, email, log, show that twitter whale picture thingy, etc), then don't bother with custom exceptions.

Can vue-router open a link in a new tab?

Just write this code in your routing file :

{
  name: 'Google',
  path: '/google',
  beforeEnter() {                    
                window.open("http://www.google.com", 
                '_blank');
            }
}

How can I get the MAC and the IP address of a connected client in PHP?

We can get MAC address in Ubuntu by this ways in php

$ipconfig =   shell_exec ("ifconfig -a | grep -Po 'HWaddr \K.*$'");  
    // display mac address   
 echo $ipconfig;

Apply pandas function to column to create multiple new columns?

This is the correct and easiest way to accomplish this for 95% of use cases:

>>> df = pd.DataFrame(zip(*[range(10)]), columns=['num'])
>>> df
    num
0    0
1    1
2    2
3    3
4    4
5    5

>>> def example(x):
...     x['p1'] = x['num']**2
...     x['p2'] = x['num']**3
...     x['p3'] = x['num']**4
...     return x

>>> df = df.apply(example, axis=1)
>>> df
    num  p1  p2  p3
0    0   0   0    0
1    1   1   1    1
2    2   4   8   16
3    3   9  27   81
4    4  16  64  256

EC2 instance has no public DNS

There is a actually a setting in the VPC called "DNS Hostnames". You can modify the VPC in which the EC2 instance exists, and change this to "Yes". That should do the trick.

I ran into this issue yesterday and tried the above answer from Manny, which did not work. The VPC setting, however, did work for me.

Ultimately I added an EIP and I use that to connect.

Generating random numbers with normal distribution in Excel

Rand() does generate a uniform distribution of random numbers between 0 and 1, but the norminv (or norm.inv) function is taking the uniform distributed Rand() as an input to generate the normally distributed sample set.

Getting Keyboard Input

You can use Scanner class like this:

  import java.util.Scanner;

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

    Scanner scan= new Scanner(System.in);

    //For string

    String text= scan.nextLine();

    System.out.println(text);

    //for int

    int num= scan.nextInt();

    System.out.println(num);
    }
}

Select parent element of known element in Selenium

This might be useful for someone else: Using this sample html

<div class="ParentDiv">
    <label for="label">labelName</label>
    <input type="button" value="elementToSelect">
</div>
<div class="DontSelect">
    <label for="animal">pig</label>
    <input type="button" value="elementToSelect">
</div>

If for example, I want to select an element in the same section (e.g div) as a label, you can use this

//label[contains(., 'labelName')]/parent::*//input[@value='elementToSelect'] 

This just means, look for a label (it could anything like a, h2) called labelName. Navigate to the parent of that label (i.e. div class="ParentDiv"). Search within the descendants of that parent to find any child element with the value of elementToSelect. With this, it will not select the second elementToSelect with DontSelect div as parent.

The trick is that you can reduce search areas for an element by navigating to the parent first and then searching descendant of that parent for the element you need. Other Syntax like following-sibling::h2 can also be used in some cases. This means the sibling following element h2. This will work for elements at the same level, having the same parent.

Spark: subtract two DataFrames

According to the api docs, doing:

dataFrame1.except(dataFrame2)

will return a new DataFrame containing rows in dataFrame1 but not in dataframe2.

How to show uncommitted changes in Git and some Git diffs in detail

You have already staged the changes (presumably by running git add), so in order to get their diff, you need to run:

git diff --cached

(A plain git diff will only show unstaged changes.)

For example: Example git diff cached use

Using Python's list index() method on a list of tuples or objects?

You can do this with a list comprehension and index()

tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
[x[0] for x in tuple_list].index("kumquat")
2
[x[1] for x in tuple_list].index(7)
1

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

This issue is not happening in Firefox and Safari. Make sure you are using the latest version of xml2json.js. Because i faced the XML parser error in IE. In Chrome best way you should open it in server like Apache or XAMPP.

How to fire a button click event from JavaScript in ASP.NET

I lived this problem in two days and suddenly I realized it that I am using this click method(for asp button) in a submit button(in html submit button) javascript method...

I mean ->

I have an html submit button and an asp button like these:

_x000D_
_x000D_
<input type="submit" value="Siparisi Gönder" onclick="SendEmail()" />_x000D_
<asp:Button ID="sendEmailButton" runat="server" Text="Gönder" OnClick="SendToEmail" Visible="True"></asp:Button>
_x000D_
_x000D_
_x000D_

SendToEmail() is a server side method in Default.aspx SendEmail() is a javascript method like this:

_x000D_
_x000D_
<script type="text/javascript" lang="javascript">_x000D_
   function SendEmail() {_x000D_
            document.getElementById('<%= sendEmailButton.UniqueID %>').click();_x000D_
            alert("Your message is sending...");_x000D_
        }_x000D_
</script>
_x000D_
_x000D_
_x000D_

And this "document.getElementById('<%= sendEmailButton.UniqueID %>').click();" method did not work in just Crome. It was working in IE and Firefox.

Then I tried and tried a lot of ways for executing "SendToEmail()" method in Crome.

Then suddenly I changed html submit button --> just html button like this and now it is working:

_x000D_
_x000D_
<input type="button" value="Siparisi Gönder" onclick="SendEmail()" />
_x000D_
_x000D_
_x000D_

Have a nice days...

How to connect Robomongo to MongoDB

Here's what we do:

  • Create a new connection, set the name, IP address and the appropriate port:

    Connection setup

  • Set up authentication, if required

    Authentication settings

  • Optionally set up other available settings for SSL, SSH, etc.

  • Save and connect

Could not resolve this reference. Could not locate the assembly

I had faced similar linker issues while adding a NuGet package into the iOS project (in Xamarin forms project). We had earlier provided the additional mtouch argument in the build configurations like this -dlsym:false -cxx -v -v -v -v -gcc_flags

After removing -dlsym:false from the configuration, the issues got resolved for me.

Loading DLLs at runtime in C#

Activator.CreateInstance() returns an object, which doesn't have an Output method.

It looks like you come from dynamic programming languages? C# is definetly not that, and what you are trying to do will be difficult.

Since you are loading a specific dll from a specific location, maybe you just want to add it as a reference to your console application?

If you absolutely want to load the assembly via Assembly.Load, you will have to go via reflection to call any members on c

Something like type.GetMethod("Output").Invoke(c, null); should do it.

Using group by on two fields and count in SQL

SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup

pip is not able to install packages correctly: Permission denied error

It looks like you're having a permissions error, based on this message in your output: error: could not create '/lib/python2.7/site-packages/lxml': Permission denied.

One thing you can try is doing a user install of the package with pip install lxml --user. For more information on how that works, check out this StackOverflow answer. (Thanks to Ishaan Taylor for the suggestion)

You can also run pip install as a superuser with sudo pip install lxml but it is not generally a good idea because it can cause issues with your system-level packages.

How do you replace double quotes with a blank space in Java?

You can do it like this:

string tmp = "Hello 'World'";
tmp.replace("'", "");

But that will just replace single quotes. To replace double quotes, you must first escape them, like so:

string tmp = "Hello, \"World\"";
tmp.replace("\"", "");

You can replace it with a space, or just leave it empty (I believe you wanted it to be left blank, but your question title implies otherwise.

Display all post meta keys and meta values of the same post ID in wordpress

WordPress have the function get_metadata this get all meta of object (Post, term, user...)

Just use

get_metadata( 'post', 15 );

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

You have entered wrong port number 3360 instead of 3306. You dont need to write database port number if you are using daefault (3306 in case of MySQL)

How do I check which version of NumPy I'm using?

From the command line, you can simply issue:

python -c "import numpy; print(numpy.version.version)"

Or:

python -c "import numpy; print(numpy.__version__)"

Why is division in Ruby returning an integer instead of decimal value?

Change the 5 to 5.0. You're getting integer division.

How to clear cache in Yarn?

Also note that the cached directory is located in ~/.yarn-cache/:

yarn cache clean: cleans that directory

yarn cache list: shows the list of cached dependencies

yarn cache dir: prints out the path of your cached directory

Huge performance difference when using group by vs distinct

The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct approach is executed like:

  • Copy all business_key values to a temporary table
  • Sort the temporary table
  • Scan the temporary table, returning each item that is different from the one before it

The group by could be executed like:

  • Scan the full table, storing each value of business key in a hashtable
  • Return the keys of the hashtable

The first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.

Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.

How to add option to select list in jQuery

$('#dropListBuilding').append('<option>'+val+'</option>');

Parallel.ForEach vs Task.Factory.StartNew

Parallel.ForEach will optimize(may not even start new threads) and block until the loop is finished, and Task.Factory will explicitly create a new task instance for each item, and return before they are finished (asynchronous tasks). Parallel.Foreach is much more efficient.

How to clear a chart from a canvas so that hover events cannot be triggered?

You should save the chart as a variable. On global scope, if its pure javascript, or as a class property, if its Angular.

Then you'll be able to use this reference to call destroy().

Pure Javascript:

var chart;

function startChart() {
    // Code for chart initialization
    chart = new Chart(...); // Replace ... with your chart parameters
}

function destroyChart() {
    chart.destroy();
}

Angular:

export class MyComponent {
    chart;

    constructor() {
        // Your constructor code goes here
    }

    ngOnInit() {
        // Probably you'll start your chart here

        // Code for chart initialization
        this.chart = new Chart(...); // Replace ... with your chart parameters
    }

    destroyChart() {
        this.chart.destroy();
    }
}

$apply already in progress error

Just use $evalAsync instead of $apply.

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

The latest set of guidance is as follows: (from https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#environment-variables)

Use:

System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);

From the docs:

public static class EnvironmentVariablesExample
{
    [FunctionName("GetEnvironmentVariables")]
    public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
    {
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
        log.LogInformation(GetEnvironmentVariable("AzureWebJobsStorage"));
        log.LogInformation(GetEnvironmentVariable("WEBSITE_SITE_NAME"));
    }

    public static string GetEnvironmentVariable(string name)
    {
        return name + ": " +
            System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
    }
}

App settings can be read from environment variables both when developing locally and when running in Azure. When developing locally, app settings come from the Values collection in the local.settings.json file. In both environments, local and Azure, GetEnvironmentVariable("<app setting name>") retrieves the value of the named app setting. For instance, when you're running locally, "My Site Name" would be returned if your local.settings.json file contains { "Values": { "WEBSITE_SITE_NAME": "My Site Name" } }.

The System.Configuration.ConfigurationManager.AppSettings property is an alternative API for getting app setting values, but we recommend that you use GetEnvironmentVariable as shown here.

Get current URL with jQuery?

Use window.location.href. This will give you the complete URL.

User Control - Custom Properties

It is very simple, just add a property:

public string Value {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

Using the Text property is a bit trickier, the UserControl class intentionally hides it. You'll need to override the attributes to put it back in working order:

[Browsable(true), EditorBrowsable(EditorBrowsableState.Always), Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

Error: " 'dict' object has no attribute 'iteritems' "

In Python2, dictionary.iteritems() is more efficient than dictionary.items() so in Python3, the functionality of dictionary.iteritems() has been migrated to dictionary.items() and iteritems() is removed. So you are getting this error.

Use dict.items() in Python3 which is same as dict.iteritems() of Python2.

How to get the first element of an array?

When there are multiple matches, JQuery's .first() is used for fetching the first DOM element that matched the css selector given to jquery.

You don't need jQuery to manipulate javascript arrays.

Laravel blank white screen

When I was new to Linux.I usually found this error with my Laravel Project. White errors means error, It may have some permission issue or error.

You just have to follow two steps, and will work like champ :)

(1) Give the permission. Run these command from root directory of your project

(a) sudo chmod 777 -R storage
(b) sudo chmod bootstrap/cache

(2) If you cloned the project or pulled from github then run

composer install

(3) Configure your .env file properly, and your project will work.

error: expected unqualified-id before ‘.’ token //(struct)

The struct's name is ReducedForm; you need to make an object (instance of the struct or class) and use that. Do this:

ReducedForm MyReducedForm;
MyReducedForm.iSimplifiedNumerator = iNumerator/iGreatCommDivisor;
MyReducedForm.iSimplifiedDenominator = iDenominator/iGreatCommDivisor;

How to export library to Jar in Android Studio?

I was able to build a library source code to compiled .jar file, using approach from this solution: https://stackoverflow.com/a/19037807/1002054

Here is the breakdown of what I did:

1. Checkout library repository

In may case it was a Volley library

2. Import library in Android Studio.

I used Android Studio 0.3.7. I've encountered some issues during that step, namely I had to copy gradle folder from new android project before I was able to import Volley library source code, this may vary depending on source code you use.

3. Modify your build.gradle file

// If your module is a library project, this is needed
//to properly recognize 'android-library' plugin
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.6.3'
    }
}

apply plugin: 'android-library'

android {
    compileSdkVersion 17
    buildToolsVersion = 17

    sourceSets {
        main  {
            // Here is the path to your source code
            java {
                srcDir 'src'
            }
        }
    }
}

// This is the actual solution, as in https://stackoverflow.com/a/19037807/1002054
task clearJar(type: Delete) {
    delete 'build/libs/myCompiledLibrary.jar'
}

task makeJar(type: Copy) {
    from('build/bundles/release/')
    into('build/libs/')
    include('classes.jar')
    rename ('classes.jar', 'myCompiledLibrary.jar')
}

makeJar.dependsOn(clearJar, build)

4. Run gradlew makeJar command from your project root.

I my case I had to copy gradlew.bat and gradle files from new android project into my library project root. You should find your compiled library file myCompiledLibrary.jar in build\libs directory.

I hope someone finds this useful.

Edit:

Caveat

Althought this works, you will encounter duplicate library exception while compiling a project with multiple modules, where more than one module (including application module) depends on the same jar file (eg. modules have own library directory, that is referenced in build.gradle of given module).

In case where you need to use single library in more then one module, I would recommend using this approach: Android gradle build and the support library

Creating an empty Pandas DataFrame, then filling it?

Initialize empty frame with column names

import pandas as pd

col_names =  ['A', 'B', 'C']
my_df  = pd.DataFrame(columns = col_names)
my_df

Add a new record to a frame

my_df.loc[len(my_df)] = [2, 4, 5]

You also might want to pass a dictionary:

my_dic = {'A':2, 'B':4, 'C':5}
my_df.loc[len(my_df)] = my_dic 

Append another frame to your existing frame

col_names =  ['A', 'B', 'C']
my_df2  = pd.DataFrame(columns = col_names)
my_df = my_df.append(my_df2)

Performance considerations

If you are adding rows inside a loop consider performance issues. For around the first 1000 records "my_df.loc" performance is better, but it gradually becomes slower by increasing the number of records in the loop.

If you plan to do thins inside a big loop (say 10M? records or so), you are better off using a mixture of these two; fill a dataframe with iloc until the size gets around 1000, then append it to the original dataframe, and empty the temp dataframe. This would boost your performance by around 10 times.

How to dismiss notification after action has been clicked

You can always cancel() the Notification from whatever is being invoked by the action (e.g., in onCreate() of the activity tied to the PendingIntent you supply to addAction()).

How to delete a line from a text file in C#?

I'd very simply:

  • Open the file for read/write
  • Read/seek through it until the start of the line you want to delete
  • Set the write pointer to the current read pointer
  • Read through to the end of the line we're deleting and skip the newline delimiters (counting the number of characters as we go, we'll call it nline)
  • Read byte-by-byte and write each byte to the file
  • When finished truncate the file to (orig_length - nline).

how to convert object to string in java

Might not be so related to the issue above. However if you are looking for a way to serialize Java object as string, this could come in hand

package pt.iol.security;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.Base64;

public class ObjectUtil {

    static final Base64 base64 = new Base64();

    public static String serializeObjectToString(Object object) throws IOException {
        try (
                ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
                GZIPOutputStream gzipOutputStream = new GZIPOutputStream(arrayOutputStream);
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(gzipOutputStream);) {
            objectOutputStream.writeObject(object);
            objectOutputStream.flush();
            return new String(base64.encode(arrayOutputStream.toByteArray()));
        }
    }

    public static Object deserializeObjectFromString(String objectString) throws IOException, ClassNotFoundException {
        try (
                ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(base64.decode(objectString));
                GZIPInputStream gzipInputStream = new GZIPInputStream(arrayInputStream);
                ObjectInputStream objectInputStream = new ObjectInputStream(gzipInputStream)) {
            return objectInputStream.readObject();
        }
    }
}

How to replace all strings to numbers contained in each string in Notepad++?

psxls gave a great answer but I think my Notepad++ version is slightly different so the $ (dollar sign) capturing did not work.

I have Notepad++ v.5.9.3 and here's how you can accomplish your task:

Search for the pattern: value=\"([0-9]*)\" And replace with: \1 (whatever you want to do around that capturing group)

Ex. Surround with square brackets

[\1] --> will produce value="[4]"

Getting error "No such module" using Xcode, but the framework is there

I installed the pod Fakery, the pod got added under my Pods file, however when I tried to use it I got the same error. Problem was, I didn't build it, after building it , the swift compiler threw a few errors in the Fakery swift files that some functions have been renamed, it also provided fixes for them too. After resolving all those compiler issues , build succeeded and I was able to use the module. So swift language compatibility was the problem in my case.

error LNK2005, already defined?

The linker tells you that you have the variable k defined multiple times. Indeed, you have a definition in A.cpp and another in B.cpp. Both compilation units produce a corresponding object file that the linker uses to create your program. The problem is that in your case the linker does not know whic definition of k to use. In C++ you can have only one defintion of the same construct (variable, type, function).

To fix it, you will have to decide what your goal is

  • If you want to have two variables, both named k, you can use an anonymous namespace in both .cpp files, then refer to k as you are doing now:

.

namespace {
  int k;
}
  • You can rename one of the ks to something else, thus avoiding the duplicate defintion.
  • If you want to have only once definition of k and use that in both .cpp files, you need to declare in one as extern int k;, and leave it as it is in the other. This will tell the linker to use the one definition (the unchanged version) in both cases -- extern implies that the variable is defined in another compilation unit.

How to rsync only a specific list of files?

--files-from= parameter needs trailing slash if you want to keep the absolute path intact. So your command would become something like below:

rsync -av --files-from=/path/to/file / /tmp/

This could be done like there are a large number of files and you want to copy all files to x path. So you would find the files and throw output to a file like below:

find /var/* -name *.log > file

Resizing Images in VB.NET

Here is an article with full details on how to do this.

Private Sub btnScale_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnScale.Click
    ' Get the scale factor.
    Dim scale_factor As Single = Single.Parse(txtScale.Text)

    ' Get the source bitmap.
    Dim bm_source As New Bitmap(picSource.Image)

    ' Make a bitmap for the result.
    Dim bm_dest As New Bitmap( _
        CInt(bm_source.Width * scale_factor), _
        CInt(bm_source.Height * scale_factor))

    ' Make a Graphics object for the result Bitmap.
    Dim gr_dest As Graphics = Graphics.FromImage(bm_dest)

    ' Copy the source image into the destination bitmap.
    gr_dest.DrawImage(bm_source, 0, 0, _
        bm_dest.Width + 1, _
        bm_dest.Height + 1)

    ' Display the result.
    picDest.Image = bm_dest
End Sub

[Edit]
One more on the similar lines.

Does Python have a package/module management system?

The Python Package Index (PyPI) seems to be standard:

  • To install a package: pip install MyProject
  • To update a package pip install --upgrade MyProject
  • To fix a version of a package pip install MyProject==1.0

You can install the package manager as follows:

curl -O http://python-distribute.org/distribute_setup.py
python distribute_setup.py
easy_install pip

References:

Maximum Java heap size of a 32-bit JVM on a 64-bit OS

The limitations of a 32-bit JVM on a 64-bit OS will be exactly the same as the limitations of a 32-bit JVM on a 32-bit OS. After all, the 32-bit JVM will be running In a 32-bit virtual machine (in the virtualization sense) so it won't know that it's running on a 64-bit OS/machine.

The one advantage to running a 32-bit JVM on a 64-bit OS versus a 32-bit OS is that you can have more physical memory, and therefore will encounter swapping/paging less frequently. This advantage is only really fully realized when you have multiple processes, however.

Entity Framework - Include Multiple Levels of Properties

I also had to use multiple includes and at 3rd level I needed multiple properties

(from e in context.JobCategorySet
                      where e.Id == id &&
                            e.AgencyId == agencyId
                      select e)
                      .Include(x => x.JobCategorySkillDetails)
                      .Include(x => x.Shifts.Select(r => r.Rate).Select(rt => rt.DurationType))
                      .Include(x => x.Shifts.Select(r => r.Rate).Select(rt => rt.RuleType))
                      .Include(x => x.Shifts.Select(r => r.Rate).Select(rt => rt.RateType))
                      .FirstOrDefaultAsync();

This may help someone :)

jQuery remove special characters from string and more

str.toLowerCase().replace(/[\*\^\'\!]/g, '').split(' ').join('-')

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

In my case I used the binaries from Shining Light and the environment variables were already updated. But still had the issue until I ran a command window with elevated privileges.

When you open the CMD window be sure to run it as Administrator. (Right click the Command Prompt in Start menu and choose "Run as administrator")

I think it can't read the files due to User Account Control.

What is the use of printStackTrace() method in Java?

I was kind of curious about this too, so I just put together a little sample code where you can see what it is doing:

try {
    throw new NullPointerException();
}
catch (NullPointerException e) {
    System.out.println(e);
}

try {
    throw new IOException();
}
catch (IOException e) {
    e.printStackTrace();
}
System.exit(0);

Calling println(e):

java.lang.NullPointerException

Calling e.printStackTrace():

java.io.IOException
      at package.Test.main(Test.java:74)