Programs & Examples On #Isoneway

React - uncaught TypeError: Cannot read property 'setState' of undefined

you have to bind new event with this keyword as i mention below...

class Counter extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            count : 1
        };

        this.delta = this.delta.bind(this);
    }

    delta() {
        this.setState({
            count : this.state.count++
        });
    }

    render() {
        return (
            <div>
                <h1>{this.state.count}</h1>
                <button onClick={this.delta}>+</button>
            </div>
        );
      }
    }

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

Remove your Gemfile.lock.

Move to bash if you are using zsh.

sudo bash
gem update --system 

Now run command bundle to create a new Gemfile.lock file. Move back to your zsh sudo exec zsh now run your rake commands.

How to pass objects to functions in C++?

There are some differences in calling conventions in C++ and Java. In C++ there are technically speaking only two conventions: pass-by-value and pass-by-reference, with some literature including a third pass-by-pointer convention (that is actually pass-by-value of a pointer type). On top of that, you can add const-ness to the type of the argument, enhancing the semantics.

Pass by reference

Passing by reference means that the function will conceptually receive your object instance and not a copy of it. The reference is conceptually an alias to the object that was used in the calling context, and cannot be null. All operations performed inside the function apply to the object outside the function. This convention is not available in Java or C.

Pass by value (and pass-by-pointer)

The compiler will generate a copy of the object in the calling context and use that copy inside the function. All operations performed inside the function are done to the copy, not the external element. This is the convention for primitive types in Java.

An special version of it is passing a pointer (address-of the object) into a function. The function receives the pointer, and any and all operations applied to the pointer itself are applied to the copy (pointer), on the other hand, operations applied to the dereferenced pointer will apply to the object instance at that memory location, so the function can have side effects. The effect of using pass-by-value of a pointer to the object will allow the internal function to modify external values, as with pass-by-reference and will also allow for optional values (pass a null pointer).

This is the convention used in C when a function needs to modify an external variable, and the convention used in Java with reference types: the reference is copied, but the referred object is the same: changes to the reference/pointer are not visible outside the function, but changes to the pointed memory are.

Adding const to the equation

In C++ you can assign constant-ness to objects when defining variables, pointers and references at different levels. You can declare a variable to be constant, you can declare a reference to a constant instance, and you can define all pointers to constant objects, constant pointers to mutable objects and constant pointers to constant elements. Conversely in Java you can only define one level of constant-ness (final keyword): that of the variable (instance for primitive types, reference for reference types), but you cannot define a reference to an immutable element (unless the class itself is immutable).

This is extensively used in C++ calling conventions. When the objects are small you can pass the object by value. The compiler will generate a copy, but that copy is not an expensive operation. For any other type, if the function will not change the object, you can pass a reference to a constant instance (usually called constant reference) of the type. This will not copy the object, but pass it into the function. But at the same time the compiler will guarantee that the object is not changed inside the function.

Rules of thumb

This are some basic rules to follow:

  • Prefer pass-by-value for primitive types
  • Prefer pass-by-reference with references to constant for other types
  • If the function needs to modify the argument use pass-by-reference
  • If the argument is optional, use pass-by-pointer (to constant if the optional value should not be modified)

There are other small deviations from these rules, the first of which is handling ownership of an object. When an object is dynamically allocated with new, it must be deallocated with delete (or the [] versions thereof). The object or function that is responsible for the destruction of the object is considered the owner of the resource. When a dynamically allocated object is created in a piece of code, but the ownership is transfered to a different element it is usually done with pass-by-pointer semantics, or if possible with smart pointers.

Side note

It is important to insist in the importance of the difference between C++ and Java references. In C++ references are conceptually the instance of the object, not an accessor to it. The simplest example is implementing a swap function:

// C++
class Type; // defined somewhere before, with the appropriate operations
void swap( Type & a, Type & b ) {
   Type tmp = a;
   a = b;
   b = tmp;
}
int main() {
   Type a, b;
   Type old_a = a, old_b = b;
   swap( a, b );
   assert( a == old_b );
   assert( b == old_a ); 
}

The swap function above changes both its arguments through the use of references. The closest code in Java:

public class C {
   // ...
   public static void swap( C a, C b ) {
      C tmp = a;
      a = b;
      b = tmp;
   }
   public static void main( String args[] ) {
      C a = new C();
      C b = new C();
      C old_a = a;
      C old_b = b;
      swap( a, b ); 
      // a and b remain unchanged a==old_a, and b==old_b
   }
}

The Java version of the code will modify the copies of the references internally, but will not modify the actual objects externally. Java references are C pointers without pointer arithmetic that get passed by value into functions.

HttpServletRequest to complete URL

// http://hostname.com/mywebapp/servlet/MyServlet/a/b;c=123?d=789

public static String getUrl(HttpServletRequest req) {
    String reqUrl = req.getRequestURL().toString();
    String queryString = req.getQueryString();   // d=789
    if (queryString != null) {
        reqUrl += "?"+queryString;
    }
    return reqUrl;
}

How do you find out the caller function in JavaScript?

It's safer to use *arguments.callee.caller since arguments.caller is deprecated...

Python: Remove division decimal

You could probably do like below

# p and q are the numbers to be divided
if p//q==p/q:
    print(p//q)
else:
    print(p/q)

Change value of input and submit form in JavaScript

No. When your input type is submit, you should have an onsubmit event declared in the markup and then do the changes you want. Meaning, have an onsubmit defined in your form tag.

Otherwise change the input type to a button and then define an onclick event for that button.

How do I decrease the size of my sql server log file?

This is one of the best suggestion in which is done using query. Good for those who has a lot of databases just like me. Can run it using a script.

https://medium.com/@bharatdwarkani/shrinking-sql-server-db-log-file-size-sql-server-db-maintenance-7ddb0c331668

USE DatabaseName;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE DatabaseName
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (DatabaseName_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE DatabaseName
SET RECOVERY FULL;
GO

What does "O(1) access time" mean?

Basically, O(1) means its computation time is constant, while O(n) means it will depend lineally on the size of input - i.e. looping through an array has O(n) - just looping -, because it depends on the number of items, while calculating the maximum between to ordinary numbers has O(1).

Wikipedia might help as well: http://en.wikipedia.org/wiki/Computational_complexity_theory

scrollIntoView Scrolls just too far

I add this css tips for those who not resolved this issue with solutions above :

#myDiv::before {
  display: block;
  content: " ";
  margin-top: -90px; // adjust this with your header height
  height: 90px; // adjust this with your header height
  visibility: hidden;
}

Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

Most answers already cover getContext() and getApplicationContext() but getBaseContext() is rarely explained.

The method getBaseContext() is only relevant when you have a ContextWrapper. Android provides a ContextWrapper class that is created around an existing Context using:

ContextWrapper wrapper = new ContextWrapper(context);

The benefit of using a ContextWrapper is that it lets you “modify behavior without changing the original Context”. For example, if you have an activity called myActivity then can create a View with a different theme than myActivity:

ContextWrapper customTheme = new ContextWrapper(myActivity) {
  @Override
  public Resources.Theme getTheme() { 
    return someTheme;
  }
}
View myView = new MyView(customTheme);

ContextWrapper is really powerful because it lets you override most functions provided by Context including code to access resources (e.g. openFileInput(), getString()), interact with other components (e.g. sendBroadcast(), registerReceiver()), requests permissions (e.g. checkCallingOrSelfPermission()) and resolving file system locations (e.g. getFilesDir()). ContextWrapper is really useful to work around device/version specific problems or to apply one-off customizations to components such as Views that require a context.

The method getBaseContext() can be used to access the “base” Context that the ContextWrapper wraps around. You might need to access the “base” context if you need to, for example, check whether it’s a Service, Activity or Application:

public class CustomToast {
  public void makeText(Context context, int resId, int duration) {
    while (context instanceof ContextWrapper) {
      context = context.baseContext();
    }
    if (context instanceof Service)) {
      throw new RuntimeException("Cannot call this from a service");
    }
    ...
  }
}

Or if you need to call the “unwrapped” version of a method:

class MyCustomWrapper extends ContextWrapper {
  @Override
  public Drawable getWallpaper() {
    if (BuildInfo.DEBUG) {
      return mDebugBackground;
    } else {
      return getBaseContext().getWallpaper();
    }
  }
}

How to free memory in Java?

In my case, since my Java code is meant to be ported to other languages in the near future (Mainly C++), I at least want to pay lip service to freeing memory properly so it helps the porting process later on.

I personally rely on nulling variables as a placeholder for future proper deletion. For example, I take the time to nullify all elements of an array before actually deleting (making null) the array itself.

But my case is very particular, and I know I'm taking performance hits when doing this.

BeautifulSoup getting href

You can use find_all in the following way to find every a element that has an href attribute, and print each one:

from BeautifulSoup import BeautifulSoup

html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

The output would be:

Found the URL: some_url
Found the URL: another_url

Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all instead.


If you want all tags with an href, you can omit the name parameter:

href_tags = soup.find_all(href=True)

How to Right-align flex item?

If you need one item to be left aligned (like a header) but then multiple items right aligned (like 3 images), then you would do something like this:

h1 {
   flex-basis: 100%; // forces this element to take up any remaining space
}

img {
   margin: 0 5px; // small margin between images
   height: 50px; // image width will be in relation to height, in case images are large - optional if images are already the proper size
}

Here's what that will look like (only relavent CSS was included in snippet above)

enter image description here

Mailto on submit button

This seems to work fine:

<button onclick="location.href='mailto:[email protected]';">send mail</button>

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

How do I concatenate multiple C++ strings on one line?

boost::format

or std::stringstream

std::stringstream msg;
msg << "Hello world, " << myInt  << niceToSeeYouString;
msg.str(); // returns std::string object

Efficiently finding the last line in a text file

#!/usr/bin/python

count = 0

f = open('last_line1','r')

for line in f.readlines():

    line = line.strip()

    count = count + 1

    print line

print count

f.close()

count1 = 0

h = open('last_line1','r')

for line in h.readlines():

    line = line.strip()

    count1 = count1 + 1

    if count1 == count:

       print line         #-------------------- this is the last line

h.close()

Exception 'open failed: EACCES (Permission denied)' on Android

Add gradle dependencies

implementation 'com.karumi:dexter:4.2.0'

Add below code in your main activity.

import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {


                checkMermission();
            }
        }, 4000);
    }

    private void checkMermission(){
        Dexter.withActivity(this)
                .withPermissions(
                        android.Manifest.permission.READ_EXTERNAL_STORAGE,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        android.Manifest.permission.ACCESS_NETWORK_STATE,
                        Manifest.permission.INTERNET
                ).withListener(new MultiplePermissionsListener() {
            @Override
            public void onPermissionsChecked(MultiplePermissionsReport report) {
                if (report.isAnyPermissionPermanentlyDenied()){
                    checkMermission();
                } else if (report.areAllPermissionsGranted()){
                    // copy some things
                } else {
                    checkMermission();
                }

            }
            @Override
            public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                token.continuePermissionRequest();
            }
        }).check();
    }

Chrome says my extension's manifest file is missing or unreadable

Mine also was funny. While copypasting " manifest.json" from the tutorial, i also managed to copy a leading space. Couldn't get why it's not finding it.

Table cell widths - fixing width, wrapping/truncating long words

As long as you fix the width of the table itself and set the table-layout property, this is pretty simple :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <style type="text/css">
        td { width: 30px; overflow: hidden; }
        table { width : 90px; table-layout: fixed; }
    </style>
</head>
<body>

    <table border="2">
        <tr>
            <td>word</td>
            <td>two words</td>
            <td>onereallylongword</td>

        </tr>
    </table>
</body>
</html>

I've tested this in IE6 and 7 and it seems to work fine.

Alternate table with new not null Column in existing table in SQL

IF NOT EXISTS (SELECT 1
FROM syscolumns sc
JOIN sysobjects so
ON sc.id = so.id
WHERE so.Name = 'Table1'
AND sc.Name = 'Col1')
BEGIN
ALTER TABLE Table1
ADD Col1 INT NOT NULL DEFAULT 0;
END
GO

Setting session variable using javascript

A session is stored server side, you can't modify it with JavaScript. Sessions may contain sensitive data.

You can modify cookies using document.cookie.

You can easily find many examples how to modify cookies.

List Git commits not pushed to the origin yet

how to determine if a commit with particular hash have been pushed to the origin already?

# list remote branches that contain $commit
git branch -r --contains $commit

How do I do multiple CASE WHEN conditions using SQL Server 2008?

Combining all conditions

select  a.* from tbl_Company a

where  a.Company_ID NOT IN (1,2)  

AND (   
        (0 = 
            CASE WHEN (@Fromdate = '' or @Todate='')
                THEN 0 
                ELSE 1  
            END
        )      -- if 0=0 true , if 0=1 fails (filter only when the fromdate and todate is present)
                OR
        (a.Created_Date between @Fromdate and @Todate )                 
    )

Linq to SQL how to do "where [column] in (list of values)"

 var filterTransNos = (from so in db.SalesOrderDetails
                    where  ItemDescription.Contains(ItemDescription)
                            select new { so.TransNo }).AsEnumerable();    


listreceipt = listreceipt.Where(p => filterTransNos.Any(p2 => p2.TransNo == p.TransNo)).ToList();

How to get character array from a string?

It already is:

_x000D_
_x000D_
var mystring = 'foobar';_x000D_
console.log(mystring[0]); // Outputs 'f'_x000D_
console.log(mystring[3]); // Outputs 'b'
_x000D_
_x000D_
_x000D_

Or for a more older browser friendly version, use:

_x000D_
_x000D_
var mystring = 'foobar';_x000D_
console.log(mystring.charAt(3)); // Outputs 'b'
_x000D_
_x000D_
_x000D_

Maximum length for MySQL type text

Acording to http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html, the limit is L + 2 bytes, where L < 2^16, or 64k.

You shouldn't need to concern yourself with limiting it, it's automatically broken down into chunks that get added as the string grows, so it won't always blindly use 64k.

how to align img inside the div to the right?

<style type="text/css">
>> .imgTop {
>>  display: block;
>>  text-align: right;
>>  }
>> </style>

<img class="imgTop" src="imgName.gif" alt="image description" height="100" width="100">

Load RSA public key from file

This program is doing almost everything with Public and private keys. The der format can be obtained but saving raw data ( without encoding base64). I hope this helps programmers.

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import sun.security.pkcs.PKCS8Key;
import sun.security.pkcs10.PKCS10;
import sun.security.x509.X500Name;

import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;



/**
 * @author Desphilboy
 * DorOd bar shomA barobach
 *
 */
public class csrgenerator {

    private static PublicKey publickey= null;
    private static PrivateKey privateKey=null;
    //private static PKCS8Key privateKey=null;
    private static KeyPairGenerator kpg= null;
    private static ByteArrayOutputStream bs =null;
    private static csrgenerator thisinstance;
    private KeyPair keypair;
    private static PKCS10 pkcs10;
    private String signaturealgorithm= "MD5WithRSA";

    public String getSignaturealgorithm() {
        return signaturealgorithm;
    }



    public void setSignaturealgorithm(String signaturealgorithm) {
        this.signaturealgorithm = signaturealgorithm;
    }



    private csrgenerator() {
        try {
           kpg = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            System.out.print("No such algorithm RSA in constructor csrgenerator\n");
        }
        kpg.initialize(2048);
        keypair = kpg.generateKeyPair();
        publickey = keypair.getPublic();
        privateKey = keypair.getPrivate();
    }



    /** Generates a new key pair 
    *
    * @param int bits 
    *   this is the number of bits in modulus must be 512, 1024, 2048  or so on 
    */
    public KeyPair generateRSAkys(int bits)
    {
          kpg.initialize(bits);
            keypair = kpg.generateKeyPair();
            publickey = keypair.getPublic();
            privateKey = keypair.getPrivate();
            KeyPair dup= keypair;
     return dup;
    }

     public static csrgenerator getInstance() {
            if (thisinstance == null)
                thisinstance = new csrgenerator();
            return thisinstance;
        }


     /**
      *  Returns a CSR as string  
      * @param cn  Common Name
      * @param OU  Organizational Unit 
      * @param Org  Organization
      * @param LocName Location name
      * @param Statename  State/Territory/Province/Region
      * @param Country    Country
      * @return     returns  csr as string.
      * @throws Exception
      */
     public String getCSR(String commonname, String organizationunit, String organization,String localname, String statename, String country ) throws Exception {
            byte[] csr = generatePKCS10(commonname, organizationunit, organization, localname, statename, country,signaturealgorithm);
            return new String(csr);
        }

     /** This function generates a new Certificate 
      * Signing Request. 
     *
     * @param CN
     *            Common Name, is X.509 speak for the name that distinguishes
     *            the Certificate best, and ties it to your Organization
     * @param OU
     *            Organizational unit
     * @param O
     *            Organization NAME
     * @param L
     *            Location
     * @param S
     *            State
     * @param C
     *            Country
     * @return    byte stream of generated request
     * @throws Exception
     */
    private static byte[] generatePKCS10(String CN, String OU, String O,String L, String S, String C,String sigAlg) throws Exception {
        // generate PKCS10 certificate request

        pkcs10 = new PKCS10(publickey);
       Signature   signature = Signature.getInstance(sigAlg);
        signature.initSign(privateKey);
        // common, orgUnit, org, locality, state, country
        //X500Name(String commonName, String organizationUnit,String organizationName,Local,State, String country)
        X500Name x500Name = new X500Name(CN, OU, O, L, S, C);
        pkcs10.encodeAndSign(x500Name,signature);
        bs = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bs);
        pkcs10.print(ps);
        byte[] c = bs.toByteArray();
        try {
            if (ps != null)
                ps.close();
            if (bs != null)
                bs.close();
        } catch (Throwable th) {
        }
        return c;
    }

    public  PublicKey getPublicKey() {
        return publickey;
    }




    /**
     * @return
     */
    public PrivateKey getPrivateKey() {
        return privateKey;
    }

    /**
     * saves private key to a file
     * @param filename
     */
    public  void SavePrivateKey(String filename)
    {
        PKCS8EncodedKeySpec pemcontents=null;
        pemcontents= new PKCS8EncodedKeySpec( privateKey.getEncoded());
        PKCS8Key pemprivatekey= new  PKCS8Key( );
        try {
            pemprivatekey.decode(pemcontents.getEncoded());
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        File file=new File(filename);
        try {

            file.createNewFile();
            FileOutputStream fos=new FileOutputStream(file);
            fos.write(pemprivatekey.getEncoded());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



    }



    /**
     * Saves Certificate Signing Request to a file;
     * @param filename  is a String containing full path to the file which will be created containing the CSR.
     */
    public void SaveCSR(String filename)
    {
        FileOutputStream fos=null;
        PrintStream ps=null;
        File file;
        try {

            file = new File(filename);
            file.createNewFile();
            fos = new FileOutputStream(file);
            ps= new PrintStream(fos);
        }catch (IOException e)
        {
            System.out.print("\n could not open the file "+ filename);
        }

        try {
            try {
                pkcs10.print(ps);
            } catch (SignatureException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            ps.flush();
            ps.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.print("\n cannot write to the file "+ filename);
            e.printStackTrace();

        }

        }


    /**
     * Saves both public key and private  key to file names specified
     * @param fnpub  file name of public key
     * @param fnpri  file name of private key
     * @throws IOException
     */
    public static void SaveKeyPair(String fnpub,String fnpri) throws IOException { 

// Store Public Key.
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
publickey.getEncoded());
FileOutputStream fos = new FileOutputStream(fnpub);
fos.write(x509EncodedKeySpec.getEncoded());
fos.close();

// Store Private Key.
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
fos = new FileOutputStream(fnpri);
fos.write(pkcs8EncodedKeySpec.getEncoded());
fos.close();
}


    /**
     * Reads a Private Key from a pem base64 encoded file.
     * @param filename name of the file to read.
     * @param algorithm Algorithm is usually "RSA"
     * @return returns the privatekey which is read from the file;
     * @throws Exception
     */
    public  PrivateKey getPemPrivateKey(String filename, String algorithm) throws Exception {
          File f = new File(filename);
          FileInputStream fis = new FileInputStream(f);
          DataInputStream dis = new DataInputStream(fis);
          byte[] keyBytes = new byte[(int) f.length()];
          dis.readFully(keyBytes);
          dis.close();

          String temp = new String(keyBytes);
          String privKeyPEM = temp.replace("-----BEGIN PRIVATE KEY-----", "");
          privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", "");
          //System.out.println("Private key\n"+privKeyPEM);

          BASE64Decoder b64=new BASE64Decoder();
          byte[] decoded = b64.decodeBuffer(privKeyPEM);

          PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
          KeyFactory kf = KeyFactory.getInstance(algorithm);
          return kf.generatePrivate(spec);
          }



    /**
     * Saves the private key to a pem file.
     * @param filename  name of the file to write the key into 
     * @param key the Private key to save.
     * @return  String representation of the pkcs8 object.
     * @throws Exception
     */
    public  String  SavePemPrivateKey(String filename) throws Exception {
        PrivateKey key=this.privateKey;
          File f = new File(filename);
          FileOutputStream fos = new FileOutputStream(f);
          DataOutputStream dos = new DataOutputStream(fos);


          byte[] keyBytes = key.getEncoded();
          PKCS8Key pkcs8= new PKCS8Key();
          pkcs8.decode(keyBytes);
          byte[] b=pkcs8.encode();

          BASE64Encoder b64=new BASE64Encoder();
          String  encoded = b64.encodeBuffer(b);

          encoded= "-----BEGIN PRIVATE KEY-----\r\n" + encoded + "-----END PRIVATE KEY-----";

         dos.writeBytes(encoded);
         dos.flush();
         dos.close();

          //System.out.println("Private key\n"+privKeyPEM);
        return pkcs8.toString();

          }


    /**
     * Saves a public key to a base64 encoded pem file
     * @param filename  name of the file 
     * @param key public key to be saved 
     * @return string representation of the pkcs8 object.
     * @throws Exception
     */
    public  String  SavePemPublicKey(String filename) throws Exception {
        PublicKey key=this.publickey;  
        File f = new File(filename);
          FileOutputStream fos = new FileOutputStream(f);
          DataOutputStream dos = new DataOutputStream(fos);


          byte[] keyBytes = key.getEncoded();
          BASE64Encoder b64=new BASE64Encoder();
          String  encoded = b64.encodeBuffer(keyBytes);

          encoded= "-----BEGIN PUBLIC KEY-----\r\n" + encoded + "-----END PUBLIC KEY-----";

         dos.writeBytes(encoded);
         dos.flush();
         dos.close();

          //System.out.println("Private key\n"+privKeyPEM);
      return  encoded.toString();

          }





       /**
     * reads a public key from a file
     * @param filename name of the file to read
     * @param algorithm is usually RSA
     * @return the read public key
     * @throws Exception
     */
    public  PublicKey getPemPublicKey(String filename, String algorithm) throws Exception {
          File f = new File(filename);
          FileInputStream fis = new FileInputStream(f);
          DataInputStream dis = new DataInputStream(fis);
          byte[] keyBytes = new byte[(int) f.length()];
          dis.readFully(keyBytes);
          dis.close();

          String temp = new String(keyBytes);
          String publicKeyPEM = temp.replace("-----BEGIN PUBLIC KEY-----\n", "");
          publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");


          BASE64Decoder b64=new BASE64Decoder();
          byte[] decoded = b64.decodeBuffer(publicKeyPEM);

          X509EncodedKeySpec spec =
                new X509EncodedKeySpec(decoded);
          KeyFactory kf = KeyFactory.getInstance(algorithm);
          return kf.generatePublic(spec);
          }




    public static void main(String[] args) throws Exception {
        csrgenerator gcsr = csrgenerator.getInstance();
        gcsr.setSignaturealgorithm("SHA512WithRSA");
        System.out.println("Public Key:\n"+gcsr.getPublicKey().toString());

        System.out.println("Private Key:\nAlgorithm: "+gcsr.getPrivateKey().getAlgorithm().toString());
        System.out.println("Format:"+gcsr.getPrivateKey().getFormat().toString());
        System.out.println("To String :"+gcsr.getPrivateKey().toString());
        System.out.println("GetEncoded :"+gcsr.getPrivateKey().getEncoded().toString());
        BASE64Encoder encoder= new BASE64Encoder();
        String s=encoder.encodeBuffer(gcsr.getPrivateKey().getEncoded());
        System.out.println("Base64:"+s+"\n");

        String csr = gcsr.getCSR( "[email protected]","baxshi az xodam", "Xodam","PointCook","VIC" ,"AU");
        System.out.println("CSR Request Generated!!");
        System.out.println(csr);
        gcsr.SaveCSR("c:\\testdir\\javacsr.csr");
        String p=gcsr.SavePemPrivateKey("c:\\testdir\\java_private.pem");
        System.out.print(p);
        p=gcsr.SavePemPublicKey("c:\\testdir\\java_public.pem");
        privateKey= gcsr.getPemPrivateKey("c:\\testdir\\java_private.pem", "RSA");
        BASE64Encoder encoder1= new BASE64Encoder();
        String s1=encoder1.encodeBuffer(gcsr.getPrivateKey().getEncoded());
        System.out.println("Private Key in Base64:"+s1+"\n");
        System.out.print(p);


    }

    }

Configuring so that pip install can work from github

I had similar issue when I had to install from github repo, but did not want to install git , etc.

The simple way to do it is using zip archive of the package. Add /zipball/master to the repo URL:

    $ pip install https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Downloading/unpacking https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
  Downloading master
  Running setup.py egg_info for package from https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Installing collected packages: django-debug-toolbar-mongo
  Running setup.py install for django-debug-toolbar-mongo
Successfully installed django-debug-toolbar-mongo
Cleaning up...

This way you will make pip work with github source repositories.

How to center horizontal table-cell

Sometimes you have things other than text inside a table cell that you'd like to be horizontally centered. In order to do this, first set up some css...

<style>
    div.centered {
        margin: auto;
        width: 100%;
        display: flex;
        justify-content: center;
    }
</style>

Then declare a div with class="centered" inside each table cell you want centered.

<td>
    <div class="centered">
        Anything: text, controls, etc... will be horizontally centered.
    </div>
</td>

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

If you really have to, you can make conditional comments work by adding the following line to <head>:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9">

Source

How Do I Upload Eclipse Projects to GitHub?

Many of these answers mention how to share the project on Git, which is easy, you just share the code on git, but one thing to take note of is that there is no apparent "project file" that the end user can double click on. Instead you have to use Import->General->Existing project and select the whole folder

What is __future__ in Python used for and how/when to use it, and how it works

It can be used to use features which will appear in newer versions while having an older release of Python.

For example

>>> from __future__ import print_function

will allow you to use print as a function:

>>> print('# of entries', len(dictionary), file=sys.stderr)

Disable all dialog boxes in Excel while running VB script?

In Access VBA I've used this to turn off all the dialogs when running a bunch of updates:

DoCmd.SetWarnings False

After running all the updates, the last step in my VBA script is:

DoCmd.SetWarnings True

Hope this helps.

Angular 2: 404 error occur when I refresh through the browser

In fact, it's normal that you have a 404 error when refreshing your application since the actual address within the browser is updating (and without # / hashbang approach). By default, HTML5 history is used for reusing in Angular2.

To fix the 404 error, you need to update your server to serve the index.html file for each route path you defined.

If you want to switch to the HashBang approach, you need to use this configuration:

import {bootstrap} from 'angular2/platform/browser';
import {provide} from 'angular2/core';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {LocationStrategy, HashLocationStrategy} from '@angular/common';

import {MyApp} from './myapp';

bootstrap(MyApp, [
  ROUTER_PROVIDERS,
  {provide: LocationStrategy, useClass: HashLocationStrategy}
]);

In this case, when you refresh the page, it will be displayed again (but you will have a # in your address).

This link could help you as well: When I refresh my website I get a 404. This is with Angular2 and firebase.

Hope it helps you, Thierry

String replacement in java, similar to a velocity template

I threw together a small test implementation of this. The basic idea is to call format and pass in the format string, and a map of objects, and the names that they have locally.

The output of the following is:

My dog is named fido, and Jane Doe owns him.

public class StringFormatter {

    private static final String fieldStart = "\\$\\{";
    private static final String fieldEnd = "\\}";

    private static final String regex = fieldStart + "([^}]+)" + fieldEnd;
    private static final Pattern pattern = Pattern.compile(regex);

    public static String format(String format, Map<String, Object> objects) {
        Matcher m = pattern.matcher(format);
        String result = format;
        while (m.find()) {
            String[] found = m.group(1).split("\\.");
            Object o = objects.get(found[0]);
            Field f = o.getClass().getField(found[1]);
            String newVal = f.get(o).toString();
            result = result.replaceFirst(regex, newVal);
        }
        return result;
    }

    static class Dog {
        public String name;
        public String owner;
        public String gender;
    }

    public static void main(String[] args) {
        Dog d = new Dog();
        d.name = "fido";
        d.owner = "Jane Doe";
        d.gender = "him";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("d", d);
        System.out.println(
           StringFormatter.format(
                "My dog is named ${d.name}, and ${d.owner} owns ${d.gender}.", 
                map));
    }
}

Note: This doesn't compile due to unhandled exceptions. But it makes the code much easier to read.

Also, I don't like that you have to construct the map yourself in the code, but I don't know how to get the names of the local variables programatically. The best way to do it, is to remember to put the object in the map as soon as you create it.

The following example produces the results that you want from your example:

public static void main(String[] args) {
    Map<String, Object> map = new HashMap<String, Object>();
    Site site = new Site();
    map.put("site", site);
    site.name = "StackOverflow.com";
    User user = new User();
    map.put("user", user);
    user.name = "jjnguy";
    System.out.println(
         format("Hello ${user.name},\n\tWelcome to ${site.name}. ", map));
}

I should also mention that I have no idea what Velocity is, so I hope this answer is relevant.

Android toolbar center title and custom font

for custom font in toolbar you can override textView font in style and then every textView in your app also toolbar title font changed automatically i tested it in android studio 3.1.3

in style do it:

<style name="defaultTextViewStyle" parent="android:Widget.TextView">
        <item name="android:fontFamily">@font/your_custom_font</item>
</style>

and then in your theme use this:

<item name="android:textViewStyle">@style/defaultTextViewStyle</item>

What should be in my .gitignore for an Android Studio project?

.gitignore from AndroidRate library

# Copyright 2017 - 2018 Vorlonsoft LLC
#
# Licensed under The MIT License (MIT)

# Built application files
*.ap_
*.apk

# Built library files
*.aar
*.jar

# Built native files
*.o
*.so

# Files for the Dalvik/Android Runtime (ART)
*.dex
*.odex

# Java class files
*.class

# Generated files
bin/
gen/
out/

# Gradle files
.gradle/
build/

# Local configuration file (sdk/ndk path, etc)
local.properties

# Windows thumbnail cache
Thumbs.db

# macOS
.DS_Store/

# Log Files
*.log

# Android Studio
.navigation/
captures/
output.json

# NDK
.externalNativeBuild/
obj/

# IntelliJ
## User-specific stuff
.idea/**/tasks.xml
.idea/**/workspace.xml
.idea/dictionaries
## Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/dynamic.xml
.idea/**/sqlDataSources.xml
.idea/**/uiDesigner.xml
## Gradle
.idea/**/gradle.xml
.idea/**/libraries
## VCS
.idea/vcs.xml
## Module files
*.iml
## File-based project format
*.iws

How to validate phone number using PHP?

Here's how I find valid 10-digit US phone numbers. At this point I'm assuming the user wants my content so the numbers themselves are trusted. I'm using in an app that ultimately sends an SMS message so I just want the raw numbers no matter what. Formatting can always be added later

//eliminate every char except 0-9
$justNums = preg_replace("/[^0-9]/", '', $string);

//eliminate leading 1 if its there
if (strlen($justNums) == 11) $justNums = preg_replace("/^1/", '',$justNums);

//if we have 10 digits left, it's probably valid.
if (strlen($justNums) == 10) $isPhoneNum = true;

Edit: I ended up having to port this to Java, if anyone's interested. It runs on every keystroke so I tried to keep it fairly light:

boolean isPhoneNum = false;
if (str.length() >= 10 && str.length() <= 14 ) { 
  //14: (###) ###-####
  //eliminate every char except 0-9
  str = str.replaceAll("[^0-9]", "");

  //remove leading 1 if it's there
  if (str.length() == 11) str = str.replaceAll("^1", "");

  isPhoneNum = str.length() == 10;
}
Log.d("ISPHONENUM", String.valueOf(isPhoneNum));

Resolving a Git conflict with binary files

mipadi's answer didn't quite work for me, I needed to do this :

git checkout --ours path/to/file.bin

or, to keep the version being merged in:

git checkout --theirs path/to/file.bin

then

git add path/to/file.bin

And then I was able to do "git mergetool" again and continue onto the next conflict.

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

In my case , I had wrote really two times an entity of same type . So I delete it and all things work correctly

How do you install GLUT and OpenGL in Visual Studio 2012?

the instructions for Vs2012

To Install FreeGLUT

  1. Download "freeglut 2.8.1 MSVC Package" from http://www.transmissionzero.co.uk/software/freeglut-devel/
  2. Extract the compressed file freeglut-MSVC.zip to a folder freeglut

  3. Inside freeglut folder:

On 32bit versions of windows

copy all files in include/GL folder to C:\Program Files\Windows Kits\8.0\Include\um\gl

copy all files in lib folder to C:\Program Files\Windows Kits\8.0\Lib\win8\um\ (note: Lib\freeglut.lib in a folder goes into x86)

copy freeglut.dll to C:\windows\system32

On 64bit versions of windows:(not 100% sure but try)

copy all files in include/GL folder to C:\Program Files(x86)\Windows Kits\8.0\Include\um\gl

copy all files in lib folder to C:\Program Files(x86)\Windows Kits\8.0\Lib\win8\um\ (note: Lib\freeglut.lib in a folder goes into x86)

copy freeglut.dll to C:\windows\SysWOW64

RecyclerView - How to smooth scroll to top of item on a certain position?

We can try like this

    recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView,new RecyclerView.State(), recyclerView.getAdapter().getItemCount());

How to prevent scanf causing a buffer overflow in C?

If you are using gcc, you can use the GNU-extension a specifier to have scanf() allocate memory for you to hold the input:

int main()
{
  char *str = NULL;

  scanf ("%as", &str);
  if (str) {
      printf("\"%s\"\n", str);
      free(str);
  }
  return 0;
}

Edit: As Jonathan pointed out, you should consult the scanf man pages as the specifier might be different (%m) and you might need to enable certain defines when compiling.

Saving binary data as file using JavaScript from a browser

Try

_x000D_
_x000D_
let bytes = [65,108,105,99,101,39,115,32,65,100,118,101,110,116,117,114,101];_x000D_
_x000D_
let base64data = btoa(String.fromCharCode.apply(null, bytes));_x000D_
_x000D_
let a = document.createElement('a');_x000D_
a.href = 'data:;base64,' + base64data;_x000D_
a.download = 'binFile.txt'; _x000D_
a.click();
_x000D_
_x000D_
_x000D_

I convert here binary data to base64 (for bigger data conversion use this) - during downloading browser decode it automatically and save raw data in file. 2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop working (probably due to sandbox security restrictions) - but JSFiddle version works - here

How do I tell Spring Boot which main class to use for the executable jar?

I had renamed my project and it was still finding the old Application class on the build path. I removed it in the 'build' folder and all was fine.

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

Make ABC Ordered List Items Have Bold Style

You could do something like this also:

ol {
  font-weight: bold;
}

ol > li > * {
  font-weight: normal;
}

So you have no "style" attributes in your HTML

How can I group by date time column without taking time into consideration

In pre Sql 2008 By taking out the date part:

GROUP BY CONVERT(CHAR(8),DateTimeColumn,10)

pyplot scatter plot marker size

I also attempted to use 'scatter' initially for this purpose. After quite a bit of wasted time - I settled on the following solution.

import matplotlib.pyplot as plt
input_list = [{'x':100,'y':200,'radius':50, 'color':(0.1,0.2,0.3)}]    
output_list = []   
for point in input_list:
    output_list.append(plt.Circle((point['x'], point['y']), point['radius'], color=point['color'], fill=False))
ax = plt.gca(aspect='equal')
ax.cla()
ax.set_xlim((0, 1000))
ax.set_ylim((0, 1000))
for circle in output_list:    
   ax.add_artist(circle)

enter image description here

This is based on an answer to this question

while EOF in JAVA?

Each call to nextLine() moves onto the next line, so when you are actually at the last readable line and the while check passes inspection, the next call to nextLine() will return EOF.


Perhaps you could do one of the following instead:

If fileReader is of type Scanner:

while ((line = fileReader.hasNextLine()) != null) {
    String line = fileReader.nextLine(); 
    System.out.println(line);
}

If fileReader is of type BufferedReader:

String line;
while ((line = fileReader.readLine()) != null) {
    System.out.println(line);
}

So you're reading the current line in the while condition and saving the line in a string for later use.

AngularJS. How to call controller function from outside of controller component

The solution angular.element(document.getElementById('ID')).scope().get() stopped working for me in angular 1.5.2. Sombody mention in a comment that this doesn't work in 1.4.9 also. I fixed it by storing the scope in a global variable:

var scopeHolder;
angular.module('fooApp').controller('appCtrl', function ($scope) {
    $scope = function bar(){
        console.log("foo");        
    };
    scopeHolder = $scope;
})

call from custom code:

scopeHolder.bar()

if you wants to restrict the scope to only this method. To minimize the exposure of whole scope. use following technique.

var scopeHolder;
angular.module('fooApp').controller('appCtrl', function ($scope) {
    $scope.bar = function(){
        console.log("foo");        
    };
    scopeHolder = $scope.bar;
})

call from custom code:

scopeHolder()

Cleanest way to write retry logic?

This method allows retries on certain exception types (throws others immediately).

public static void DoRetry(
    List<Type> retryOnExceptionTypes,
    Action actionToTry,
    int retryCount = 5,
    int msWaitBeforeEachRety = 300)
{
    for (var i = 0; i < retryCount; ++i)
    {
        try
        {
            actionToTry();
            break;
        }
        catch (Exception ex)
        {
            // Retries exceeded
            // Throws on last iteration of loop
            if (i == retryCount - 1) throw;

            // Is type retryable?
            var exceptionType = ex.GetType();
            if (!retryOnExceptionTypes.Contains(exceptionType))
            {
                throw;
            }

            // Wait before retry
            Thread.Sleep(msWaitBeforeEachRety);
        }
    }
}
public static void DoRetry(
    Type retryOnExceptionType,
    Action actionToTry,
    int retryCount = 5,
    int msWaitBeforeEachRety = 300)
        => DoRetry(new List<Type> {retryOnExceptionType}, actionToTry, retryCount, msWaitBeforeEachRety);

Example usage:

DoRetry(typeof(IOException), () => {
    using (var fs = new FileStream(requestedFilePath, FileMode.Create, FileAccess.Write))
    {
        fs.Write(entryBytes, 0, entryBytes.Length);
    }
});

How do I add a reference to the MySQL connector for .NET?

"Add a reference to MySql.Data.dll" means you need to add a library reference to the downloaded connector. The IDE will link the database connection library with your application when it compiles.

Step-by-Step Example

I downloaded the binary (no installer) zip package from the MySQL web site, extracted onto the desktop, and did the following:

  1. Create a new project in Visual Studio
  2. In the Solution Explorer, under the project name, locate References and right-click on it. Select "Add Reference".
  3. In the "Add Reference" dialog, switch to the "Browse" tab and browse to the folder containing the downloaded connector. Navigate to the "bin" folder, and select the "MySql.Data.dll" file. Click OK.
  4. At the top of your code, add using MySql.Data.MySqlClient;. If you've added the reference correctly, IntelliSense should offer to complete this for you.

What causes this error? "Runtime error 380: Invalid property value"

I presume your application uses a masked edit box? This is a relatively well known problem, documented by Microsoft here:

http://support.microsoft.com/kb/177088

The article refers to VB4 and 5, but I am pretty sure the same is true for VB6.

EDIT

On further research, I am finding references to this problem with other controls as well. Recompiling your application on Windows XP for users that are running XP will probably produce them a working version, though it's not an ideal solution...

Cannot access wamp server on local network

If you are using wamp stack, it will be fixed by open port in Firewall (Control Pannel). It work for my case (detail how to open port 80: https://tips.alocentral.com/open-tcp-port-80-in-windows-firewall/)

Change a Nullable column to NOT NULL with Default Value

Try this

ALTER TABLE table_name ALTER COLUMN col_name data_type NOT NULL;

Trigger a Travis-CI rebuild without pushing a commit?

If the build never occurred (perhaps you didn't get the Pull-Request build switch set to on in time), you can mark the Pull Request on Github as closed then mark it as opened and a new build will be triggered.

Scroll RecyclerView to show selected item on top

just call this method simply:

((LinearLayoutManager)recyclerView.getLayoutManager()).scrollToPositionWithOffset(yourItemPosition,0);

instead of:

recyclerView.scrollToPosition(yourItemPosition);

ERROR: Sonar server 'http://localhost:9000' can not be reached

In sonar.properties file in conf folder I had hardcoaded ip of my machine where sobarqube was installed in property sonar.web.host=10.9 235.22 I commented this and it started working for me.

Java error: Implicit super constructor is undefined for default constructor

You can solve this error by adding an argumentless constructor to the base class (as shown below).

Cheers.

 abstract public class BaseClass {
        // ADD AN ARGUMENTLESS CONSTRUCTOR TO THE BASE CLASS
        public BaseClass(){
        }

        String someString;
        public BaseClass(String someString) {
            this.someString = someString;
        }
        abstract public String getName();
    }

public class ACSubClass extends BaseClass {
    public ASubClass(String someString) {
        super(someString);
    }
    public String getName() {
        return "name value for ASubClass";
    }
}

apc vs eaccelerator vs xcache

APC is going to be included in PHP 6, and I'd guess it has been chosen for good reason :)

It's fairly easy to install and certainly speeds things up.

Return JSON with error status code MVC

The neatest solution I've found is to create your own JsonResult that extends the original implementation and allows you to specify a HttpStatusCode:

public class JsonHttpStatusResult : JsonResult
{
    private readonly HttpStatusCode _httpStatus;

    public JsonHttpStatusResult(object data, HttpStatusCode httpStatus)
    {
        Data = data;
        _httpStatus = httpStatus;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        context.RequestContext.HttpContext.Response.StatusCode = (int)_httpStatus;
        base.ExecuteResult(context);
    }
}

You can then use this in your controller action like so:

if(thereWereErrors)
{
    var errorModel = new { error = "There was an error" };
    return new JsonHttpStatusResult(errorModel, HttpStatusCode.InternalServerError);
}

.bashrc: Permission denied

The .bashrc file is in your user home directory (~/.bashrc or ~vagrant/.bashrc both resolve to the same path), inside the VM's filesystem. This file is invisible on the host machine, so you can't use any Windows editors to edit it directly.

You have two simple choices:

  1. Learn how to use a console-based text editor. My favourite is vi (or vim), which takes 15 minutes to learn the basics and is much quicker for simple edits than anything else.

    vi .bashrc

  2. Copy .bashrc out to /vagrant (which is a shared directory) and edit it using your Windows editors. Make sure not to save it back with any extensions.

    cp .bashrc /vagrant ... edit using your host machine ... cp /vagrant/.bashrc .

I'd recommend getting to know the command-line based editors. Once you're working inside the VM, it's best to stay there as otherwise you might just get confused.

You (the vagrant user) are the owner of your home .bashrc so you do have permissions to edit it.

Once edited, you can execute it by typing source .bashrc I prefer to logout and in again (there may be more than one file executed on login).

Using a remote repository with non-standard port

Try this

git clone ssh://[email protected]:11111/home/git/repo.git

How to rotate a div using jQuery

EDIT: Updated for jQuery 1.8

Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: Added code to make it a jQuery function.

For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.


Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.

Here is a jsFiddle.

If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.

HTML

<div class="rotate">
    <h1>Rotatey text</h1>
</div>

CSS

/* Totally for style */
.rotate {
    background: #F02311;
    color: #FFF;
    width: 200px;
    height: 200px;
    text-align: center;
    font: normal 1em Arial;
    position: relative;
    top: 50px;
    left: 50px;
}

/* The real code */
.rotated {
    -webkit-transform: rotate(45deg);  /* Chrome, Safari 3.1+ */
    -moz-transform: rotate(45deg);  /* Firefox 3.5-15 */
    -ms-transform: rotate(45deg);  /* IE 9 */
    -o-transform: rotate(45deg);  /* Opera 10.50-12.00 */
    transform: rotate(45deg);  /* Firefox 16+, IE 10+, Opera 12.10+ */
}

jQuery

Make sure these are wrapped in $(document).ready

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});

Custom intervals

var rotation = 0;
$('.rotate').click(function() {
    rotation += 5;
    $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
                 '-moz-transform' : 'rotate('+ rotation +'deg)',
                 '-ms-transform' : 'rotate('+ rotation +'deg)',
                 'transform' : 'rotate('+ rotation +'deg)'});
});

How do I get the last character of a string using an Excel function?

Just another way to do this:

=MID(A1, LEN(A1), 1)

Call an overridden method from super class in typescript

below is an generic example

    //base class
    class A {
        
        // The virtual method
        protected virtualStuff1?():void;
    
        public Stuff2(){
            //Calling overridden child method by parent if implemented
            this.virtualStuff1 && this.virtualStuff1();
            alert("Baseclass Stuff2");
        }
    }
    
    //class B implementing virtual method
    class B extends A{
        
        // overriding virtual method
        public virtualStuff1()
        {
            alert("Class B virtualStuff1");
        }
    }
    
    //Class C not implementing virtual method
    class C extends A{
     
    }
    
    var b1 = new B();
    var c1= new C();
    b1.Stuff2();
    b1.virtualStuff1();
    c1.Stuff2();

MongoDB - Update objects in a document's array (nested updating)

There is no way to do this in single query. You have to search the document in first query:

If document exists:

db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } , 
                {$inc : {"items.$.price" : 1} } , 
                false , 
                true);

Else

db.bar.update( {user_id : 123456 } , 
                {$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
                false , 
                true);

No need to add condition {$ne : "my_item_two" }.

Also in multithreaded enviourment you have to be careful that only one thread can execute the second (insert case, if document did not found) at a time, otherwise duplicate embed documents will be inserted.

JNI converting jstring to char *

Thanks Jason Rogers's answer first.

In Android && cpp should be this:

const char *nativeString = env->GetStringUTFChars(javaString, nullptr);

// use your string

env->ReleaseStringUTFChars(javaString, nativeString);

Can fix this errors:

1.error: base operand of '->' has non-pointer type 'JNIEnv {aka _JNIEnv}'

2.error: no matching function for call to '_JNIEnv::GetStringUTFChars(JNIEnv*&, _jstring*&, bool)'

3.error: no matching function for call to '_JNIEnv::ReleaseStringUTFChars(JNIEnv*&, _jstring*&, char const*&)'

4.add "env->DeleteLocalRef(nativeString);" at end.

How to get the selected item from ListView?

You are implementing the Click Handler rather than Select Handler. A List by default doesn't suppose to have selection.

What you should change, in your above example, is to

public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
    MyClass item = (MyClass) adapter.getItem(position);
}

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

Change the position attribute to fixed instead of absolute.

How to connect Robomongo to MongoDB

  1. First you have to run the mongod command in your terminal. Make sure the command executes properly.

  2. Then in a new terminal tab run the mongo command.

  3. Then open the Robomongo GUI and create a new connection with the default settings.

How to import data from text file to mysql database

You should set the option:

local-infile=1

into your [mysql] entry of my.cnf file or call mysql client with the --local-infile option:

mysql --local-infile -uroot -pyourpwd yourdbname

You have to be sure that the same parameter is defined into your [mysqld] section too to enable the "local infile" feature server side.

It's a security restriction.

LOAD DATA LOCAL INFILE '/softwares/data/data.csv' INTO TABLE tableName;

Add to Array jQuery

You are right. This has nothing to do with jQuery though.

var myArray = [];
myArray.push("foo");
// myArray now contains "foo" at index 0.

How to exclude particular class name in CSS selector?

In modern browsers you can do:

.reMode_hover:not(.reMode_selected):hover{}

Consult http://caniuse.com/css-sel3 for compatibility information.

Your content must have a ListView whose id attribute is 'android.R.id.list'

<ListView android:id="@id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="false"
        android:scrollbars="vertical"/>

Format date and Subtract days using Moment.js

Try this:

var duration = moment.duration({'days' : 1});
moment().subtract(duration).format('DD-MM-YYYY');

This will give you 14-04-2015 - today is 15-04-2015

Alternatively if your momentjs version is less than 2.8.0, you can use:

startdate = moment().subtract('days', 1).format('DD-MM-YYYY');

Instead of this:

startdate = moment().subtract(1, 'days').format('DD-MM-YYYY');

Error: the entity type requires a primary key

Removed and added back in the table using Scaffold-DbContext and the error went away

How can I create numbered map markers in Google Maps V3?

Google Maps version 3 has built-in support for marker labels. No need to generate your own images anymore or implement 3rd party classes. Marker Labels

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

        config.Formatters.Remove(config.Formatters.XmlFormatter);

Make a VStack fill the width of the screen in SwiftUI

One more alternative is to place one of the subviews inside of an HStack and place a Spacer() after it:

struct ContentView : View {
    var body: some View {
        VStack(alignment: .leading) {

            HStack {
                Text("Title")
                    .font(.title)
                    .background(Color.yellow)
                Spacer()
            }

            Text("Content")
                .lineLimit(nil)
                .font(.body)
                .background(Color.blue)

            Spacer()
            }

            .background(Color.red)
    }
}

resulting in :

HStack inside a VStack

Docker can't connect to docker daemon

If regenerating TLS certificates doesn't work

docker-machine regenerate-certs default

Try restarting the docker machine and setting the env variable:

docker-machine restart default
eval $(docker-machine env default)

Check if the machine is running with:

docker-machine ls

or alternatively

docker run hello-world

This worked for me. However, if you still don't have the daemon up, Docker's troubleshooting page details a process for stopping, removing and creating a new machine.

Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

It was particular for me. I am sending a header named 'SESSIONHASH'. No problem for Chrome and Opera, but Firefox also wants this header in the list "Access-Control-Allow-Headers". Otherwise, Firefox will throw the CORS error.

How to extract the n-th elements from a list of tuples?

Found this as I was searching for which way is fastest to pull the second element of a 2-tuple list. Not what I wanted but ran same test as shown with a 3rd method plus test the zip method

setup = 'elements = [(1,1) for _ in range(100000)];from operator import itemgetter'
method1 = '[x[1] for x in elements]'
method2 = 'map(itemgetter(1), elements)'
method3 = 'dict(elements).values()'
method4 = 'zip(*elements)[1]'

import timeit
t = timeit.Timer(method1, setup)
print('Method 1: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup)
print('Method 2: ' + str(t.timeit(100)))
t = timeit.Timer(method3, setup)
print('Method 3: ' + str(t.timeit(100)))
t = timeit.Timer(method4, setup)
print('Method 4: ' + str(t.timeit(100)))

Method 1: 0.618785858154
Method 2: 0.711684942245
Method 3: 0.298138141632
Method 4: 1.32586884499

So over twice as fast if you have a 2 tuple pair to just convert to a dict and take the values.

while ($row = mysql_fetch_array($result)) - how many loops are being performed?

For the first one: your program will go through the loop once for every row in the result set returned by the query. You can know in advance how many results there are by using mysql_num_rows().

For the second one: this time you are only using one row of the result set and you are doing something for each of the columns. That's what the foreach language construct does: it goes through the body of the loop for each entry in the array $row. The number of times the program will go through the loop is knowable in advance: it will go through once for every column in the result set (which presumably you know, but if you need to determine it you can use count($row)).

How to add onload event to a div element

First to answer your question: No, you can't, not directly like you wanted to do so. May be a bit late to answer, but this is my solution, without jQuery, pure javascript. It was originally written to apply a resize function to textareas after DOM is loaded and on keyup.

Same way you could use it to do something with (all) divs or only one, if specified, like so:

document.addEventListener("DOMContentLoaded", function() {
    var divs = document.querySelectorAll('div'); // all divs
    var mydiv = document.getElementById('myDiv'); // only div#myDiv
    divs.forEach( div => {
        do_something_with_all_divs(div);
    });
    do_something_with_mydiv(mydiv);
});

If you really need to do something with a div, loaded after the DOM is loaded, e.g. after an ajax call, you could use a very helpful hack, which is easy to understand an you'll find it ...working-with-elements-before-the-dom-is-ready.... It says "before the DOM is ready" but it works brillant the same way, after an ajax insertion or js-appendChild-whatever of a div. Here's the code, with some tiny changes to my needs.

css

.loaded { // I use only class loaded instead of a nodename
    animation-name: nodeReady;
    animation-duration: 0.001s;
}

@keyframes nodeReady {  
    from { clip: rect(1px, auto, auto, auto); }
    to { clip: rect(0px, auto, auto, auto); }  
}

javascript

document.addEventListener("animationstart", function(event) {
    var e = event || window.event;
    if (e.animationName == "nodeReady") {
        e.target.classList.remove('loaded');
        do_something_else();
    }
}, false);

What is the function __construct used for?

__construct is a method for initializing of new object before it is used.
http://php.net/manual/en/language.oop5.decon.php#object.construct

Groovy String to Date

Googling around for Groovy ways to "cast" a String to a Date, I came across this article: http://www.goodercode.com/wp/intercept-method-calls-groovy-type-conversion/

The author uses Groovy metaMethods to allow dynamically extending the behavior of any class' asType method. Here is the code from the website.

class Convert {
    private from
    private to

    private Convert(clazz) { from = clazz }
    static def from(clazz) {
        new Convert(clazz)
    }

    def to(clazz) {
        to = clazz
        return this
    }

    def using(closure) {
        def originalAsType = from.metaClass.getMetaMethod('asType', [] as Class[])
        from.metaClass.asType = { Class clazz ->
            if( clazz == to ) {
                closure.setProperty('value', delegate)
                closure(delegate)
            } else {
                originalAsType.doMethodInvoke(delegate, clazz)
            }
        }
    }
}

They provide a Convert class that wraps the Groovy complexity, making it trivial to add custom as-based type conversion from any type to any other:

Convert.from( String ).to( Date ).using { new java.text.SimpleDateFormat('MM-dd-yyyy').parse(value) }

def christmas = '12-25-2010' as Date

It's a convenient and powerful solution, but I wouldn't recommend it to someone who isn't familiar with the tradeoffs and pitfalls of tinkering with metaClasses.

Laravel Checking If a Record Exists

Shortest working options:

// if you need to do something with the user 
if ($user = User::whereEmail(Input::get('email'))->first()) {

    // ...

}

// otherwise
$userExists = User::whereEmail(Input::get('email'))->exists();

SQL conditional SELECT

@selectField1 AS bit
@selectField2 AS bit

SELECT
CASE 
    WHEN @selectField1 THEN Field1
    WHEN @selectField2 THEN Field2
    ELSE someDefaultField
END
FROM Table

Is this what you're looking for?

Disabling and enabling a html input button

You can do this fairly easily with just straight JavaScript, no libraries required.

Enable a button

document.getElementById("Button").disabled=false;

Disable a button

 document.getElementById("Button").disabled=true;

No external libraries necessary.

Turning Sonar off for certain code

You can annotate a class or a method with SuppressWarnings

@java.lang.SuppressWarnings("squid:S00112")

squid:S00112 in this case is a Sonar issue ID. You can find this ID in the Sonar UI. Go to Issues Drilldown. Find an issue you want to suppress warnings on. In the red issue box in your code is there a Rule link with a definition of a given issue. Once you click that you will see the ID at the top of the page.

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

In a shameless attempt to steal some votes, SecurityProtocol is an Enum with the [Flags] attribute. So you can do this:

[Net.ServicePointManager]::SecurityProtocol = 
  [Net.SecurityProtocolType]::Tls12 -bor `
  [Net.SecurityProtocolType]::Tls11 -bor `
  [Net.SecurityProtocolType]::Tls

Or since this is PowerShell, you can let it parse a string for you:

[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"

Then you don't technically need to know the TLS version.

I copied and pasted this from a script I created after reading this answer because I didn't want to cycle through all the available protocols to find one that worked. Of course, you could do that if you wanted to.

Final note - I have the original (minus SO edits) statement in my PowerShell profile so it's in every session I start now. It's not totally foolproof since there are still some sites that just fail but I surely see the message in question much less frequently.

Proper way to return JSON using node or Express

You can use a middleware to set the default Content-Type, and set Content-Type differently for particular APIs. Here is an example:

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

const port = process.env.PORT || 3000;

const server = app.listen(port);

server.timeout = 1000 * 60 * 10; // 10 minutes

// Use middleware to set the default Content-Type
app.use(function (req, res, next) {
    res.header('Content-Type', 'application/json');
    next();
});

app.get('/api/endpoint1', (req, res) => {
    res.send(JSON.stringify({value: 1}));
})

app.get('/api/endpoint2', (req, res) => {
    // Set Content-Type differently for this particular API
    res.set({'Content-Type': 'application/xml'});
    res.send(`<note>
        <to>Tove</to>
        <from>Jani</from>
        <heading>Reminder</heading>
        <body>Don't forget me this weekend!</body>
        </note>`);
})

Create Carriage Return in PHP String?

$postfields["message"] = "This is a sample ticket opened by the API\rwith a carriage return";

Division of integers in Java

In Java
Integer/Integer = Integer
Integer/Double = Double//Either of numerator or denominator must be floating point number
1/10 = 0
1.0/10 = 0.1
1/10.0 = 0.1

Just type cast either of them.

How do I sleep for a millisecond in Perl?

From perlfaq8:


How can I sleep() or alarm() for under a second?

If you want finer granularity than the 1 second that the sleep() function provides, the easiest way is to use the select() function as documented in select in perlfunc. Try the Time::HiRes and the BSD::Itimer modules (available from CPAN, and starting from Perl 5.8 Time::HiRes is part of the standard distribution).

Check object empty

If your Object contains Objects then check if they are null, if it have primitives check for their default values.

for Instance:

Person Object 
name Property with getter and setter

to check if name is not initialized. 

Person p = new Person();
if(p.getName()!=null)

How to uninstall Ruby from /usr/local?

Edit: As suggested in comments. This solution is for Linux OS. That too if you have installed ruby manually from package-manager.

If you want to have multiple ruby versions, better to have RVM. In that case you don't need to remove ruby older version.

Still if want to remove then follow the steps below:

First you should find where Ruby is:

whereis ruby

will list all the places where it exists on your system, then you can remove all them explicitly. Or you can use something like this:

rm -rf /usr/local/lib/ruby
rm -rf /usr/lib/ruby
rm -f /usr/local/bin/ruby
rm -f /usr/bin/ruby
rm -f /usr/local/bin/irb
rm -f /usr/bin/irb
rm -f /usr/local/bin/gem
rm -f /usr/bin/gem

How to get the nvidia driver version from the command line?

modinfo does the trick.

root@nyx:/usr/src# modinfo nvidia|grep version:
version:        331.113

Could not load type 'XXX.Global'

When you try to access the Microsoft Dynamics NAV Web client, you get the following error. Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 This error can occur when there are multiple versions of the .NET Framework on the computer that is running IIS, and IIS was installed after .NET Framework 4.0 or before the Service Model in Windows Communication Foundation was registered.

For Windows 7 and Windows Server 2008, use the ASP.NET IIS Registration Tool (aspnet_regiis.exe,) to register the correct version of ASP.NET. For more information about the aspnet_regiis.exe, see ASP.NET IIS Registration Tool at Microsoft web site.

try this solution https://www.youtube.com/watch?v=LNwpNqgX7qw

How to cancel/abort jQuery AJAX request?

You can use jquery-validate.js . The following is the code snippet from jquery-validate.js.

// ajax mode: abort
// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()

var pendingRequests = {},
    ajax;
// Use a prefilter if available (1.5+)
if ( $.ajaxPrefilter ) {
    $.ajaxPrefilter(function( settings, _, xhr ) {
        var port = settings.port;
        if ( settings.mode === "abort" ) {
            if ( pendingRequests[port] ) {
                pendingRequests[port].abort();
            }
            pendingRequests[port] = xhr;
        }
    });
} else {
    // Proxy ajax
    ajax = $.ajax;
    $.ajax = function( settings ) {
        var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,
            port = ( "port" in settings ? settings : $.ajaxSettings ).port;
        if ( mode === "abort" ) {
            if ( pendingRequests[port] ) {
                pendingRequests[port].abort();
            }
            pendingRequests[port] = ajax.apply(this, arguments);
            return pendingRequests[port];
        }
        return ajax.apply(this, arguments);
    };
}

So that you just only need to set the parameter mode to abort when you are making ajax request.

Ref:https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.js

Address validation using Google Maps API

I know that this post is a bit old but incase anyone finds it still relevant you might want to check out the free geocoding services offered by USC College. This does included address validation via ajax and static calls. The only catch is that they request a link back and only offer allotments of 2500 calls. More than fair. https://webgis.usc.edu/Services/AddressValidation/Default.aspx

Show ImageView programmatically

Redirect website after certain amount of time

Here's a complete (yet simple) example of redirecting after X seconds, while updating a counter div:

_x000D_
_x000D_
<html>_x000D_
<body>_x000D_
    <div id="counter">5</div>_x000D_
    <script>_x000D_
        setInterval(function() {_x000D_
            var div = document.querySelector("#counter");_x000D_
            var count = div.textContent * 1 - 1;_x000D_
            div.textContent = count;_x000D_
            if (count <= 0) {_x000D_
                window.location.replace("https://example.com");_x000D_
            }_x000D_
        }, 1000);_x000D_
    </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

The initial content of the counter div is the number of seconds to wait.

Bootstrap 3 panel header with buttons wrong position

or this? By using row class

  <div class="row"> 
  <div class="  col-lg-2  col-md-2 col-sm-2 col-xs-2">
     <h4>Panel header</h4>
  </div>
 <div class="  col-lg-10  col-md-10 col-sm-10 col-xs-10 ">
    <div class="btn-group  pull-right">
       <a href="#" class="btn btn-default btn-sm">## Lock</a>
        <a href="#" class="btn btn-default btn-sm">## Delete</a>
        <a href="#" class="btn btn-default btn-sm">## Move</a>
    </div>
     </div>
  </div>
</div>

Are the decimal places in a CSS width respected?

Even when the number is rounded when the page is painted, the full value is preserved in memory and used for subsequent child calculation. For example, if your box of 100.4999px paints to 100px, it's child with a width of 50% will be calculated as .5*100.4999 instead of .5*100. And so on to deeper levels.

I've created deeply nested grid layout systems where parents widths are ems, and children are percents, and including up to four decimal points upstream had a noticeable impact.

Edge case, sure, but something to keep in mind.

ERROR 1064 (42000) in MySQL

This was my case: I forgot to add ' before );

End of file.sql with error:

...
('node','ad','0','3879','3879','und','0','-14.30602','-170.696181','0','0','0'),
('node','ad','0','3880','3880','und','0','-14.30602','-170.696181','0','0','0);

End of file.sql without error:

...
('node','ad','0','3879','3879','und','0','-14.30602','-170.696181','0','0','0'),
('node','ad','0','3880','3880','und','0','-14.30602','-170.696181','0','0','0');

php refresh current page?

$_SERVER['REQUEST_URI'] should work.

Document Root PHP

Just / refers to the root of your website from the public html folder. DOCUMENT_ROOT refers to the local path to the folder on the server that contains your website.

For example, I have EasyPHP setup on a machine...

$_SERVER["DOCUMENT_ROOT"] gives me file:///C:/Program%20Files%20(x86)/EasyPHP-5.3.9/www but any file I link to with just / will be relative to my www folder.

If you want to give the absolute path to a file on your server (from the server's root) you can use DOCUMENT_ROOT. if you want to give the absolute path to a file from your website's root, use just /.

Proper use of errors

The convention for out of range in JavaScript is using RangeError. To check the type use if / else + instanceof starting at the most specific to the most generic

try {
    throw new RangeError();
}
catch (e){
    if (e instanceof RangeError){
        console.log('out of range');
    } else { 
        throw; 
    }
}

Sorting HTML table with JavaScript

I have edited the code from one of the example here to use jquery. It's still not 100% jquery though. Any thoughts on the two different versions, like what are the pros and cons of each?

function column_sort() {
    getCellValue = (tr, idx) => $(tr).find('td').eq( idx ).text();

    comparer = (idx, asc) => (a, b) => ((v1, v2) => 
        v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)
        )(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
    
    table = $(this).closest('table')[0];
    tbody = $(table).find('tbody')[0];

    elm = $(this)[0];
    children = elm.parentNode.children;
    Array.from(tbody.querySelectorAll('tr')).sort( comparer(
        Array.from(children).indexOf(elm), table.asc = !table.asc))
        .forEach(tr => tbody.appendChild(tr) );
}

table.find('thead th').on('click', column_sort);

What is the use of "object sender" and "EventArgs e" parameters?

Those two parameters (or variants of) are sent, by convention, with all events.

  • sender: The object which has raised the event
  • e an instance of EventArgs including, in many cases, an object which inherits from EventArgs. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.

In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs are Empty as there is no further information about the event.

Looking at the 2 parameters separately, here are some examples where they are useful.

sender

Say you have multiple buttons on a form. These buttons could contain a Tag describing what clicking them should do. You could handle all the Click events with the same handler, and depending on the sender do something different

private void HandleButtonClick(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    if(btn.Tag == "Hello")
      MessageBox.Show("Hello")
    else if(btn.Tag == "Goodbye")
       Application.Exit();
    // etc.
}

Disclaimer : That's a contrived example; don't do that!

e

Some events are cancelable. They send CancelEventArgs instead of EventArgs. This object adds a simple boolean property Cancel on the event args. Code handling this event can cancel the event:

private void HandleCancellableEvent(object sender, CancelEventArgs e)
{
    if(/* some condition*/)
    {
       // Cancel this event
       e.Cancel = true;
    }
}

How to get a cross-origin resource sharing (CORS) post request working

If for some reasons while trying to add headers or set control policy you're still getting nowhere you may consider using apache ProxyPass…

For example in one <VirtualHost> that uses SSL add the two following directives:

SSLProxyEngine On
ProxyPass /oauth https://remote.tld/oauth

Make sure the following apache modules are loaded (load them using a2enmod):

  • proxy
  • proxy_connect
  • proxy_http

Obviously you'll have to change your AJAX requests url in order to use the apache proxy…

Convert all data frame character columns to factors

The easiest way would be to use the code given below. It would automate the whole process of converting all the variables as factors in a dataframe in R. it worked perfectly fine for me. food_cat here is the dataset which I am using. Change it to the one which you are working on.

    for(i in 1:ncol(food_cat)){

food_cat[,i] <- as.factor(food_cat[,i])

}

Check if a string isn't nil or empty in Lua

One simple thing you could do is abstract the test inside a function.

local function isempty(s)
  return s == nil or s == ''
end

if isempty(foo) then
  foo = "default value"
end

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

Open android/gradle/gradle-wrapper.properties and change this line: distributionUrl=

https\://services.gradle.org/distributions/gradle-4.1-all.zip

to this line:

distributionUrl=

https\://services.gradle.org/distributions/gradle-4.4-all.zip

Open android/build.gradle and change this line:

classpath 'com.android.tools.build:gradle:3.0.1'

to this:

classpath 'com.android.tools.build:gradle:3.1.2'

How to append the output to a file?

Yeah.

command >> file to redirect just stdout of command.

command >> file 2>&1 to redirect stdout and stderr to the file (works in bash, zsh)

And if you need to use sudo, remember that just

sudo command >> /file/requiring/sudo/privileges does not work, as privilege elevation applies to command but not shell redirection part. However, simply using tee solves the problem:

command | sudo tee -a /file/requiring/sudo/privileges

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

This is due to a PHP 5.3.0 bug on Windows where MYSQL_ATTR_INIT_COMMAND is not available. The PHP bug report is:

http://bugs.php.net/bug.php?id=47224

If you are experiencing this, please update your WAMP product to a version that uses PHP 5.3.1 or later version.

How to convert LINQ query result to List?

No need to do so much works..

var query = from c in obj.tbCourses
        where ...
        select c;

Then you can use:

List<course> list_course= query.ToList<course>();

It works fine for me.

Get to UIViewController from UIView?

This doesn't answer the question directly, but rather makes an assumption about the intent of the question.

If you have a view and in that view you need to call a method on another object, like say the view controller, you can use the NSNotificationCenter instead.

First create your notification string in a header file

#define SLCopyStringNotification @"ShaoloCopyStringNotification"

In your view call postNotificationName:

- (IBAction) copyString:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:SLCopyStringNotification object:nil];
}

Then in your view controller you add an observer. I do this in viewDidLoad

- (void)viewDidLoad
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(copyString:)
                                                 name:SLCopyStringNotification
                                               object:nil];
}

Now (also in the same view controller) implement your method copyString: as depicted in the @selector above.

- (IBAction) copyString:(id)sender
{
    CalculatorResult* result = (CalculatorResult*)[[PercentCalculator sharedInstance].arrayTableDS objectAtIndex:([self.viewTableResults indexPathForSelectedRow].row)];
    UIPasteboard *gpBoard = [UIPasteboard generalPasteboard];
    [gpBoard setString:result.stringResult];
}

I'm not saying this is the right way to do this, it just seems cleaner than running up the first responder chain. I used this code to implement a UIMenuController on a UITableView and pass the event back up to the UIViewController so I can do something with the data.

How does JavaScript .prototype work?

The Prototype creates new object by cloning existing object. So really when we think about prototype we can really think cloning or making a copy of something instead of making it up.

How to create border in UIButton?

This can be achieved in various methods in Swift 3.0 Worked on Latest version August - 2017

Option 1:

Directly assign the borderWidth property values for UI Button:

  btnUserButtonName.layer.borderWidth = 1.0

Set Title with Default Color values for UI Button:

btnUserButtonName.setTitleColor(UIColor.darkGray, for: .normal)

Set Border with Default Color for the border property values for UI Button:

btnUserButtonName.layer.borderColor = UIColor.red

Set user defined Color for the border property values for UI Button:

   let myGrayColor = UIColor(red: 0.889415, green: 0.889436, blue:0.889424, alpha: 1.0 )
   btnUserButtonName.layer.borderColor = myGrayColor.cgColor

Option 2: [Recommended]

Use the Extension method, so the Button through out the application will be looking consistent and no need to repeat multiple lines of code every where.

//Create an extension class in any of the swift file

extension UIButton {
func setBordersSettings() {
        let c1GreenColor = (UIColor(red: -0.108958, green: 0.714926, blue: 0.758113, alpha: 1.0))
        self.layer.borderWidth = 1.0
        self.layer.cornerRadius = 5.0
        self.layer.borderColor = c1GreenColor.cgColor
        self.setTitleColor(c1GreenColor, for: .normal)
        self.layer.masksToBounds = true
    }
}

Usage in code:

//use the method and call whever the border has to be applied

btnUserButtonName.setBordersSettings()

Output of Extension method Button:

enter image description here

Java switch statement: Constant expression required, but it IS constant

I got this error on Android, and my solution was just to use:

public static final int TAKE_PICTURE = 1;

instead of

public static int TAKE_PICTURE = 1;

What is the difference between dynamic and static polymorphism in Java?

Method Overloading is known as Static Polymorphism and also Known as Compile Time Polymorphism or Static Binding because overloaded method calls get resolved at compile time by the compiler on the basis of the argument list and the reference on which we are calling the method.

And Method Overriding is known as Dynamic Polymorphism or simple Polymorphism or Runtime Method Dispatch or Dynamic Binding because overridden method call get resolved at runtime.

In order to understand why this is so let's take an example of Mammal and Human class

class Mammal {
    public void speak() { System.out.println("ohlllalalalalalaoaoaoa"); }
}

class Human extends Mammal {

    @Override
    public void speak() { System.out.println("Hello"); }

    public void speak(String language) {
        if (language.equals("Hindi")) System.out.println("Namaste");
        else System.out.println("Hello");
    }

}

I have included output as well as bytecode of in below lines of code

Mammal anyMammal = new Mammal();
anyMammal.speak();  // Output - ohlllalalalalalaoaoaoa
// 10: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V

Mammal humanMammal = new Human();
humanMammal.speak(); // Output - Hello
// 23: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V

Human human = new Human();
human.speak(); // Output - Hello
// 36: invokevirtual #7 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:()V

human.speak("Hindi"); // Output - Namaste
// 42: invokevirtual #9 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:(Ljava/lang/String;)V

And by looking at above code we can see that the bytecodes of humanMammal.speak() , human.speak() and human.speak("Hindi") are totally different because the compiler is able to differentiate between them based on the argument list and class reference. And this is why Method Overloading is known as Static Polymorphism.

But bytecode for anyMammal.speak() and humanMammal.speak() is same because according to compiler both methods are called on Mammal reference but the output for both method calls is different because at runtime JVM knows what object a reference is holding and JVM calls the method on the object and this is why Method Overriding is known as Dynamic Polymorphism.

So from above code and bytecode, it is clear that during compilation phase calling method is considered from the reference type. But at execution time method will be called from the object which the reference is holding.

If you want to know more about this you can read more on How Does JVM Handle Method Overloading and Overriding Internally.

php - push array into array - key issue

Use this..

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
    $res_arr_values[] = $row;
}

Strangest language feature

In J, most primitives (a.k.a. functions) are monadic (one argument) or dyadic (two arguments, one to the left, one to the right). But the amend primitive takes 3 (I think it's the only one, besides foreigns). It's understandable that it would take 3, but it just looks... wrong at first.

vector =: i. 10   NB. Vector will be 0 1 2 3 4 5 6 7 8 9
(10) (0) } vector NB. Will yield 10 1 2 3 4 5 6 7 8 9

move column in pandas dataframe

This function will reorder your columns without losing data. Any omitted columns remain in the center of the data set:

def reorder_columns(columns, first_cols=[], last_cols=[], drop_cols=[]):
    columns = list(set(columns) - set(first_cols))
    columns = list(set(columns) - set(drop_cols))
    columns = list(set(columns) - set(last_cols))
    new_order = first_cols + columns + last_cols
    return new_order

Example usage:

my_list = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']
reorder_columns(my_list, first_cols=['fourth', 'third'], last_cols=['second'], drop_cols=['fifth'])

# Output:
['fourth', 'third', 'first', 'sixth', 'second']

To assign to your dataframe, use:

my_list = df.columns.tolist()
reordered_cols = reorder_columns(my_list, first_cols=['fourth', 'third'], last_cols=['second'], drop_cols=['fifth'])
df = df[reordered_cols]

Why es6 react component works only with "export default"?

Exporting without default means it's a "named export". You can have multiple named exports in a single file. So if you do this,

class Template {}
class AnotherTemplate {}

export { Template, AnotherTemplate }

then you have to import these exports using their exact names. So to use these components in another file you'd have to do,

import {Template, AnotherTemplate} from './components/templates'

Alternatively if you export as the default export like this,

export default class Template {}

Then in another file you import the default export without using the {}, like this,

import Template from './components/templates'

There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.

You're free to rename the default export as you import it,

import TheTemplate from './components/templates'

And you can import default and named exports at the same time,

import Template,{AnotherTemplate} from './components/templates'

ModuleNotFoundError: No module named 'sklearn'

If you are using Ubuntu 18.04 or higher with python3.xxx then try this command

$ sudo apt install python3-sklearn 

then try your command. hope it will work

Add a tooltip to a div

It can be done with CSS only, no javascript at all : running demo

  1. Apply a custom HTML attribute, eg. data-tooltip="bla bla" to your object (div or whatever):

    <div data-tooltip="bla bla">
        something here
    </div>
    
  2. Define the :before pseudoelement of each [data-tooltip] object to be transparent, absolutely positioned and with data-tooltip="" value as content:

    [data-tooltip]:before {            
        position : absolute;
         content : attr(data-tooltip);
         opacity : 0;
    }
    
  3. Define :hover:before hovering state of each [data-tooltip] to make it visible:

    [data-tooltip]:hover:before {        
        opacity : 1;
    }
    
  4. Apply your styles (color, size, position etc) to the tooltip object; end of the story.

In the demo I've defined another rule to specify if the tooltip must disappear when hovering over it but outside of the parent, with another custom attribute, data-tooltip-persistent, and a simple rule:

[data-tooltip]:not([data-tooltip-persistent]):before {
    pointer-events: none;
}

Note 1: The browser coverage for this is very wide, but consider using a javascript fallback (if needed) for old IE.

Note 2: an enhancement might be adding a bit of javascript to calculate the mouse position and add it to the pseudo elements, by changing a class applied to it.

How to top, left justify text in a <td> cell that spans multiple rows

 <td rowspan="2" style="text-align:left;vertical-align:top;padding:0">Save a lot</td>

That should do it.

failed to open stream: HTTP wrapper does not support writeable connections

Instead of doing file_put_contents(***WebSiteURL***...) you need to use the server path to /cache/lang/file.php (e.g. /home/content/site/folders/filename.php).

You cannot open a file over HTTP and expect it to be written. Instead you need to open it using the local path.

How to change workspace and build record Root Directory on Jenkins?

EDIT: Per other comments, the "Advanced..." button appears to have been removed in more recent versions of Jenkins. If your version doesn't have it, see knorx's answer.

I had the same problem, and even after finding this old pull request I still had trouble finding where to specify the Workspace Root Directory or Build Record Root Directory at the system level, versus specifying a custom workspace for each job.

To set these:

  1. Navigate to Jenkins -> Manage Jenkins -> Configure System
  2. Right at the top, under Home directory, click the Advanced... button: advanced button under Home directory
  3. Now the fields for Workspace Root Directory and Build Record Root Directory appear: additional directory options
  4. The information that appears if you click the help bubbles to the left of each option is very instructive. In particular (from the Workspace Root Directory help):

    This value may include the following variables:

    • ${JENKINS_HOME} — Absolute path of the Jenkins home directory
    • ${ITEM_ROOTDIR} — Absolute path of the directory where Jenkins stores the configuration and related metadata for a given job
    • ${ITEM_FULL_NAME} — The full name of a given job, which may be slash-separated, e.g. foo/bar for the job bar in folder foo


    The value should normally include ${ITEM_ROOTDIR} or ${ITEM_FULL_NAME}, otherwise different jobs will end up sharing the same workspace.

Vue js error: Component template should contain exactly one root element

Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.

The right approach is

<template>
  <div> <!-- The root -->
    <p></p> 
    <p></p>
  </div>
</template>

The wrong approach

<template> <!-- No root Element -->
    <p></p> 
    <p></p>
</template>

Multi Root Components

The way around to that problem is using functional components, they are components where you have to pass no reactive data means component will not be watching for any data changes as well as not updating it self when something in parent component changes.

As this is a work around it comes with a price, functional components don't have any life cycle hooks passed to it, they are instance less as well you cannot refer to this anymore and everything is passed with context.

Here is how you can create a simple functional component.

Vue.component('my-component', {
    // you must set functional as true
  functional: true,
  // Props are optional
  props: {
    // ...
  },
  // To compensate for the lack of an instance,
  // we are now provided a 2nd context argument.
  render: function (createElement, context) {
    // ...
  }
})

Now that we have covered functional components in some detail lets cover how to create multi root components, for that I am gonna present you with a generic example.

<template>
 <ul>
     <NavBarRoutes :routes="persistentNavRoutes"/>
     <NavBarRoutes v-if="loggedIn" :routes="loggedInNavRoutes" />
     <NavBarRoutes v-else :routes="loggedOutNavRoutes" />
 </ul>
</template>

Now if we take a look at NavBarRoutes template

<template>
 <li
 v-for="route in routes"
 :key="route.name"
 >
 <router-link :to="route">
 {{ route.title }}
 </router-link>
 </li>
</template>

We cant do some thing like this we will be violating single root component restriction

Solution Make this component functional and use render

{
functional: true,
render(h, { props }) {
 return props.routes.map(route =>
  <li key={route.name}>
    <router-link to={route}>
      {route.title}
    </router-link>
  </li>
 )
}

Here you have it you have created a multi root component, Happy coding

Reference for more details visit: https://blog.carbonteq.com/vuejs-create-multi-root-components/

Is there an XSLT name-of element?

<xsl:for-each select="person">
  <xsl:for-each select="*">
    <xsl:value-of select="local-name()"/> : <xsl:value-of select="."/>
  </xsl:for-each>  
</xsl:for-each>

Can't push image to Amazon ECR - fails with "no basic auth credentials"

I was facing the same issue and fixed it with this command. It works for me, please update it as per your account. This is for Ubuntu machine where AWS-CLI needs to be installed with Docker

algorithm_name='multi-model-xgboost'

account=$(aws sts get-caller-identity --query Account --output text)

# Get the region defined in the current configuration
region=$(aws configure get region)

aws ecr get-login-password --region ${region} | docker login --username AWS --password-stdin ${account}.dkr.ecr.${region}.amazonaws.com/${algorithm_name}

Can I add background color only for padding?

Use the background-clip and box-shadow properties.

1) Set background-clip: content-box - this restricts the background only to the content itself (instead of covering both the padding and border)

2) Add an inner box-shadow with the spread radius set to the same value as the padding.

So say the padding is 10px - set box-shadow: inset 0 0 0 10px lightGreen - which will make only the padding area light green.

Codepen demo

_x000D_
_x000D_
nav {_x000D_
  width: 80%;_x000D_
  height: 50px;_x000D_
  background-color: gray;_x000D_
  float: left;_x000D_
  padding: 10px; /* 10px padding */_x000D_
  border: 2px solid red;_x000D_
  background-clip: content-box; /* <---- */_x000D_
  box-shadow: inset 0 0 0 10px lightGreen; /* <-- 10px spread radius */_x000D_
}_x000D_
ul {_x000D_
  list-style: none;_x000D_
}_x000D_
li {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<h2>The light green background color shows the padding of the element</h2>_x000D_
<nav>_x000D_
  <ul>_x000D_
    <li><a href="index.html">Home</a>_x000D_
    </li>_x000D_
    <li><a href="/about/">About</a>_x000D_
    </li>_x000D_
    <li><a href="/blog/">Blog</a>_x000D_
    </li>_x000D_
  </ul>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

For a thorough tutorial covering this technique see this great css-tricks post

pip issue installing almost any library

I had this with PyCharm and upgrading pip to 10.0.1 broke pip with "'main' not found in module" error.

I could solve this problem by installing pip 9.0.3 as seen in some other thread. These are the steps I did:

  1. Downloaded 9.0.3 version of pip from https://pypi.org/simple/pip/ (since pip couldn't be used to install it).
  2. Install pip 9.0.3 from tar.gz python -m pip install pip-9.0.3.tar.gz

Everything started to work after that.

How to print number with commas as thousands separators?

The accepted answer is fine, but I actually prefer format(number,','). Easier for me to interpret and remember.

https://docs.python.org/3/library/functions.html#format

Javascript onHover event

I don't think you need/want the timeout.

onhover (hover) would be defined as the time period while "over" something. IMHO

onmouseover = start...

onmouseout = ...end

For the record I've done some stuff with this to "fake" the hover event in IE6. It was rather expensive and in the end I ditched it in favor of performance.

Tuning nginx worker_process to obtain 100k hits per min

Config file:

worker_processes  4;  # 2 * Number of CPUs

events {
    worker_connections  19000;  # It's the key to high performance - have a lot of connections available
}

worker_rlimit_nofile    20000;  # Each connection needs a filehandle (or 2 if you are proxying)


# Total amount of users you can serve = worker_processes * worker_connections

more info: Optimizing nginx for high traffic loads

Change default date time format on a single database in SQL Server

You could use SET DATEFORMAT, like in this example

declare @dates table (orig varchar(50) ,parsed datetime)

SET DATEFORMAT ydm;

insert into @dates
select '2008-09-01','2008-09-01'

SET DATEFORMAT ymd;
insert into @dates
select '2008-09-01','2008-09-01'

select * from @dates

You would need to specify the dateformat in the code when you parse your XML data

What's the difference between commit() and apply() in SharedPreferences

The docs give a pretty good explanation of the difference between apply() and commit():

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself. As SharedPreferences instances are singletons within a process, it's safe to replace any instance of commit() with apply() if you were already ignoring the return value.

What is a regex to match ONLY an empty string?

I would use a negative lookahead for any character:

^(?![\s\S])

This can only match if the input is totally empty, because the character class will match any character, including any of the various newline characters.

Determine which element the mouse pointer is on top of in JavaScript

The following code will help you to get the element of the mouse pointer. The resulted elements will display in the console.

document.addEventListener('mousemove', function(e) {
    console.log(document.elementFromPoint(e.pageX, e.pageY)); 
})

Visual Studio breakpoints not being hit

I struggled forever trying to fix this. Finally this is what did it for me.

Select Debug->Options->Debugging->General

Tick Enable .NET Framework source stepping.

(This may be all you need to do but if you are like me, you also have to do the ones stated below. The below solution will also fix errors where your project is loading old assemblies/.pdb files despite rebuilding and cleaning.)

Select Tools -> Options -> Projects and Solutions -> Build and Run,

Untick the checkbox of "Only Build startup projects and dependencies on Run",

Select Always Build from the "On Run, when project are out of date" dropdown.

How to override the properties of a CSS class using another CSS class

If you list the bakground-none class after the other classes, its properties will override those already set. There is no need to use !important here.

For example:

.red { background-color: red; }
.background-none { background: none; }

and

<a class="red background-none" href="#carousel">...</a>

The link will not have a red background. Please note that this only overrides properties that have a selector that is less or equally specific.

Mockito verify order / sequence of method calls

InOrder helps you to do that.

ServiceClassA firstMock = mock(ServiceClassA.class);
ServiceClassB secondMock = mock(ServiceClassB.class);

Mockito.doNothing().when(firstMock).methodOne();   
Mockito.doNothing().when(secondMock).methodTwo();  

//create inOrder object passing any mocks that need to be verified in order
InOrder inOrder = inOrder(firstMock, secondMock);

//following will make sure that firstMock was called before secondMock
inOrder.verify(firstMock).methodOne();
inOrder.verify(secondMock).methodTwo();

How to call a function from another controller in angularjs?

The best approach for you to communicate between the two controllers is to use events.

See the scope documentation

In this check out $on, $broadcast and $emit.

What are the different types of indexes, what are the benefits of each?

  • Unique - Guarantees unique values for the column(or set of columns) included in the index
  • Covering - Includes all of the columns that are used in a particular query (or set of queries), allowing the database to use only the index and not actually have to look at the table data to retrieve the results
  • Clustered - This is way in which the actual data is ordered on the disk, which means if a query uses the clustered index for looking up the values, it does not have to take the additional step of looking up the actual table row for any data not included in the index.

Responsive iframe using Bootstrap

Option 1

With Bootstrap 3.2 you can wrap each iframe in the responsive-embed wrapper of your choice:

http://getbootstrap.com/components/#responsive-embed

<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="…"></iframe>
</div>

<!-- 4:3 aspect ratio -->
<div class="embed-responsive embed-responsive-4by3">
  <iframe class="embed-responsive-item" src="…"></iframe>
</div>

Option 2

If you don't want to wrap your iframes, you can use FluidVids https://github.com/toddmotto/fluidvids. See demo here: http://toddmotto.com/labs/fluidvids/

   <!-- fluidvids.js -->
    <script src="js/fluidvids.js"></script>
    <script>
    fluidvids.init({
      selector: ['iframe'],
      players: ['www.youtube.com', 'player.vimeo.com']
    });
    </script>

Making HTML page zoom by default

A better solution is not to make your page dependable on zoom settings. If you set limits like the one you are proposing, you are limiting accessibility. If someone cannot read your text well, they just won't be able to change that. I would use proper CSS to make it look nice in any zoom.

If your really insist, take a look at this question on how to detect zoom level using JavaScript (nightmare!): How to detect page zoom level in all modern browsers?

Best practice to run Linux service as a different user

  • Some daemons (e.g. apache) do this by themselves by calling setuid()
  • You could use the setuid-file flag to run the process as a different user.
  • Of course, the solution you mentioned works as well.

If you intend to write your own daemon, then I recommend calling setuid(). This way, your process can

  1. Make use of its root privileges (e.g. open log files, create pid files).
  2. Drop its root privileges at a certain point during startup.

How to load local html file into UIWebView

Here the way the working of HTML file with Jquery.

 _webview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 568)];
    [self.view addSubview:_webview];

    NSString *filePath=[[NSBundle mainBundle]pathForResource:@"jquery" ofType:@"html" inDirectory:nil];

    NSLog(@"%@",filePath);
    NSString *htmlstring=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

    [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
                         or
    [_webview loadHTMLString:htmlstring baseURL:nil];

You can use either the requests to call the HTML file in your UIWebview

xsd:boolean element type accept "true" but not "True". How can I make it accept it?

You cannot.

According to the XML Schema specification, a boolean is true or false. True is not valid:


  3.2.2.1 Lexical representation
  An instance of a datatype that is defined as ·boolean· can have the 
  following legal literals {true, false, 1, 0}. 

  3.2.2.2 Canonical representation
  The canonical representation for boolean is the set of 
  literals {true, false}. 

If the tool you are using truly validates against the XML Schema standard, then you cannot convince it to accept True for a boolean.

JS strings "+" vs concat method

In JS, "+" concatenation works by creating a new String object.

For example, with...

var s = "Hello";

...we have one object s.

Next:

s = s + " World";

Now, s is a new object.

2nd method: String.prototype.concat

How to force input to only allow Alpha Letters?

Short ONELINER:

_x000D_
_x000D_
<input onkeypress="return /[a-z]/i.test(event.key)" >
_x000D_
_x000D_
_x000D_

For all unicode letters try this regexp: /\p{L}/u (but ... this) - and here is working example :)

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

from Jackson 2.7.x+ there is a way to annotate the member variable itself:

 @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
 private List<String> newsletters;

More info here: Jackson @JsonFormat

Python - Convert a bytes array into JSON format

Python 3.5 + Use io module

import json
import io

my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'

fix_bytes_value = my_bytes_value.replace(b"'", b'"')

my_json = json.load(io.BytesIO(fix_bytes_value))  

Git pull after forced update

This won't fix branches that already have the code you don't want in them (see below for how to do that), but if they had pulled some-branch and now want it to be clean (and not "ahead" of origin/some-branch) then you simply:

git checkout some-branch   # where some-branch can be replaced by any other branch
git branch base-branch -D  # where base-branch is the one with the squashed commits
git checkout -b base-branch origin/base-branch  # recreating branch with correct commits

Note: You can combine these all by putting && between them

Note2: Florian mentioned this in a comment, but who reads comments when looking for answers?

Note3: If you have contaminated branches, you can create new ones based off the new "dumb branch" and just cherry-pick commits over.

Ex:

git checkout feature-old  # some branch with the extra commits
git log                   # gives commits (write down the id of the ones you want)
git checkout base-branch  # after you have already cleaned your local copy of it as above
git checkout -b feature-new # make a new branch for your feature
git cherry-pick asdfasd   # where asdfasd is one of the commit ids you want
# repeat previous step for each commit id
git branch feature-old -D # delete the old branch

Now feature-new is your branch without the extra (possibly bad) commits!

How to return multiple values in one column (T-SQL)?

Sorry, read the question wrong the first time. You can do something like this:

declare @result varchar(max)

--must "initialize" result for this to work
select @result = ''

select @result = @result + alias
FROM aliases
WHERE username='Bob'

How do I connect to a SQL Server 2008 database using JDBC?

Simple Java Program which connects to the SQL Server.

NOTE: You need to add sqljdbc.jar into the build path

// localhost : local computer acts as a server

// 1433 : SQL default port number

// username : sa

// password: use password, which is used at the time of installing SQL server management studio, In my case, it is 'root'

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

    public class Conn {
        public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {

            Connection conn=null;
            try {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
                conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=company", "sa", "root");

                if(conn!=null)
                    System.out.println("Database Successfully connected");

            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }

How to use ArrayAdapter<myClass>

Subclass the ArrayAdapter and override the method getView() to return your own view that contains the contents that you want to display.

AWS EFS vs EBS vs S3 (differences & when to use?)

AWS EFS, EBS and S3. From Functional Standpoint, here is the difference

EFS:

  1. Network filesystem :can be shared across several Servers; even between regions. The same is not available for EBS case. This can be used esp for storing the ETL programs without the risk of security

  2. Highly available, scalable service.

  3. Running any application that has a high workload, requires scalable storage, and must produce output quickly.

  4. It can provide higher throughput. It match sudden file system growth, even for workloads up to 500,000 IOPS or 10 GB per second.

  5. Lift-and-shift application support: EFS is elastic, available, and scalable, and enables you to move enterprise applications easily and quickly without needing to re-architect them.

  6. Analytics for big data: It has the ability to run big data applications, which demand significant node throughput, low-latency file access, and read-after-write operations.

EBS:

  1. for NoSQL databases, EBS offers NoSQL databases the low-latency performance and dependability they need for peak performance.

S3:

Robust performance, scalability, and availability: Amazon S3 scales storage resources free from resource procurement cycles or investments upfront.

2)Data lake and big data analytics: Create a data lake to hold raw data in its native format, then using machine learning tools, analytics to draw insights.

  1. Backup and restoration: Secure, robust backup and restoration solutions
  2. Data archiving
  3. S3 is an object store good at storing vast numbers of backups or user files. Unlike EBS or EFS, S3 is not limited to EC2. Files stored within an S3 bucket can be accessed programmatically or directly from services such as AWS CloudFront. Many websites use it to hold their content and media files, which may be served efficiently via AWS CloudFront.

Using sudo with Python script

  • Use -S option in the sudo command which tells to read the password from 'stdin' instead of the terminal device.

  • Tell Popen to read stdin from PIPE.

  • Send the Password to the stdin PIPE of the process by using it as an argument to communicate method. Do not forget to add a new line character, '\n', at the end of the password.

sp = Popen(cmd , shell=True, stdin=PIPE)
out, err = sp.communicate(_user_pass+'\n')   

"break;" out of "if" statement?

As already mentioned that, break-statement works only with switches and loops. Here is another way to achieve what is being asked. I am reproducing https://stackoverflow.com/a/257421/1188057 as nobody else mentioned it. It's just a trick involving the do-while loop.

do {
  // do something
  if (error) {
    break;
  }
  // do something else
  if (error) {
    break;
  }
  // etc..
} while (0);

Though I would prefer the use of goto-statement.

iOS: set font size of UILabel Programmatically

If you are looking for swift code:

var titleLabel = UILabel()
titleLabel.font = UIFont(name: "HelveticaNeue-UltraLight",
                         size: 20.0)

Arduino IDE can't find ESP8266WiFi.h file

For those who are having trouble with fatal error: ESP8266WiFi.h: No such file or directory, you can install the package manually.

  1. Download the Arduino ESP8266 core from here https://github.com/esp8266/Arduino
  2. Go into library from the downloaded core and grab ESP8266WiFi.
  3. Drag that into your local Arduino/library folder. This can be found by going into preferences and looking at your Sketchbook location

You may still need to have the http://arduino.esp8266.com/stable/package_esp8266com_index.json package installed beforehand, however.

Edit: That wasn't the full issue, you need to make sure you have the correct ESP8266 Board selected before compiling.

Hope this helps others.

How to produce an csv output file from stored procedure in SQL Server

Just to answer a native way to do this that finally worked, everything had to be casted as a varchar

ALTER PROCEDURE [clickpay].[sp_GetDocuments] 

@Submid bigint

AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
   DECLARE @raw_sql varchar(max)

DECLARE @columnHeader VARCHAR(max)
SELECT @columnHeader = COALESCE(@columnHeader+',' ,'')+ ''''+column_name +'''' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documents'

DECLARE @ColumnList VARCHAR(max)
SELECT @ColumnList = COALESCE(@ColumnList+',' ,'')+ 'CAST('+column_name +' AS VARCHAR)' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documents'

SELECT @raw_sql = 'SELECT '+ @columnHeader +' UNION ALL SELECT ' + @ColumnList + ' FROM ' + 'Documents where Submid = ' +  CAST(@Submid AS VARCHAR)

-- Insert statements for procedure here
exec(@raw_sql)
END

msvcr110.dll is missing from computer error while installing PHP

I was missing the MSVCR110.dll. Which I corrected. I could run php from the command line but not the web server. Then I clicked on php-cgi.exe and it gave me the answer. The php5.dll was missing (I downloaded the wrong copy). So for my 2012 IIS box I re-installed using php's x86 non thread safe zip.

&& (AND) and || (OR) in IF statements

No, it will not be evaluated. And this is very useful. For example, if you need to test whether a String is not null or empty, you can write:

if (str != null && !str.isEmpty()) {
  doSomethingWith(str.charAt(0));
}

or, the other way around

if (str == null || str.isEmpty()) {
  complainAboutUnusableString();
} else {
  doSomethingWith(str.charAt(0));
}

If we didn't have 'short-circuits' in Java, we'd receive a lot of NullPointerExceptions in the above lines of code.

How to add a named sheet at the end of all Excel sheets?

ThisWorkbook.Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "XYZ"

(when you add a worksheet, anyway it'll be the active sheet)

Do the parentheses after the type name make a difference with new?

new Thing(); is explicit that you want a constructor called whereas new Thing; is taken to imply you don't mind if the constructor isn't called.

If used on a struct/class with a user-defined constructor, there is no difference. If called on a trivial struct/class (e.g. struct Thing { int i; };) then new Thing; is like malloc(sizeof(Thing)); whereas new Thing(); is like calloc(sizeof(Thing)); - it gets zero initialized.

The gotcha lies in-between:

struct Thingy {
  ~Thingy(); // No-longer a trivial class
  virtual WaxOn();
  int i;
};

The behavior of new Thingy; vs new Thingy(); in this case changed between C++98 and C++2003. See Michael Burr's explanation for how and why.

Is it possible to deserialize XML into List<T>?

I think I have found a better way. You don't have to put attributes into your classes. I've made two methods for serialization and deserialization which take generic list as parameter.

Take a look (it works for me):

private void SerializeParams<T>(XDocument doc, List<T> paramList)
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(paramList.GetType());

        System.Xml.XmlWriter writer = doc.CreateWriter();

        serializer.Serialize(writer, paramList);

        writer.Close();           
    }

private List<T> DeserializeParams<T>(XDocument doc)
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<T>));

        System.Xml.XmlReader reader = doc.CreateReader();

        List<T> result = (List<T>)serializer.Deserialize(reader);
        reader.Close();

        return result;
    }

So you can serialize whatever list you want! You don't need to specify the list type every time.

        List<AssemblyBO> list = new List<AssemblyBO>();
        list.Add(new AssemblyBO());
        list.Add(new AssemblyBO() { DisplayName = "Try", Identifier = "243242" });
        XDocument doc = new XDocument();
        SerializeParams<T>(doc, list);
        List<AssemblyBO> newList = DeserializeParams<AssemblyBO>(doc);

How can I get the username of the logged-in user in Django?

For classed based views use self.request.user.id

How to have Android Service communicate with Activity

Another way could be using observers with a fake model class through the activity and the service itself, implementing an MVC pattern variation. I don't know if it's the best way to accomplish this, but it's the way that worked for me. If you need some example ask for it and i'll post something.

php get values from json encode

json_decode will return the same array that was originally encoded. For instanse, if you

$array = json_decode($json, true);
echo $array['countryId'];

OR

$obj= json_decode($json);

echo $obj->countryId;

These both will echo 84. I think json_encode and json_decode function names are self-explanatory...

Difference between Inheritance and Composition

No , Both are different . Composition follow "HAS-A" relationship and inheritance follow "IS-A" relationship . Best Example for composition was Strategic pattern .

Are iframes considered 'bad practice'?

As with all technologies, it has its ups and downs. If you are using an iframe to get around a properly developed site, then of course it is bad practice. However sometimes an iframe is acceptable.

One of the main problems with an iframe has to do with bookmarks and navigation. If you are using it to simply embed a page inside your content, I think that is fine. That is what an iframe is for.

However I've seen iframes abused as well. It should never be used as an integral part of your site, but as a piece of content within a site.

Usually, if you can do it without an iframe, that is a better option. I'm sure others here may have more information or more specific examples, it all comes down to the problem you are trying to solve.

With that said, if you are limited to HTML and have no access to a backend like PHP or ASP.NET etc, sometimes an iframe is your only option.

Using Mockito to mock classes with generic parameters

With JUnit5 I think the best way is to @ExtendWith(MockitoExtension.class) with @Mock in the method parameter or the field.

The following example demonstrates that with Hamcrest matchers.

package com.vogella.junit5;                                                                    
                                                                                               
import static org.hamcrest.MatcherAssert.assertThat;                                           
import static org.hamcrest.Matchers.hasItem;                                                   
import static org.mockito.Mockito.verify;                                                      
                                                                                               
import java.util.Arrays;                                                                       
import java.util.List;                                                                         
                                                                                               
import org.junit.jupiter.api.Test;                                                             
import org.junit.jupiter.api.extension.ExtendWith;                                             
import org.mockito.ArgumentCaptor;                                                             
import org.mockito.Captor;                                                                     
import org.mockito.Mock;                                                                       
import org.mockito.junit.jupiter.MockitoExtension;                                             
                                                                                               
@ExtendWith(MockitoExtension.class)                                                            
public class MockitoArgumentCaptureTest {                                                      
                                                                                               
                                                                                               
    @Captor                                                                                    
    private ArgumentCaptor<List<String>> captor;                                               
                                                                                               
    @Test                                                                                      
    public final void shouldContainCertainListItem(@Mock List<String> mockedList) {            
        var asList = Arrays.asList("someElement_test", "someElement");                         
        mockedList.addAll(asList);                                                             
                                                                                               
        verify(mockedList).addAll(captor.capture());                                           
        List<String> capturedArgument = captor.getValue();                                     
        assertThat(capturedArgument, hasItem("someElement"));                                  
    }                                                                                          
}                                                                                              
                                                                                              

See https://www.vogella.com/tutorials/Mockito/article.html for the required Maven/Gradle dependencies.

Adding Image to xCode by dragging it from File

You can't add image from desktop to UIimageView, you only can add image (dragging) into project folders and then select the name image into UIimageView properties (inspector).

Tutorial on how to do that: http://conecode.com/news/2011/06/ios-tutorial-creating-an-image-view-uiimageview/

In SQL Server, what does "SET ANSI_NULLS ON" mean?

If ANSI_NULLS is set to "ON" and if we apply = , <> on NULL column value while writing select statement then it will not return any result.

Example

create table #tempTable (sn int, ename varchar(50))

insert into #tempTable
values (1, 'Manoj'), (2, 'Pankaj'), (3, NULL), (4, 'Lokesh'), (5, 'Gopal')

SET ANSI_NULLS ON

select * from #tempTable where ename is NULL -- (1 row(s) affected)
select * from #tempTable where ename = NULL -- (0 row(s) affected)
select * from #tempTable where ename is not NULL -- (4 row(s) affected)
select * from #tempTable where ename <> NULL -- (0 row(s) affected)

SET ANSI_NULLS OFF

select * from #tempTable where ename is NULL -- (1 row(s) affected)
select * from #tempTable where ename = NULL -- (1 row(s) affected)
select * from #tempTable where ename is not NULL -- (4 row(s) affected)
select * from #tempTable where ename <> NULL -- (4 row(s) affected)

Execute Shell Script after post build in Jenkins

You can also run arbitrary commands using the Groovy Post Build - and that will give you a lot of control over when they run and so forth. We use that to run a 'finger of blame' shell script in the case of failed or unstable builds.

if (manager.build.result.isWorseThan(hudson.model.Result.SUCCESS)) {
  item = hudson.model.Hudson.instance.getItem("PROJECTNAMEHERE")
  lastStableBuild = item.getLastStableBuild()
  lastStableDate = lastStableBuild.getTime()
  formattedLastStableDate = lastStableDate.format("MM/dd/yyyy h:mm:ss a")
  now = new Date()
  formattedNow = now.format("MM/dd/yyyy h:mm:ss a")
  command = ['/appframe/jenkins/appframework/fob.ksh', "${formattedLastStableDate}", "${formattedNow}"]
  manager.listener.logger.println "FOB Command: ${command}"
  manager.listener.logger.println command.execute().text
}

(Our command takes the last stable build date and the current time as parameters so it can go investigate who might have broken the build, but you could run whatever commands you like in a similar fashion)

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

This should do it using built in functions.

public static int minIndex (ArrayList<Float> list) {
  return list.indexOf (Collections.min(list)); }

Temporary table in SQL server causing ' There is already an object named' error

In Azure Data warehouse also this occurs sometimes, because temporary tables created for a user session.. I got the same issue fixed by reconnecting the database,

How to check whether a file is empty or not?

Both getsize() and stat() will throw an exception if the file does not exist. This function will return True/False without throwing (simpler but less robust):

import os
def is_non_zero_file(fpath):  
    return os.path.isfile(fpath) and os.path.getsize(fpath) > 0

jQuery DIV click, with anchors

<div class="info">
   <h2>Takvim</h2>
   <a href="item-list.php"> Click Me !</a>
</div>


$(document).delegate("div.info", "click", function() {
   window.location = $(this).find("a").attr("href");
});

Using media breakpoints in Bootstrap 4-alpha

Bootstrap has a way of using media queries to define the different task for different sites. It uses four breakpoints.

we have extra small screen sizes which are less than 576 pixels that small in which I mean it's size from 576 to 768 pixels.

medium screen sizes take up screen size from 768 pixels up to 992 pixels large screen size from 992 pixels up to 1200 pixels.

E.g Small Text

This means that at the small screen between 576px and 768px, center the text For medium screen, change "sm" to "md" and same goes to large "lg"

Using grep to search for hex strings in a file

This seems to work for me:

LANG=C grep --only-matching --byte-offset --binary --text --perl-regexp "<\x-hex pattern>" <file>

short form:

LANG=C grep -obUaP "<\x-hex pattern>" <file>

Example:

LANG=C grep -obUaP "\x01\x02" /bin/grep

Output (cygwin binary):

153: <\x01\x02>
33210: <\x01\x02>
53453: <\x01\x02>

So you can grep this again to extract offsets. But don't forget to use binary mode again.

Note: LANG=C is needed to avoid utf8 encoding issues.

SVN: Folder already under version control but not comitting?

I had a similar-looking problem after adding a directory tree which contained .svn directories (because it was an svn:external in its source environment): svn status told me "?", but when trying to add it, it was "already under version control".

Since no other versioned directories were present, I did

find . -mindepth 2 -name '.svn' -exec rm -rf '{}' \;

to remove the wrong .svn directories; after doing this, I was able to add the new directory.

Note:

  • If other versioned directories are contained, the find expression must be changed to be more specific
  • If unsure, first omit the "-exec ..." part to see what would be deleted

Using Jasmine to spy on a function without an object

My answer differs slightly to @FlavorScape in that I had a single (default export) function in the imported module, I did the following:

import * as functionToTest from 'whatever-lib';

const fooSpy = spyOn(functionToTest, 'default');

append to url and refresh page

location.href = location.href + "&parameter=" + value;

Calling C++ class methods via a function pointer

To create a new object you can either use placement new, as mentioned above, or have your class implement a clone() method that creates a copy of the object. You can then call this clone method using a member function pointer as explained above to create new instances of the object. The advantage of clone is that sometimes you may be working with a pointer to a base class where you don't know the type of the object. In this case a clone() method can be easier to use. Also, clone() will let you copy the state of the object if that is what you want.

The following artifacts could not be resolved: javax.jms:jms:jar:1.1

May not be the exactly same problem. but there is a nice article on the same line Here

Find object in list that has attribute equal to some value (that meets any condition)

Since it has not been mentioned just for completion. The good ol' filter to filter your to be filtered elements.

Functional programming ftw.

####### Set Up #######
class X:

    def __init__(self, val):
        self.val = val

elem = 5

my_unfiltered_list = [X(1), X(2), X(3), X(4), X(5), X(5), X(6)]

####### Set Up #######

### Filter one liner ### filter(lambda x: condition(x), some_list)
my_filter_iter = filter(lambda x: x.val == elem, my_unfiltered_list)
### Returns a flippin' iterator at least in Python 3.5 and that's what I'm on

print(next(my_filter_iter).val)
print(next(my_filter_iter).val)
print(next(my_filter_iter).val)

### [1, 2, 3, 4, 5, 5, 6] Will Return: ###
# 5
# 5
# Traceback (most recent call last):
#   File "C:\Users\mousavin\workspace\Scripts\test.py", line 22, in <module>
#     print(next(my_filter_iter).value)
# StopIteration


# You can do that None stuff or whatever at this point, if you don't like exceptions.

I know that generally in python list comprehensions are preferred or at least that is what I read, but I don't see the issue to be honest. Of course Python is not an FP language, but Map / Reduce / Filter are perfectly readable and are the most standard of standard use cases in functional programming.

So there you go. Know thy functional programming.

filter condition list

It won't get any easier than this:

next(filter(lambda x: x.val == value,  my_unfiltered_list)) # Optionally: next(..., None) or some other default value to prevent Exceptions