Programs & Examples On #Appcelerator

Use this tag for programming or development questions related to the Appcelerator Platform for developing Native Mobile Apps and APIs using JavaScript. Please use Appcelerator-specific tags such as [appcelerator-titanium], not [titanium].

Could not load NIB in bundle

try to find out all

XXXController = [[XXXControlloer alloc] initWithNibName:@"XXXController" bundle:nil];

in your code, and make sure that XXXController are spelled correctly

Where does application data file actually stored on android device?

This is a simple way to identify the application related storage paths of a particular app.

Steps:

  1. Have the android device connected to your mac or android emulator open
  2. Open the terminal
  3. adb shell
  4. find .

The "find ." command will list all the files with their paths in the terminal.

./apex/com.android.media.swcodec
./apex/com.android.media.swcodec/etc
./apex/com.android.media.swcodec/etc/init.rc
./apex/com.android.media.swcodec/etc/seccomp_policy
./apex/com.android.media.swcodec/etc/seccomp_policy/mediaswcodec.policy
./apex/com.android.media.swcodec/etc/ld.config.txt
./apex/com.android.media.swcodec/etc/media_codecs.xml
./apex/com.android.media.swcodec/apex_manifest.json
./apex/com.android.media.swcodec/lib
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libcodec2_soft_common.so
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libcodec2_soft_vorbisdec.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_h263dec.so
./apex/com.android.media.swcodec/lib/libhidltransport.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_h263enc.so
./apex/com.android.media.swcodec/lib/libcodec2_vndk.so
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libmedia_codecserviceregistrant.so
./apex/com.android.media.swcodec/lib/libhidlbase.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_aacdec.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_vp9dec.so
.....

After this, just search for your app with the bundle identifier and you can use adb pull command to download the files to your local directory.

PHP validation/regex for URL

Just in case you want to know if the url really exists:

function url_exist($url){//se passar a URL existe
    $c=curl_init();
    curl_setopt($c,CURLOPT_URL,$url);
    curl_setopt($c,CURLOPT_HEADER,1);//get the header
    curl_setopt($c,CURLOPT_NOBODY,1);//and *only* get the header
    curl_setopt($c,CURLOPT_RETURNTRANSFER,1);//get the response as a string from curl_exec(), rather than echoing it
    curl_setopt($c,CURLOPT_FRESH_CONNECT,1);//don't use a cached version of the url
    if(!curl_exec($c)){
        //echo $url.' inexists';
        return false;
    }else{
        //echo $url.' exists';
        return true;
    }
    //$httpcode=curl_getinfo($c,CURLINFO_HTTP_CODE);
    //return ($httpcode<400);
}

Find an element by class name, from a known parent element

You were close. You can do:

var element = $("#parentDiv").find(".myClassNameOfInterest");

Alternatively, you can do:

var element = $(".myClassNameOfInterest", "#parentDiv");

...which sets the context of the jQuery object to the #parentDiv.

EDIT:

Additionally, it may be faster in some browsers if you do div.myClassNameOfInterest instead of just .myClassNameOfInterest.

Font.createFont(..) set color and size (java.awt.Font)

Because font doesn't have color, you need a panel to make a backgound color and give the foreground color for both JLabel (if you use JLabel) and JPanel to make font color, like example below :

JLabel lblusr = new JLabel("User name : ");
lblusr.setForeground(Color.YELLOW);

JPanel usrPanel = new JPanel();
Color maroon = new Color (128, 0, 0);
usrPanel.setBackground(maroon);
usrPanel.setOpaque(true);
usrPanel.setForeground(Color.YELLOW);
usrPanel.add(lblusr);

The background color of label is maroon with yellow font color.

Javascript Array inside Array - how can I call the child array name?

You've made an array of arrays (multidimensional), so options[0] in this case is the size array. you need to reference the first element of the child, which for you is: options[0][0].

If you wanted to loop through all entries you can use the for .. in ... syntax which is described here.

var a = [1,2,4,5,120,12];
for (var val in t) {
    console.log(t[val]);
}

var b = ['S','M','L'];
var both = [a,b];

for (var val in both) {
     for(val2 in both[val]){console.log(both[val][val2])}
}

Good font for code presentations?

I use DejaVu Sans Mono at Size 16.

UPDATE : I have switched to Envy Code R for coding and Anonymous Pro for terminal

Adding a new array element to a JSON object

JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON

var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';

var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"

nginx- duplicate default server error

In my case junk files from editor caused the problem. I had a config as below:

#...
http {
 # ...
 include ../sites/*;
}

In the ../sites directory initially I had a default.config file. However, by mistake I saved duplicate files as default.config.save and default.config.save.1. Removing them resolved the issue.

How to implement if-else statement in XSLT?

You have to reimplement it using <xsl:choose> tag:

       <xsl:choose>
         <xsl:when test="$CreatedDate > $IDAppendedDate">
           <h2> mooooooooooooo </h2>
         </xsl:when>
         <xsl:otherwise>
          <h2> dooooooooooooo </h2>
         </xsl:otherwise>
       </xsl:choose>

Python: import module from another directory at the same level in project hierarchy

In the "root" __init__.py you can also do a

import sys
sys.path.insert(1, '.')

which should make both modules importable.

What characters do I need to escape in XML documents?

Escaping characters is different for tags and attributes.

For tags:

 < &lt;
 > &gt; (only for compatibility, read below)
 & &amp;

For attributes:

" &quot;
' &apos;

From Character Data and Markup:

The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. If they are needed elsewhere, they must be escaped using either numeric character references or the strings " &amp; " and " &lt; " respectively. The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility, be escaped using either " &gt; " or a character reference when it appears in the string " ]]> " in content, when that string is not marking the end of a CDATA section.

To allow attribute values to contain both single and double quotes, the apostrophe or single-quote character (') may be represented as " &apos; ", and the double-quote character (") as " &quot; ".

Loop over html table and get checked checkboxes (JQuery)

use .filter(':has(:checkbox:checked)' ie:

$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
 $('#out').append(this.id);
});

How to delete or change directory of a cloned git repository on a local computer

Just move it :)

command line :

move "C:\Documents and Setings\$USER\project" C:\project

or just drag the folder in explorer.

Git won't care where it is - all the metadata for the repository is inside a folder called .git inside your project folder.

How to write std::string to file?

Assuming you're using a std::ofstream to write to file, the following snippet will write a std::string to file in human readable form:

std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;

Rotating a view in Android

fun rotateArrow(view: View): Boolean {
    return if (view.rotation == 0F) {
        view.animate().setDuration(200).rotation(180F)
        true
    } else {
         view.animate().setDuration(200).rotation(0F)
         false
    }
}

Rolling back bad changes with svn in Eclipse

In Eclipse using Subversive:

Right click your project > Team > Merge

In the merge window, select the revisions you want to revert as normally but also enable checkbox "Reversed merge".

Merge as normally.

Regular Expressions- Match Anything

Because . Find a single character, except newline or line terminator.

So, to match anything, You can use like this: (.|\n)*?

Hope it helps!

How to set div width using ng-style

The syntax of ng-style is not quite that. It accepts a dictionary of keys (attribute names) and values (the value they should take, an empty string unsets them) rather than only a string. I think what you want is this:

<div ng-style="{ 'width' : width, 'background' : bgColor }"></div>

And then in your controller:

$scope.width = '900px';
$scope.bgColor = 'red';

This preserves the separation of template and the controller: the controller holds the semantic values while the template maps them to the correct attribute name.

Using $window or $location to Redirect in AngularJS

I believe the way to do this is $location.url('/RouteTo/Login');

Edit for Clarity

Say my route for my login view was /Login, I would say $location.url('/Login') to navigate to that route.

For locations outside of the Angular app (i.e. no route defined), plain old JavaScript will serve:

window.location = "http://www.my-domain.com/login"

Node.js check if file exists

@Fox: great answer! Here's a bit of an extension with some more options. It's what I've been using lately as a go-to solution:

var fs = require('fs');

fs.lstat( targetPath, function (err, inodeStatus) {
  if (err) {

    // file does not exist-
    if (err.code === 'ENOENT' ) {
      console.log('No file or directory at',targetPath);
      return;
    }

    // miscellaneous error (e.g. permissions)
    console.error(err);
    return;
  }


  // Check if this is a file or directory
  var isDirectory = inodeStatus.isDirectory();


  // Get file size
  //
  // NOTE: this won't work recursively for directories-- see:
  // http://stackoverflow.com/a/7550430/486547
  //
  var sizeInBytes = inodeStatus.size;

  console.log(
    (isDirectory ? 'Folder' : 'File'),
    'at',targetPath,
    'is',sizeInBytes,'bytes.'
  );


}

P.S. check out fs-extra if you aren't already using it-- it's pretty sweet. https://github.com/jprichardson/node-fs-extra)

Replace one character with another in Bash

Try this for paths:

echo \"hello world\"|sed 's/ /+/g'|sed 's/+/\/g'|sed 's/\"//g'

It replaces the space inside the double-quoted string with a + sing, then replaces the + sign with a backslash, then removes/replaces the double-quotes.

I had to use this to replace the spaces in one of my paths in Cygwin.

echo \"$(cygpath -u $JAVA_HOME)\"|sed 's/ /+/g'|sed 's/+/\\/g'|sed 's/\"//g'

How can I remove duplicate rows?

DELETE 
FROM MyTable
WHERE NOT EXISTS (
              SELECT min(RowID)
              FROM Mytable
              WHERE (SELECT RowID 
                     FROM Mytable
                     GROUP BY Col1, Col2, Col3
                     ))
               );

jQuery - Getting the text value of a table cell in the same row as a clicked element

You want .children() instead (documentation here):

$(this).closest('tr').children('td.two').text();

What is the difference between C# and .NET?

Here I provided you a link where explain what is C# Language and the .NET Framework Platform Architecture. Remember that C# is a general-purpose, object-oriented programming language, and it runs on the .NET Framework.

.NET Framework includes a large class library named Framework Class Library (FCL) and provides user interface, data access, database connectivity, cryptography, web application development, numeric algorithms, and network communications.

.NET Framework was developed by Microsoft that runs primarily on Microsoft Windows.

Introduction to the C# Language and the .NET Framework from Microsoft Docs

Is there a portable way to get the current username in Python?

psutil provides a portable way that doesn't use environment variables like the getpass solution. It is less prone to security issues, and should probably be the accepted answer as of today.

import psutil

def get_username():
    return psutil.Process().username()

Under the hood, this combines the getpwuid based method for unix and the GetTokenInformation method for Windows.

Send message to specific client with socket.io and node.js

Also you can keep clients refferences. But this makes your memmory busy.

Create an empty object and set your clients into it.

const myClientList = {};

  server.on("connection", (socket) => {
    console.info(`Client connected [id=${socket.id}]`);
     myClientList[socket.id] = socket;   
  });
  socket.on("disconnect", (socket) => {
    delete myClientList[socket.id];
  });

then call your specific client by id from the object

myClientList[specificId].emit("blabla","somedata");

What are some uses of template template parameters?

Here's another practical example from my CUDA Convolutional neural network library. I have the following class template:

template <class T> class Tensor

which is actually implements n-dimensional matrices manipulation. There's also a child class template:

template <class T> class TensorGPU : public Tensor<T>

which implements the same functionality but in GPU. Both templates can work with all basic types, like float, double, int, etc And I also have a class template (simplified):

template <template <class> class TT, class T> class CLayerT: public Layer<TT<T> >
{
    TT<T> weights;
    TT<T> inputs;
    TT<int> connection_matrix;
}

The reason here to have template template syntax is because I can declare implementation of the class

class CLayerCuda: public CLayerT<TensorGPU, float>

which will have both weights and inputs of type float and on GPU, but connection_matrix will always be int, either on CPU (by specifying TT = Tensor) or on GPU (by specifying TT=TensorGPU).

invalid new-expression of abstract class type

for others scratching their heads, I came across this error because I had innapropriately const-qualified one of the arguments to a method in a base class, so the derived class member functions were not over-riding it. so make sure you don't have something like

class Base 
{
  public:
      virtual void foo(int a, const int b) = 0;
}
class D: public Base 
{
 public:
     void foo(int a, int b){};
}

getting the reason why websockets closed with close code 1006

I've got the error while using Chrome as client and golang gorilla websocket as server under nginx proxy

And sending just some "ping" message from server to client every x second resolved problem

How to add hyperlink in JLabel?

I wrote an article on how to set a hyperlink or a mailto on a jLabel.

So just try it :

I think that's exactly what you're searching for.

Here's the complete code example :

/**
 * Example of a jLabel Hyperlink and a jLabel Mailto
 */

import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 *
 * @author ibrabelware
 */
public class JLabelLink extends JFrame {
    private JPanel pan;
    private JLabel contact;
        private JLabel website;
    /**
     * Creates new form JLabelLink
     */
    public JLabelLink() {
        this.setTitle("jLabelLinkExample");
        this.setSize(300, 100);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);

        pan = new JPanel();
        contact = new JLabel();
        website = new JLabel();

        contact.setText("<html> contact : <a href=\"\">[email protected]</a></html>");
        contact.setCursor(new Cursor(Cursor.HAND_CURSOR));

        website.setText("<html> Website : <a href=\"\">http://www.google.com/</a></html>");
        website.setCursor(new Cursor(Cursor.HAND_CURSOR));

    pan.add(contact);
    pan.add(website);
        this.setContentPane(pan);
        this.setVisible(true);
        sendMail(contact);
        goWebsite(website);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Create and display the form
         */
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new JLabelLink().setVisible(true);
            }
        });
    }

    private void goWebsite(JLabel website) {
        website.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    Desktop.getDesktop().browse(new URI("http://www.google.com/webhp?nomo=1&hl=fr"));
                } catch (URISyntaxException | IOException ex) {
                    //It looks like there's a problem
                }
            }
        });
    }

    private void sendMail(JLabel contact) {
        contact.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    Desktop.getDesktop().mail(new URI("mailto:[email protected]?subject=TEST"));
                } catch (URISyntaxException | IOException ex) {
                    //It looks like there's a problem
                }
            }
        });
    }
}

round() for float in C++

It's available since C++11 in cmath (according to http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf)

#include <cmath>
#include <iostream>

int main(int argc, char** argv) {
  std::cout << "round(0.5):\t" << round(0.5) << std::endl;
  std::cout << "round(-0.5):\t" << round(-0.5) << std::endl;
  std::cout << "round(1.4):\t" << round(1.4) << std::endl;
  std::cout << "round(-1.4):\t" << round(-1.4) << std::endl;
  std::cout << "round(1.6):\t" << round(1.6) << std::endl;
  std::cout << "round(-1.6):\t" << round(-1.6) << std::endl;
  return 0;
}

Output:

round(0.5):  1
round(-0.5): -1
round(1.4):  1
round(-1.4): -1
round(1.6):  2
round(-1.6): -2

No server in Eclipse; trying to install Tomcat

The reason you might not be getting any results is because you might not be having the J2EE environment setup in your Eclipse IDE. Follow these steps to solve the problem.

  1. Goto Help -> Install new Software
  2. Select {Oxygen - http://download.eclipse.org/releases/oxygen} (or Similar option/version) in the "Work with" tab.
  3. Search for Web,XML,Java EE and OSGi Enterprise Development
  4. Check the boxes corresponding to,
    • Eclipse Java EE Developer Tools
    • JST Server Adapters
    • JST Server Adapters Extensions
  5. Click next and accept the license agreement.

Hope this helps.

swift 3.0 Data to String?

for swift 5

let testString = "This is a test string"
let somedata = testString.data(using: String.Encoding.utf8)
let backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String?
print("testString > \(testString)")
//testString > This is a test string
print("somedata > \(String(describing: somedata))")
//somedata > Optional(21 bytes)
print("backToString > \(String(describing: backToString))")
//backToString > Optional("This is a test string")

How do you reinstall an app's dependencies using npm?

For Windows you can use

(if exist node_modules rmdir node_modules /q /s) && npm install

which removes node_modules directory and performs npm install then. Removal before install assures that all packages are reinstalled.

What is the recommended way to make a numeric TextField in JavaFX?

Try this simple code it will do the job.

DecimalFormat format = new DecimalFormat( "#.0" );
TextField field = new TextField();
field.setTextFormatter( new TextFormatter<>(c ->
{
    if ( c.getControlNewText().isEmpty() )
    {
        return c;
    }

    ParsePosition parsePosition = new ParsePosition( 0 );
    Object object = format.parse( c.getControlNewText(), parsePosition );

    if ( object == null || parsePosition.getIndex() <          c.getControlNewText().length() )
    {
        return null;
    }
    else
    {
        return c;
    }
}));

How to make a gap between two DIV within the same column

You can make use of the first-child selector

<div class="sidebar">
    <div class="box">
        <p> 
            Text is here
         </p>
     </div>
    <div class="box">
        <p> 
            Text is here
         </p>
     </div>
</div>

and in CSS

.box {
    padding: 10px;
    text-align: justify;
    margin-top: 20px;
}
.box:first-child {
    margin-top: none;
}

Example: http://jsbin.com/ozarot/edit#javascript,html,live

Maximize a window programmatically and prevent the user from changing the windows state

To programmatically maximize the windowstate you can use:

 this.WindowState = FormWindowState.Maximized;
 this.MaximizeBox = false;

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

Had a similiar experience, but it was because I had renamed an enum in one of my classes. I exported and re-imported the Classes that had referred to the old enum and the error message disappeared. This suggests it is a caching issue in the VBA environment.

How do I find out if first character of a string is a number?

I just came across this question and thought on contributing with a solution that does not use regex.

In my case I use a helper method:

public boolean notNumber(String input){
    boolean notNumber = false;
    try {
        // must not start with a number
        @SuppressWarnings("unused")
        double checker = Double.valueOf(input.substring(0,1));
    }
    catch (Exception e) {
        notNumber = true;           
    }
    return notNumber;
}

Probably an overkill, but I try to avoid regex whenever I can.

ReferenceError: variable is not defined

Got the error (in the function init) with the following code ;

"use strict" ;

var hdr ;

function init(){ // called on load
    hdr = document.getElementById("hdr");
}

... while using the stock browser on a Samsung galaxy Fame ( crap phone which makes it a good tester ) - userAgent ; Mozilla/5.0 (Linux; U; Android 4.1.2; en-gb; GT-S6810P Build/JZO54K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30

The same code works everywhere else I tried including the stock browser on an older HTC phone - userAgent ; Mozilla/5.0 (Linux; U; Android 2.3.5; en-gb; HTC_WildfireS_A510e Build/GRJ90) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1

The fix for this was to change

var hdr ;

to

var hdr = null ;

How to hide soft keyboard on android after clicking outside EditText?

There is a simpler approach, based on iPhone same issue. Simply override the background's layout on touch event, where the edit text is contained. Just use this code in the activity's OnCreate (login_fondo is the root layout):

    final LinearLayout llLogin = (LinearLayout)findViewById(R.id.login_fondo);
    llLogin.setOnTouchListener(
            new OnTouchListener()
            {
                @Override
                public boolean onTouch(View view, MotionEvent ev) {
                    InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(
                            android.content.Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(), 0);
                    return false;
                }
            });

How can I find a specific element in a List<T>?

Try:

 list.Find(item => item.id==myid);

Import cycle not allowed

Here is an illustration of your first import cycle problem.

                  project/controllers/account
                     ^                    \    
                    /                      \
                   /                        \ 
                  /                         \/
         project/components/mux <--- project/controllers/base

As you can see with my bad ASCII chart is that you are creating an import cycle when project/components/mux imports project/controllers/account. Since Go does not support circular dependencies you get the import cycle not allowed error during compile time.

Java - How to create a custom dialog box?

Try this simple class for customizing a dialog to your liking:

import java.util.ArrayList;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;

public class CustomDialog
{
    private List<JComponent> components;

    private String title;
    private int messageType;
    private JRootPane rootPane;
    private String[] options;
    private int optionIndex;

    public CustomDialog()
    {
        components = new ArrayList<>();

        setTitle("Custom dialog");
        setMessageType(JOptionPane.PLAIN_MESSAGE);
        setRootPane(null);
        setOptions(new String[] { "OK", "Cancel" });
        setOptionSelection(0);
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public void setMessageType(int messageType)
    {
        this.messageType = messageType;
    }

    public void addComponent(JComponent component)
    {
        components.add(component);
    }

    public void addMessageText(String messageText)
    {
        JLabel label = new JLabel("<html>" + messageText + "</html>");

        components.add(label);
    }

    public void setRootPane(JRootPane rootPane)
    {
        this.rootPane = rootPane;
    }

    public void setOptions(String[] options)
    {
        this.options = options;
    }

    public void setOptionSelection(int optionIndex)
    {
        this.optionIndex = optionIndex;
    }

    public int show()
    {
        int optionType = JOptionPane.OK_CANCEL_OPTION;
        Object optionSelection = null;

        if(options.length != 0)
        {
            optionSelection = options[optionIndex];
        }

        int selection = JOptionPane.showOptionDialog(rootPane,
                components.toArray(), title, optionType, messageType, null,
                options, optionSelection);

        return selection;
    }

    public static String getLineBreak()
    {
        return "<br>";
    }
}

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

App Passwords helped me.

  1. Go to https://myaccount.google.com/security.
  2. Scroll down to "Signing in to Google".
  3. Enable 2-Step Verification.
  4. Add App Password.
  5. Use the generated password in your code.

How can I check if a string is null or empty in PowerShell?

# cases
$x = null
$x = ''
$x = ' '

# test
if ($x -and $x.trim()) {'not empty'} else {'empty'}
or
if ([string]::IsNullOrWhiteSpace($x)) {'empty'} else {'not empty'}

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

React - Component Full Screen (with height 100%)

I had trouble until i used the inspector and realized react puts everything inside a div with id='root' granting that 100% height along with body and html worked for me.

Ruby - ignore "exit" in code

loop {   begin     Bar.new   rescue SystemExit     p $!  #: #<SystemExit: exit>   end } 

This will print #<SystemExit: exit> in an infinite loop, without ever exiting.

phpmyadmin.pma_table_uiprefs doesn't exist

I came across this same problem on Ubuntu 13.10. I didn't want to hack PHP files, because normally phpMyAdmin works out of the box after installing the package from Ubuntu repositories. Instead I ran:

sudo dpkg-reconfigure phpmyadmin

During reconfigure, I said "yes" to reinstalling the phpMyAdmin database. Afterwards, the problem was gone. I have a vague memory of answering "No" to that question at some earlier time, during an install or upgrade. That is probably why the problem occurred in the first place.

Jquery to open Bootstrap v3 modal of remote url

e.relatedTarget.data('load-url'); won't work
use dataset.loadUrl

$('#myModal').on('show.bs.modal', function (e) {
    var loadurl = e.relatedTarget.dataset.loadUrl;
    $(this).find('.modal-body').load(loadurl);
});

How to print a list in Python "nicely"

As other answers have mentioned, pprint is a great module that will do what you want. However if you don't want to import it and just want to print debugging output during development, you can approximate its output.

Some of the other answers work fine for strings, but if you try them with a class object it will give you the error TypeError: sequence item 0: expected string, instance found.

For more complex objects, make sure the class has a __repr__ method that prints the property information you want:

class Foo(object):
    def __init__(self, bar):
        self.bar = bar

    def __repr__(self):
        return "Foo - (%r)" % self.bar

And then when you want to print the output, simply map your list to the str function like this:

l = [Foo(10), Foo(20), Foo("A string"), Foo(2.4)]
print "[%s]" % ",\n ".join(map(str,l))

outputs:

 [Foo - (10),
  Foo - (20),
  Foo - ('A string'),
  Foo - (2.4)]

You can also do things like override the __repr__ method of list to get a form of nested pretty printing:

class my_list(list):
    def __repr__(self):
        return "[%s]" % ",\n ".join(map(str, self))

a = my_list(["first", 2, my_list(["another", "list", "here"]), "last"])
print a

gives

[first,
 2,
 [another,
 list,
 here],
 last]

Unfortunately no second-level indentation but for a quick debug it can be useful.

ORA-01652: unable to extend temp segment by 128 in tablespace SYSTEM: How to extend?

Each tablespace has one or more datafiles that it uses to store data.

The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.

To find out if the actual limit is 32gb, run the following:

select value from v$parameter where name = 'db_block_size';

Compare the result you get with the first column below, and that will indicate what your max datafile size is.

I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).

Block Sz   Max Datafile Sz (Gb)   Max DB Sz (Tb)

--------   --------------------   --------------

   2,048                  8,192          524,264

   4,096                 16,384        1,048,528

   8,192                 32,768        2,097,056

  16,384                 65,536        4,194,112

  32,768                131,072        8,388,224

You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):

select bytes/1024/1024 as mb_size,
       maxbytes/1024/1024 as maxsize_set,
       x.*
from   dba_data_files x

MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).

If your datafile has a low max size or autoextend is not on you could simply run:

alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;

However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:

alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;

JWT (Json Web Token) Audience "aud" versus Client_Id - What's the difference?

If you came here searching OpenID Connect (OIDC): OAuth 2.0 != OIDC

I recognize that this is tagged for oauth 2.0 and NOT OIDC, however there is frequently a conflation between the 2 standards since both standards can use JWTs and the aud claim. And one (OIDC) is basically an extension of the other (OAUTH 2.0). (I stumbled across this question looking for OIDC myself.)

OAuth 2.0 Access Tokens##

For OAuth 2.0 Access tokens, existing answers pretty well cover it. Additionally here is one relevant section from OAuth 2.0 Framework (RFC 6749)

For public clients using implicit flows, this specification does not provide any method for the client to determine what client an access token was issued to.
...
Authenticating resource owners to clients is out of scope for this specification. Any specification that uses the authorization process as a form of delegated end-user authentication to the client (e.g., third-party sign-in service) MUST NOT use the implicit flow without additional security mechanisms that would enable the client to determine if the access token was issued for its use (e.g., audience- restricting the access token).

OIDC ID Tokens##

OIDC has ID Tokens in addition to Access tokens. The OIDC spec is explicit on the use of the aud claim in ID Tokens. (openid-connect-core-1.0)

aud
REQUIRED. Audience(s) that this ID Token is intended for. It MUST contain the OAuth 2.0 client_id of the Relying Party as an audience value. It MAY also contain identifiers for other audiences. In the general case, the aud value is an array of case sensitive strings. In the common special case when there is one audience, the aud value MAY be a single case sensitive string.

furthermore OIDC specifies the azp claim that is used in conjunction with aud when aud has more than one value.

azp
OPTIONAL. Authorized party - the party to which the ID Token was issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. This Claim is only needed when the ID Token has a single audience value and that audience is different than the authorized party. It MAY be included even when the authorized party is the same as the sole audience. The azp value is a case sensitive string containing a StringOrURI value.

How to show a running progress bar while page is loading

In this sample, I created a JavaScript progress bar (with percentage display), you can control it and hide it with JavaScript.

In this sample, the progress bar advances every 100ms. You can see it in JSFiddle

var elapsedTime = 0;
var interval = setInterval(function() {
  timer()
}, 100);

function progressbar(percent) {
  document.getElementById("prgsbarcolor").style.width = percent + '%';
  document.getElementById("prgsbartext").innerHTML = percent + '%';
}

function timer() {
  if (elapsedTime > 100) {
    document.getElementById("prgsbartext").style.color = "#FFF";
    document.getElementById("prgsbartext").innerHTML = "Completed.";
    if (elapsedTime >= 107) {
      clearInterval(interval);
      history.go(-1);
    }
  } else {
    progressbar(elapsedTime);
  }
  elapsedTime++;
}

How do I remove an array item in TypeScript?

Answer using TypeScript spread operator (...)

// Your key
const key = 'two';

// Your array
const arr = [
    'one',
    'two',
    'three'
];

// Get either the index or -1
const index = arr.indexOf(key); // returns 0


// Despite a real index, or -1, use spread operator and Array.prototype.slice()    
const newArray = (index > -1) ? [
    ...arr.slice(0, index),
    ...arr.slice(index + 1)
] : arr;

"Eliminate render-blocking CSS in above-the-fold content"

A related question has been asked before: What is “above-the-fold content” in Google Pagespeed?

Firstly you have to notice that this is all about 'mobile pages'.
So when I interpreted your question and screenshot correctly, then this is not for your site!

On the contrary - doing some of the things advised by Google in their guidelines will things make worse than better for 'normal' websites.
And not everything that comes from Google is the "holy grail" just because it comes from Google. And they themselves are not a good role model if you have a look at their HTML markup.

The best advice I could give you is:

  • Set width and height on replaced elements in your CSS, so that the browser can layout the elements and doesn't have to wait for the replaced content!

Additionally why do you use different CSS files, rather than just one?
The additional request is worse than the small amount of data volume. And after the first request the CSS file is cached anyway.

The things one should always take care of are:

  • reduce the number of requests as much as possible
  • keep your overall page weight as low as possible

And don't puzzle your brain about how to get 100% of Google's PageSpeed Insights tool ...! ;-)

Addition 1: Here is the page on which Google shows us, what they recommend for Optimize CSS Delivery.

As said before, I don't think that this is neither realistic nor that it makes sense for a "normal" website! Because mainly when you have a responsive web design it is most certain that you use media queries and other layout styles. So if you are not gonna load your CSS first and in a blocking manner you'll get a FOUT (Flash Of Unstyled Text). I really do not believe that this is "better" than at least some more milliseconds to render the page!

Imho Google is starting a new "hype" (when I have a look at all the question about it here on Stackoverflow) ...!

How do I disable form fields using CSS?

A variation to the pointer-events: none; solution, which resolves the issue of the input still being accessible via it's labeled control or tabindex, is to wrap the input in a div, which is styled as a disabled text input, and setting input { visibility: hidden; } when the input is "disabled".
Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/visibility#Values

_x000D_
_x000D_
div.dependant {_x000D_
  border: 0.1px solid rgb(170, 170, 170);_x000D_
  background-color: rgb(235,235,228);_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
input[type="checkbox"]:not(:checked) ~ div.dependant:first-of-type {_x000D_
  display: inline-block;_x000D_
}_x000D_
input[type="checkbox"]:checked ~ div.dependant:first-of-type {_x000D_
  display: contents;_x000D_
}_x000D_
input[type="checkbox"]:not(:checked) ~ div.dependant:first-of-type > input {_x000D_
  visibility: hidden;_x000D_
}
_x000D_
<form>_x000D_
  <label for="chk1">Enable textbox?</label>_x000D_
  <input id="chk1" type="checkbox" />_x000D_
  <br />_x000D_
  <label for="text1">Input textbox label</label>_x000D_
  <div class="dependant">_x000D_
    <input id="text1" type="text" />_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

The disabled styling applied in the snippet above is taken from the Chrome UI and may not be visually identical to disabled inputs on other browsers. Possibly it can be customised for individual browsers using engine-specific CSS extension -prefixes. Though at a glance, I don't think it could:
Microsoft CSS extensions, Mozilla CSS extensions, WebKit CSS extensions

It would seem far more sensible to introduce an additional value visibility: disabled or display: disabled or perhaps even appearance: disabled, given that visibility: hidden already affects the behavior of the applicable elements any associated control elements.

How to write trycatch in R

tryCatch has a slightly complex syntax structure. However, once we understand the 4 parts which constitute a complete tryCatch call as shown below, it becomes easy to remember:

expr: [Required] R code(s) to be evaluated

error : [Optional] What should run if an error occured while evaluating the codes in expr

warning : [Optional] What should run if a warning occured while evaluating the codes in expr

finally : [Optional] What should run just before quitting the tryCatch call, irrespective of if expr ran successfully, with an error, or with a warning

tryCatch(
    expr = {
        # Your code...
        # goes here...
        # ...
    },
    error = function(e){ 
        # (Optional)
        # Do this if an error is caught...
    },
    warning = function(w){
        # (Optional)
        # Do this if an warning is caught...
    },
    finally = {
        # (Optional)
        # Do this at the end before quitting the tryCatch structure...
    }
)

Thus, a toy example, to calculate the log of a value might look like:

log_calculator <- function(x){
    tryCatch(
        expr = {
            message(log(x))
            message("Successfully executed the log(x) call.")
        },
        error = function(e){
            message('Caught an error!')
            print(e)
        },
        warning = function(w){
            message('Caught an warning!')
            print(w)
        },
        finally = {
            message('All done, quitting.')
        }
    )    
}

Now, running three cases:

A valid case

log_calculator(10)
# 2.30258509299405
# Successfully executed the log(x) call.
# All done, quitting.

A "warning" case

log_calculator(-10)
# Caught an warning!
# <simpleWarning in log(x): NaNs produced>
# All done, quitting.

An "error" case

log_calculator("log_me")
# Caught an error!
# <simpleError in log(x): non-numeric argument to mathematical function>
# All done, quitting.

I've written about some useful use-cases which I use regularly. Find more details here: https://rsangole.netlify.com/post/try-catch/

Hope this is helpful.

Getting RSA private key from PEM BASE64 Encoded private key file

You've just published that private key, so now the whole world knows what it is. Hopefully that was just for testing.

EDIT: Others have noted that the openssl text header of the published key, -----BEGIN RSA PRIVATE KEY-----, indicates that it is PKCS#1. However, the actual Base64 contents of the key in question is PKCS#8. Evidently the OP copy and pasted the header and trailer of a PKCS#1 key onto the PKCS#8 key for some unknown reason. The sample code I've provided below works with PKCS#8 private keys.

Here is some code that will create the private key from that data. You'll have to replace the Base64 decoding with your IBM Base64 decoder.

public class RSAToy {

    private static final String BEGIN_RSA_PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\n"
            + "MIIEuwIBADAN ...skipped the rest\n"
         // + ...   
         // + ... skipped the rest
         // + ...   
            + "-----END RSA PRIVATE KEY-----";

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

        // Remove the first and last lines

        String privKeyPEM = BEGIN_RSA_PRIVATE_KEY.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
        privKeyPEM = privKeyPEM.replace("-----END RSA PRIVATE KEY-----", "");
        System.out.println(privKeyPEM);

        // Base64 decode the data

        byte [] encoded = Base64.decode(privKeyPEM);

        // PKCS8 decode the encoded RSA private key

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey privKey = kf.generatePrivate(keySpec);

        // Display the results

        System.out.println(privKey);
    }
}

Is there an "if -then - else " statement in XPath?

The official language specification for XPath 2.0 on W3.org details that the language does indeed support if statements. See Section 3.8 Conditional Expressions, in particular. Along with the syntax format and explanation, it gives the following example:

if ($widget1/unit-cost < $widget2/unit-cost) 
  then $widget1
  else $widget2

This would suggest that you shouldn't have brackets surrounding your expressions (otherwise the syntax looks correct). I'm not wholly confident, but it's surely worth a try. So you'll want to change your query to look like this:

if (fn:ends-with(//div [@id='head']/text(),': '))
  then fn:substring-before(//div [@id='head']/text(),': ')
  else //div [@id='head']/text()

I do strongly suspect this may fix it however, as the fact that your XPath engine seems to be trying to interpret if as a function, where it is in fact a special construct of the language.

Finally, to point out the obvious, insure that your XPath engine does in fact support XPath 2.0 (as opposed to an earlier version)! I don't believe conditional expressions are part of previous versions of XPath.

How to cast from List<Double> to double[] in Java?

You can use primitive collections from Eclipse Collections and avoid boxing altogether.

DoubleList frameList = DoubleLists.mutable.empty();
double[] arr = frameList.toArray();

If you can't or don't want to initialize a DoubleList:

List<Double> frames = new ArrayList<>();
double[] arr = ListAdapter.adapt(frames).asLazy().collectDouble(each -> each).toArray();

Note: I am a contributor to Eclipse Collections.

How to break long string to multiple lines

you may simply create your string in multiple steps, a bit redundant but it keeps the code readable and maintain sanity while debugging or editing

SqlQueryString = "Insert into Employee values(" 
SqlQueryString = SqlQueryString & txtEmployeeNo.Value & " ,"
SqlQueryString = SqlQueryString & " '" & txtEmployeeNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtContractStartDate.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtSeatNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtContractStartDate.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtSeatNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtFloor.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtLeaves.Value & "' )"

What's the difference between the Window.Loaded and Window.ContentRendered events

If you're using data binding, then you need to use the ContentRendered event.

For the code below, the Header is NULL when the Loaded event is raised. However, Header gets its value when the ContentRendered event is raised.

<MenuItem Header="{Binding NewGame_Name}" Command="{Binding NewGameCommand}" />

Java; String replace (using regular expressions)?

What is your polynomial? If you're "processing" it, I'm envisioning some sort of tree of sub-expressions being generated at some point, and would think that it would be much simpler to use that to generate your string than to re-parse the raw expression with a regex.

Just throwing a different way of thinking out there. I'm not sure what else is going on in your app.

Multiple file extensions in OpenFileDialog

Based on First answer here is the complete image selection options:

Filter = @"|All Image Files|*.BMP;*.bmp;*.JPG;*.JPEG*.jpg;*.jpeg;*.PNG;*.png;*.GIF;*.gif;*.tif;*.tiff;*.ico;*.ICO
           |PNG|*.PNG;*.png
           |JPEG|*.JPG;*.JPEG*.jpg;*.jpeg
           |Bitmap(.BMP,.bmp)|*.BMP;*.bmp                                    
           |GIF|*.GIF;*.gif
           |TIF|*.tif;*.tiff
           |ICO|*.ico;*.ICO";

How should I cast in VB.NET?

According to the certification exam you should use Convert.ToXXX() whenever possible for simple conversions because it optimizes performance better than CXXX conversions.

Java: Rotating Images

A simple way to do it without the use of such a complicated draw statement:

    //Make a backup so that we can reset our graphics object after using it.
    AffineTransform backup = g2d.getTransform();
    //rx is the x coordinate for rotation, ry is the y coordinate for rotation, and angle
    //is the angle to rotate the image. If you want to rotate around the center of an image,
    //use the image's center x and y coordinates for rx and ry.
    AffineTransform a = AffineTransform.getRotateInstance(angle, rx, ry);
    //Set our Graphics2D object to the transform
    g2d.setTransform(a);
    //Draw our image like normal
    g2d.drawImage(image, x, y, null);
    //Reset our graphics object so we can draw with it again.
    g2d.setTransform(backup);

Brew doctor says: "Warning: /usr/local/include isn't writable."

For High Sierra:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then, try your brew commands.

Issue #3285

How to send push notification to web browser?

this is simple way to do push notification for all browser https://pushjs.org

Push.create("Hello world!", {
body: "How's it hangin'?",
icon: '/icon.png',
timeout: 4000,
onClick: function () {
    window.focus();
    this.close();
 }
});

Transactions in .net

You could also wrap the transaction up into it's own stored procedure and handle it that way instead of doing transactions in C# itself.

How to close activity and go back to previous activity in android

Finish closes the whole application, this is is something i hate in Android development not finish that is fine but that they do not keep up wit ok syntax they have

startActivity(intent)

Why not

closeActivity(intent) ?

Using the "start" command with parameters passed to the started program

The spaces are DOSs/CMDs Problems so you should go to the Path via:

cd "c:\program files\Microsoft Virtual PC"

and then simply start VPC via:

start Virtual~1.exe -pc MY-PC -launch

~1 means the first exe with "Virtual" at the beginning. So if there is a "Virtual PC.exe" and a "Virtual PC1.exe" the first would be the Virtual~1.exe and the second Virtual~2.exe and so on.

Or use a VNC-Client like VirtualBox.

How to terminate a process in vbscript

Just type in the following command: taskkill /f /im (program name) To find out the im of your program open task manager and look at the process while your program is running. After the program has run a process will disappear from the task manager; that is your program.

How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

How to read the shell variable in groovy / how to assign shell return value to groovy variable.

Requirement : Open a text file read the lines using shell and store the value in groovy and get the parameter for each line .

Here , is delimiter

Ex: releaseModule.txt

./APP_TSBASE/app/team/i-home/deployments/ip-cc.war/cs_workflowReport.jar,configurable-wf-report,94,23crb1,artifact



./APP_TSBASE/app/team/i-home/deployments/ip.war/cs_workflowReport.jar,configurable-temppweb-report,394,rvu3crb1,artifact

========================

Here want to get module name 2nd Parameter (configurable-wf-report) , build no 3rd Parameter (94), commit id 4th (23crb1)

def  module = sh(script: """awk -F',' '{ print \$2 "," \$3 "," \$4 }' releaseModules.txt  | sort -u """, returnStdout: true).trim()

echo module

List lines = module.split( '\n' ).findAll { !it.startsWith( ',' ) }

def buildid

def Modname

lines.each {

List det1 =  it.split(',')

buildid=det1[1].trim() 

Modname = det1[0].trim()

tag= det1[2].trim()

               

echo Modname               

echo buildid

                echo tag

                        

}

When should the xlsm or xlsb formats be used?

One could think that xlsb has only advantages over xlsm. The fact that xlsm is XML-based and xlsb is binary is that when workbook corruption occurs, you have better chances to repair a xlsm than a xlsb.

Can I force a UITableView to hide the separator between empty cells?

If you use iOS 7 SDK, this is very simple.

Just add this line in your viewDidLoad method:

self.yourTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

SQL Server IF NOT EXISTS Usage?

Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.

set nocount on

create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)

insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)

declare @PersonID int
set @PersonID = 1

IF EXISTS    
    (
    SELECT 1    
    FROM Timesheet_Hours    
    WHERE Posted_Flag = 1    
        AND Staff_Id = @PersonID    
    )    
    BEGIN
        RAISERROR('Timesheets have already been posted!', 16, 1)
        ROLLBACK TRAN
    END
ELSE
    IF NOT EXISTS
        (
        SELECT 1
        FROM Timesheet_Hours
        WHERE Staff_Id = @PersonID
        )
        BEGIN
            RAISERROR('Default list has not been loaded!', 16, 1)
            ROLLBACK TRAN
        END
    ELSE
        print 'No problems here'

drop table Timesheet_Hours

jQuery: get parent, parent id?

Here are 3 examples:

_x000D_
_x000D_
$(document).on('click', 'ul li a', function (e) {_x000D_
    e.preventDefault();_x000D_
_x000D_
    var example1 = $(this).parents('ul:first').attr('id');_x000D_
    $('#results').append('<p>Result from example 1: <strong>' + example1 + '</strong></p>');_x000D_
_x000D_
    var example2 = $(this).parents('ul:eq(0)').attr('id');_x000D_
    $('#results').append('<p>Result from example 2: <strong>' + example2 + '</strong></p>');_x000D_
  _x000D_
    var example3 = $(this).closest('ul').attr('id');_x000D_
    $('#results').append('<p>Result from example 3: <strong>' + example3 + '</strong></p>');_x000D_
  _x000D_
  _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<ul id ="myList">_x000D_
  <li><a href="www.example.com">Click here</a></li>_x000D_
</ul>_x000D_
_x000D_
<div id="results">_x000D_
  <h1>Results:</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Let me know whether it was helpful.

No module named Image

Did you setup PIL module? Link

You can try to reinstall it on your computer.

Best way to get identity of inserted row?

ALWAYS use scope_identity(), there's NEVER a need for anything else.

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

The source code provides some basic guidance:

The order in terms of verbosity, from least to most is ERROR, WARN, INFO, DEBUG, VERBOSE. Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.

For more detail, Kurtis' answer is dead on. I would just add: Don't log any personally identifiable or private information at INFO or above (WARN/ERROR). Otherwise, bug reports or anything else that includes logging may be polluted.

Android Studio - How to Change Android SDK Path

In Android studio 1.2.2 you can simply changes project based SDK, Steps:

  1. Right click on Module and select Open module setting or press F12
  2. Select SDK location from left hand side
  3. Now you can change SDK location as well as JDK location from this page

Is it possible to wait until all javascript files are loaded before executing javascript code?

You can use <script>'s defer attribute. It specifies that the script will be executed when the page has finished parsing.

<script defer src="path/to/yourscript.js">

A nice article about this: http://davidwalsh.name/script-defer

Browser support seems pretty good: http://caniuse.com/#search=defer

Another great article about loading JS using defer and async: https://flaviocopes.com/javascript-async-defer/

How to specify an element after which to wrap in css flexbox?

Setting a min-width on child elements will also create a breakpoint. For example breaking every 3 elements,

flex-grow: 1;
min-width: 33%; 

If there are 4 elements, this will have the 4th element wrap taking the full 100%. If there are 5 elements, the 4th and 5th elements will wrap and take each 50%.

Make sure to have parent element with,

flex-wrap: wrap

Eclipse will not start and I haven't changed anything

Maybe worth mentioning that when I had this problem I followed bia.migueis's advice - move everything out of the plugins folder - and the workspace would open again, minus a lot of my configuration. But then after that, I copied/overwrote all the original files back into the plugins folder and opened the workspace again: it still worked and the settings I'd had before seemed to be intact.

Delete specific line number(s) from a text file using sed?

and awk as well

awk 'NR!~/^(5|10|25)$/' file

What does the "On Error Resume Next" statement do?

When an error occurs, the execution will continue on the next line without interrupting the script.

React.js inline style best practices

I prefer to use styled-components. It provide better solution for design.

import React, { Component, Fragment } from 'react'
import styled from 'styled-components';

const StyledDiv = styled.div`
    display: block;
    margin-left: auto;
    margin-right: auto;
    font-size:200; // here we can set static
    color: ${props => props.color} // set dynamic color by props
`;

export default class RenderHtml extends Component {
    render() {
        return (
            <Fragment>
                <StyledDiv color={'white'}>
                    Have a good and productive day!
                </StyledDiv>
            </Fragment>
        )
    }
}

Error: Cannot find module html

This is what i did for rendering html files. And it solved the errors. Install consolidate and mustache by executing the below command in your project folder.

$ sudo npm install consolidate mustache --save

And make the following changes to your app.js file

var engine = require('consolidate');

app.set('views', __dirname + '/views');
app.engine('html', engine.mustache);
app.set('view engine', 'html');

And now html pages will be rendered properly.

Finding last occurrence of substring in string, replacing that

To replace from the right:

def replace_right(source, target, replacement, replacements=None):
    return replacement.join(source.rsplit(target, replacements))

In use:

>>> replace_right("asd.asd.asd.", ".", ". -", 1)
'asd.asd.asd. -'

How in node to split string by newline ('\n')?

A solution that works with all possible line endings including mixed ones and keeping empty lines as well can be achieved using two replaces and one split as follows

text.replace(/\r\n/g, "\r").replace(/\n/g, "\r").split(/\r/);

some code to test it

  var CR = "\x0D";  //   \r
  var LF = "\x0A";  //   \n

  var mixedfile = "00" + CR + LF +            // 1 x win
                  "01" + LF +                 // 1 x linux
                  "02" + CR +                 // 1 x old mac
                  "03" + CR + CR +            // 2 x old mac
                  "05" + LF + LF +            // 2 x linux
                  "07" + CR + LF + CR + LF +  // 2 x win
                  "09";

  function showarr (desc, arr)
  {
     console.log ("// ----- " + desc);
     for (var ii in arr)
        console.log (ii + ") [" + arr[ii] +  "] (len = " + arr[ii].length + ")");
  }

  showarr ("using 2 replace + 1 split", 
           mixedfile.replace(/\r\n/g, "\r").replace(/\n/g, "\r").split(/\r/));

and the output

  // ----- using 2 replace + 1 split
  0) [00] (len = 2)
  1) [01] (len = 2)
  2) [02] (len = 2)
  3) [03] (len = 2)
  4) [] (len = 0)
  5) [05] (len = 2)
  6) [] (len = 0)
  7) [07] (len = 2)
  8) [] (len = 0)
  9) [09] (len = 2)

HTML5 image icon to input placeholder

  1. You can set it as background-image and use text-indent or a padding to shift the text to the right.
  2. You can break it up into two elements.

Honestly, I would avoid usage of HTML5/CSS3 without a good fallback. There are just too many people using old browsers that don't support all the new fancy stuff. It will take a while before we can drop the fallback, unfortunately :(

The first method I mentioned is the safest and easiest. Both ways requires Javascript to hide the icon.

CSS:

input#search {
    background-image: url(bg.jpg);
    background-repeat: no-repeat;
    text-indent: 20px;
}

HTML:

<input type="text" id="search" name="search" onchange="hideIcon(this);" value="search" />

Javascript:

function hideIcon(self) {
    self.style.backgroundImage = 'none';
}

September 25h, 2013

I can't believe I said "Both ways requires JavaScript to hide the icon.", because this is not entirely true.

The most common timing to hide placeholder text is on change, as suggested in this answer. For icons however it's okay to hide them on focus which can be done in CSS with the active pseudo-class.

#search:active { background-image: none; }

Heck, using CSS3 you can make it fade away!

http://jsfiddle.net/2tTxE/


November 5th, 2013

Of course, there's the CSS3 ::before pseudo-elements too. Beware of browser support though!

            Chrome  Firefox     IE      Opera   Safari
:before     (yes)   1.0         8.0     4       4.0
::before    (yes)   1.5         9.0     7       4.0

https://developer.mozilla.org/en-US/docs/Web/CSS/::before

HTML/CSS font color vs span style

1st preference external style sheet.

<span class="myClass">test</span>

css

.myClass
{
color:red;
}

2nd preference inline style

<span style="color:red">test</span>

<font> as mentioned is deprecated.

What's the difference between a single precision and double precision floating point operation?

Single precision number uses 32 bits, with the MSB being sign bit, whereas double precision number uses 64bits, MSB being sign bit

Single precision

SEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFF.(SIGN+EXPONENT+SIGNIFICAND)

Double precision:

SEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF.(SIGN+EXPONENT+SIGNIFICAND)

Netbeans - Error: Could not find or load main class

I just ran into this problem. I was running my source from the command line and kept getting the same error. It turns out that I needed to remove the package name from my source code and then the command line compiler was happy.

The solutions above didn't work for me so maybe this will work for someone else with a similar problem.

Why does Oracle not find oci.dll?

I was also looking for solving this issue. Maybe this answer will help someone.

In my case similar issue have appeared when I used Oracle Instant Client 18.5 for connecting to DB using Toad 13.1.1.5

To solve it I've downloaded more recent version of OIC - Oracle Instant Client 19.3 and Toad connected to Oracle's DB without issues.

Maybe there was version incompatibility issue. New version of Toad require a new version of oci library.

Both OICs were 64 bit and folders of both of them I've added into the user's Path variable.

Client OS: Win10

Server: OL7.7,

DB: 18c

How to read pickle file?

There is a read_pickle function as part of pandas 0.22+

import pandas as pd

object = pd.read_pickle(r'filepath')

Show all current locks from get_lock

SHOW FULL PROCESSLIST;

You will see the locks in there

How to make a HTML Page in A4 paper size page(s)?

I've used HTML to generate reports which print-out correctly at real sizes on real paper.

If you carefully use mm as your units in the CSS file you should be OK, at least for single pages. People can screw you up by changing the print zoom in their browser, though.

I seem to remember everything I was doing was single page, so I didn't have to worry about pagination - that might be much harder.

CSS grid wrapping

Here's my attempt. Excuse the fluff, I was feeling extra creative.

My method is a parent div with fixed dimensions. The rest is just fitting the content inside that div accordingly.

This will rescale the images regardless of the aspect ratio. There will be no hard cropping either.

_x000D_
_x000D_
body {_x000D_
    background: #131418;_x000D_
    text-align: center;_x000D_
    margin: 0 auto;_x000D_
}_x000D_
_x000D_
.my-image-parent {_x000D_
    display: inline-block;_x000D_
    width: 300px;_x000D_
    height: 300px;_x000D_
    line-height: 300px; /* Should match your div height */_x000D_
    text-align: center;_x000D_
    font-size: 0;_x000D_
}_x000D_
_x000D_
/* Start demonstration background fluff */_x000D_
    .bg1 {background: url(https://unsplash.it/801/799);}_x000D_
    .bg2 {background: url(https://unsplash.it/799/800);}_x000D_
    .bg3 {background: url(https://unsplash.it/800/799);}_x000D_
    .bg4 {background: url(https://unsplash.it/801/801);}_x000D_
    .bg5 {background: url(https://unsplash.it/802/800);}_x000D_
    .bg6 {background: url(https://unsplash.it/800/802);}_x000D_
    .bg7 {background: url(https://unsplash.it/802/802);}_x000D_
    .bg8 {background: url(https://unsplash.it/803/800);}_x000D_
    .bg9 {background: url(https://unsplash.it/800/803);}_x000D_
    .bg10 {background: url(https://unsplash.it/803/803);}_x000D_
    .bg11 {background: url(https://unsplash.it/803/799);}_x000D_
    .bg12 {background: url(https://unsplash.it/799/803);}_x000D_
    .bg13 {background: url(https://unsplash.it/806/799);}_x000D_
    .bg14 {background: url(https://unsplash.it/805/799);}_x000D_
    .bg15 {background: url(https://unsplash.it/798/804);}_x000D_
    .bg16 {background: url(https://unsplash.it/804/799);}_x000D_
    .bg17 {background: url(https://unsplash.it/804/804);}_x000D_
    .bg18 {background: url(https://unsplash.it/799/804);}_x000D_
    .bg19 {background: url(https://unsplash.it/798/803);}_x000D_
    .bg20 {background: url(https://unsplash.it/803/797);}_x000D_
/* end demonstration background fluff */_x000D_
_x000D_
.my-image {_x000D_
    width: auto;_x000D_
    height: 100%;_x000D_
    vertical-align: middle;_x000D_
    background-size: contain;_x000D_
    background-position: center;_x000D_
    background-repeat: no-repeat;_x000D_
}
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg1"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg2"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg3"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg4"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg5"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg6"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg7"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg8"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg9"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg10"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg11"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg12"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg13"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg14"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg15"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg16"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg17"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg18"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg19"></div>_x000D_
</div>_x000D_
_x000D_
<div class="my-image-parent">_x000D_
    <div class="my-image bg20"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Cassandra "no viable alternative at input"

Wrong syntax. Here you are:

insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');

or:

insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');

The second one is normally used for case-sensitive column names.

Angular 4 img src is not found

Try This:

<img class="img-responsive" src="assets/img/google-body-ads.png">

What is the difference between a stored procedure and a view?

Mahesh is not quite correct when he suggests that you can't alter the data in a view. So with patrick's view

CREATE View vw_user_profile AS 
Select A.user_id, B.profile_description
FROM tbl_user A left join tbl_profile B on A.user_id = b.user_id

I CAN update the data ... as an example I can do either of these ...

Update vw_user_profile Set profile_description='Manager' where user_id=4

or

Update tbl_profile Set profile_description='Manager' where user_id=4

You can't INSERT to this view as not all of the fields in all of the table are present and I'm assuming that PROFILE_ID is the primary key and can't be NULL. However you can sometimes INSERT into a view ...

I created a view on an existing table using ...

Create View Junk as SELECT * from [TableName]

THEN

Insert into junk (Code,name) values 
('glyn','Glyn Roberts'),
('Mary','Maryann Roberts')

and

DELETE from Junk Where ID>4

Both the INSERT and the DELETE worked in this case

Obviously you can't update any fields which are aggregated or calculated but any view which is just a straight view should be updateable.

If the view contains more than one table then you can't insert or delete but if the view is a subset of one table only then you usually can.

Generating random numbers with Swift

Just call this function and provide minimum and maximum range of number and you will get a random number.

eg.like randomNumber(MIN: 0, MAX: 10) and You will get number between 0 to 9.

func randomNumber(MIN: Int, MAX: Int)-> Int{
    return Int(arc4random_uniform(UInt32(MAX-MIN)) + UInt32(MIN));
}

Note:- You will always get output an Integer number.

Scrollbar without fixed height/Dynamic height with scrollbar

Flexbox is a modern alternative that lets you do this without fixed heights or JavaScript.

Setting display: flex; flex-direction: column; on the container and flex-shrink: 0; on the header and footer divs does the trick:

HTML:

<div id="body">
    <div id="head">
        <p>Dynamic size without scrollbar</p>
        <p>Dynamic size without scrollbar</p>
        <p>Dynamic size without scrollbar</p>  
    </div>
    <div id="content">
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
    </div>
    <div id="foot">
        <p>Fixed size without scrollbar</p>
        <p>Fixed size without scrollbar</p>
    </div>  
</div>

CSS:

#body {
    position: absolute;
    top: 150px;
    left: 150px;
    height: 300px;
    width: 500px;
    border: black dashed 2px;
    display: flex;
    flex-direction: column;
}

#head {
    border: green solid 1px;
    flex-shrink: 0;
}

#content{
    border: red solid 1px;
    overflow-y: auto;
    /*height: 100%;*/
}

#foot {
    border: blue solid 1px;
    height: 50px;
    flex-shrink: 0;
}

Property 'value' does not exist on type 'Readonly<{}>'

event.target is of type EventTarget which doesn't always have a value. If it's a DOM element you need to cast it to the correct type:

handleChange(event) {
    this.setState({value: (event.target as HTMLInputElement).value});
}

This will infer the "correct" type for the state variable as well though being explicit is probably better

Class file for com.google.android.gms.internal.zzaja not found

This error occurs only due to the difference in version. Whenever this kinda error occurs try to change the SDK versions, Gradle Build versions, or dependency version. If you are using

targetSdkVersion = 26
compileSdkVersion = 26
'com.android.tools.build:gradle:3.6.3'

then add this version for firebase dependencies.

implementation 'com.google.firebase:firebase-core:11.6.0'
implementation 'com.google.firebase:firebase-database:11.6.0'
implementation 'com.google.firebase:firebase-auth:11.6.0'

It works.

DataColumn Name from DataRow (not DataTable)

You can make it easier in your code (if you're doing this a lot anyway) by using an extension on the DataRow object, like:

static class Extensions
{
    public static string GetColumn(this DataRow Row, int Ordinal)
    {
        return Row.Table.Columns[Ordinal].ColumnName;
    }
}

Then call it using:

string MyColumnName = MyRow.GetColumn(5);

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

When I had an error Access Error: 404 -- Not Found I fixed it by doing the following:

  1. Open command prompt and type "netstat -aon" (without the quotes)
  2. Search for port 8080 and look at its PID number/code.
  3. Open Task Manager (CTRL+ALT+DELETE), go to Services tab, and find the service with the exact PID number. Then right click it and stop the process.

Image size (Python, OpenCV)

For me the easiest way is to take all the values returned by image.shape:

height, width, channels = img.shape

if you don't want the number of channels (useful to determine if the image is bgr or grayscale) just drop the value:

height, width, _ = img.shape

Jquery find nearest matching element

closest() only looks for parents, I'm guessing what you really want is .find()

$(this).closest('.row').children('.column').find('.inputQty').val();

Which type of folder structure should be used with Angular 2?

Here's mine

app
|
|-- shared (for html shared between modules)
|   |
|   |-- layouts
|   |   |
|   |   |-- default
|   |   |   |-- default.component.ts|html|scss|spec.ts
|   |   |   |-- default.module.ts
|   |   |
|   |   |-- fullwidth
|   |       |-- fullwidth.component.ts|html|scss|spec.ts
|   |       |-- fullwidth.module.ts
|   |
|   |-- components
|   |   |-- footer
|   |   |   |-- footer.component.ts|html|scss|spec.ts
|   |   |-- header
|   |   |   |-- header.component.ts|html|scss|spec.ts
|   |   |-- sidebar
|   |   |   |-- sidebar.component.ts|html|scss|spec.ts
|   |
|   |-- widgets
|   |   |-- card
|   |   |-- chart
|   |   |-- table
|   |
|   |-- shared.module.ts
|
|-- core (for code shared between modules)
|   |
|   |-- services
|   |-- guards
|   |-- helpers
|   |-- models
|   |-- pipes
|   |-- core.module.ts
|
|-- modules (each module contains its own set)
|   |
|   |-- dashboard
|   |-- users
|   |-- books
|       |-- components -> folders
|       |-- models
|       |-- guards
|       |-- books.service.ts
|       |-- books.module.ts
|
|-- material
|   |-- material.module.ts

Android ViewPager with bottom dots

My handmade solution:

In the layout:

<LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/dots"
        />

And in the Activity

private final static int NUM_PAGES = 5;
private ViewPager mViewPager;
private List<ImageView> dots;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // ...
    addDots();
}

public void addDots() {
    dots = new ArrayList<>();
    LinearLayout dotsLayout = (LinearLayout)findViewById(R.id.dots);

    for(int i = 0; i < NUM_PAGES; i++) {
        ImageView dot = new ImageView(this);
        dot.setImageDrawable(getResources().getDrawable(R.drawable.pager_dot_not_selected));

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );
        dotsLayout.addView(dot, params);

        dots.add(dot);
    }

    mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            selectDot(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    });
}

public void selectDot(int idx) {
    Resources res = getResources();
    for(int i = 0; i < NUM_PAGES; i++) {
        int drawableId = (i==idx)?(R.drawable.pager_dot_selected):(R.drawable.pager_dot_not_selected);
        Drawable drawable = res.getDrawable(drawableId);
        dots.get(i).setImageDrawable(drawable);
    }
}

Exclude property from type

I've found solution with declaring some variables and using spread operator to infer type:

interface XYZ {
  x: number;
  y: number;
  z: number;
}

declare var { z, ...xy }: XYZ;

type XY = typeof xy; // { x: number; y: number; }

It works, but I would be glad to see a better solution.

DIV :after - add content after DIV

Position your <div> absolutely at the bottom and don't forget to give div.A a position: relative - http://jsfiddle.net/TTaMx/

    .A {
        position: relative;
        margin: 40px 0;
        height: 40px;
        width: 200px;
        background: #eee;
    }

    .A:after {
        content: " ";
        display: block;
        background: #c00;
        height: 29px;
        width: 100%;

        position: absolute;
        bottom: -29px;
    }?

Click a button programmatically - JS

The other answers here rely on the user making an initial click (on the image). This is fine for the specifics of the OP detail but not necessarily the question title.

There is an answer here explaining how to do it by firing a click event on the button ( or any element ).

What evaluates to True/False in R?

This is documented on ?logical. The pertinent section of which is:

Details:

     ‘TRUE’ and ‘FALSE’ are reserved words denoting logical constants
     in the R language, whereas ‘T’ and ‘F’ are global variables whose
     initial values set to these.  All four are ‘logical(1)’ vectors.

     Logical vectors are coerced to integer vectors in contexts where a
     numerical value is required, with ‘TRUE’ being mapped to ‘1L’,
     ‘FALSE’ to ‘0L’ and ‘NA’ to ‘NA_integer_’.

The second paragraph there explains the behaviour you are seeing, namely 5 == 1L and 5 == 0L respectively, which should both return FALSE, where as 1 == 1L and 0 == 0L should be TRUE for 1 == TRUE and 0 == FALSE respectively. I believe these are not testing what you want them to test; the comparison is on the basis of the numerical representation of TRUE and FALSE in R, i.e. what numeric values they take when coerced to numeric.

However, only TRUE is guaranteed to the be TRUE:

> isTRUE(TRUE)
[1] TRUE
> isTRUE(1)
[1] FALSE
> isTRUE(T)
[1] TRUE
> T <- 2
> isTRUE(T)
[1] FALSE

isTRUE is a wrapper for identical(x, TRUE), and from ?isTRUE we note:

Details:
....

     ‘isTRUE(x)’ is an abbreviation of ‘identical(TRUE, x)’, and so is
     true if and only if ‘x’ is a length-one logical vector whose only
     element is ‘TRUE’ and which has no attributes (not even names).

So by the same virtue, only FALSE is guaranteed to be exactly equal to FALSE.

> identical(F, FALSE)
[1] TRUE
> identical(0, FALSE)
[1] FALSE
> F <- "hello"
> identical(F, FALSE)
[1] FALSE

If this concerns you, always use isTRUE() or identical(x, FALSE) to check for equivalence with TRUE and FALSE respectively. == is not doing what you think it is.

C library function to perform sort

qsort() is the function you're looking for. You call it with a pointer to your array of data, the number of elements in that array, the size of each element and a comparison function.

It does its magic and your array is sorted in-place. An example follows:

#include <stdio.h>
#include <stdlib.h>
int comp (const void * elem1, const void * elem2) 
{
    int f = *((int*)elem1);
    int s = *((int*)elem2);
    if (f > s) return  1;
    if (f < s) return -1;
    return 0;
}
int main(int argc, char* argv[]) 
{
    int x[] = {4,5,2,3,1,0,9,8,6,7};

    qsort (x, sizeof(x)/sizeof(*x), sizeof(*x), comp);

    for (int i = 0 ; i < 10 ; i++)
        printf ("%d ", x[i]);

    return 0;
}

Get a random item from a JavaScript array

1. solution: define Array prototype

Array.prototype.random = function () {
  return this[Math.floor((Math.random()*this.length))];
}

that will work on inline arrays

[2,3,5].random()

and of course predefined arrays

list = [2,3,5]
list.random()

2. solution: define custom function that accepts list and returns element

get_random = function (list) {
  return list[Math.floor((Math.random()*list.length))];
} 

get_random([2,3,5])

Oracle DB : java.sql.SQLException: Closed Connection

It means the connection was successfully established at some point, but when you tried to commit right there, the connection was no longer open. The parameters you mentioned sound like connection pool settings. If so, they're unrelated to this problem. The most likely cause is a firewall between you and the database that is killing connections after a certain amount of idle time. The most common fix is to make your connection pool run a validation query when a connection is checked out from it. This will immediately identify and evict dead connnections, ensuring that you only get good connections out of the pool.

Xcode stuck on Indexing

Had similar problem in Xcode 6.4. The progress bar indicated that "Indexing" was "Paused". Tried deleting project.xcworkspace, then deleting Derived Data as described above. Did not appear to help. Noting that the posts above also suggest fixing warnings, and since I had inherited this huge project with 180 warnings, I said to myself, "What the hell this looks like a good day to fix warnings". As I was fixing warnings, a half hour later, I noticed that the "Indexing" progress bar had increased from 10% to about 20%. An hour later, it was at 50%, then another hour to 80%, then after another half hour it was done! Conclusion: Add "take a long lunch or a nap" to the above suggestions.

How to get the list of files in a directory in a shell script?

This is a way to do it where the syntax is simpler for me to understand:

yourfilenames=`ls ./*.txt`
for eachfile in $yourfilenames
do
   echo $eachfile
done

./ is the current working directory but could be replaced with any path
*.txt returns anything.txt
You can check what will be listed easily by typing the ls command straight into the terminal.

Basically, you create a variable yourfilenames containing everything the list command returns as a separate element, and then you loop through it. The loop creates a temporary variable eachfile that contains a single element of the variable it's looping through, in this case a filename. This isn't necessarily better than the other answers, but I find it intuitive because I'm already familiar with the ls command and the for loop syntax.

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

I have made a more complete middleware suitable for express or connect. It supports OPTIONS requests for preflight checking. Note that it will allow CORS access to anything, you might want to put in some checks if you want to limit access.

app.use(function(req, res, next) {
    var oneof = false;
    if(req.headers.origin) {
        res.header('Access-Control-Allow-Origin', req.headers.origin);
        oneof = true;
    }
    if(req.headers['access-control-request-method']) {
        res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);
        oneof = true;
    }
    if(req.headers['access-control-request-headers']) {
        res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
        oneof = true;
    }
    if(oneof) {
        res.header('Access-Control-Max-Age', 60 * 60 * 24 * 365);
    }

    // intercept OPTIONS method
    if (oneof && req.method == 'OPTIONS') {
        res.send(200);
    }
    else {
        next();
    }
});

How to sort a Pandas DataFrame by index?

Dataframes have a sort_index method which returns a copy by default. Pass inplace=True to operate in place.

import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())

Gives me:

     A
1    4
29   2
100  1
150  5
234  3

How to $http Synchronous call with AngularJS

Here's a way you can do it asynchronously and manage things like you would normally. Everything is still shared. You get a reference to the object that you want updated. Whenever you update that in your service, it gets updated globally without having to watch or return a promise. This is really nice because you can update the underlying object from within the service without ever having to rebind. Using Angular the way it's meant to be used. I think it's probably a bad idea to make $http.get/post synchronous. You'll get a noticeable delay in the script.

app.factory('AssessmentSettingsService', ['$http', function($http) {
    //assessment is what I want to keep updating
    var settings = { assessment: null };

    return {
        getSettings: function () {
             //return settings so I can keep updating assessment and the
             //reference to settings will stay in tact
             return settings;
        },
        updateAssessment: function () {
            $http.get('/assessment/api/get/' + scan.assessmentId).success(function(response) {
                //I don't have to return a thing.  I just set the object.
                settings.assessment = response;
            });
        }
    };
}]);

    ...
        controller: ['$scope', '$http', 'AssessmentSettingsService', function ($scope, as) {
            $scope.settings = as.getSettings();
            //Look.  I can even update after I've already grabbed the object
            as.updateAssessment();

And somewhere in a view:

<h1>{{settings.assessment.title}}</h1>

Bootstrap get div to align in the center

When I align elements in center I use the bootstrap class text-center:

<div class="text-center">Centered content goes here</div>

How to use glob() to find files recursively?

That one uses fnmatch or regular expression:

import fnmatch, os

def filepaths(directory, pattern):
    for root, dirs, files in os.walk(directory):
        for basename in files:
            try:
                matched = pattern.match(basename)
            except AttributeError:
                matched = fnmatch.fnmatch(basename, pattern)
            if matched:
                yield os.path.join(root, basename)

# usage
if __name__ == '__main__':
    from pprint import pprint as pp
    import re
    path = r'/Users/hipertracker/app/myapp'
    pp([x for x in filepaths(path, re.compile(r'.*\.py$'))])
    pp([x for x in filepaths(path, '*.py')])

jQuery + client-side template = "Syntax error, unrecognized expression"

Turns out string starting with a newline (or anything other than "<") is not considered HTML string in jQuery 1.9

http://stage.jquery.com/upgrade-guide/1.9/#jquery-htmlstring-versus-jquery-selectorstring

How to convert existing non-empty directory into a Git working directory and push files to a remote repository

Here's my solution if you created the repository with some default readme file or license

git init
git add -A
git commit -m "initial commit"   
git remote add origin https://<git-userName>@github.com/xyz.git //Add your username so it will avoid asking username each time before you push your code
git fetch
git pull https://github.com/xyz.git <branch>
git push origin <branch> 

Binding a Button's visibility to a bool value in ViewModel

Generally there are two ways to do it, a converter class or a property in the Viewmodel that essentially converts the value for you.

I tend to use the property approach if it is a one off conversion. If you want to reuse it, use the converter. Below, find an example of the converter:

<ValueConversion(GetType(Boolean), GetType(Visibility))> _
Public Class BoolToVisibilityConverter
    Implements IValueConverter

    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert

        If value IsNot Nothing Then
            If value = True Then 
                Return Visibility.Visible
            Else
                Return Visibility.Collapsed
            End If
        Else
            Return Visibility.Collapsed
        End If
    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New NotImplementedException
    End Function
End Class

A ViewModel property method would just check the boolean property value, and return a visibility based on that. Be sure to implement INotifyPropertyChanged and call it on both the Boolean and Visibility properties to updated properly.

Default passwords of Oracle 11g?

Login into the machine as oracle login user id( where oracle is installed)..

  1. Add ORACLE_HOME = <Oracle installation Directory> in Environment variable

  2. Open a command prompt

  3. Change the directory to %ORACLE_HOME%\bin

  4. type the command sqlplus /nolog

  5. SQL> connect /as sysdba

  6. SQL> alter user SYS identified by "newpassword";

One more check, while oracle installation and database confiuration assistant setup, if you configure any database then you might have given password and checked the same password for all other accounts.. If so, then you try with the password which you have given in your database configuration assistant setup.

Hope this will work for you..

How to send email from MySQL 5.1

I would be very concerned about putting the load of sending e-mails on my database server (small though it may be). I might suggest one of these alternatives:

  1. Have application logic detect the need to send an e-mail and send it.
  2. Have a MySQL trigger populate a table that queues up the e-mails to be sent and have a process monitor that table and send the e-mails.

How to get english language word database?

WordNet database might be helpful. I once worked on a Firefox add-on which deals with words and all kinds of simple to complicated associations between them and stuff. Looks like WordNet will be very much useful to you.

Here it is in MySQL format. And this one (web-archived link) uses Wordnet v3.0 data, rather than the older Wordnet 2.0 data.

How to disable HTML button using JavaScript?

<button disabled=true>text here</button>

You can still use an attribute. Just use the 'disabled' attribute instead of 'value'.

How to change scroll bar position with CSS?

Try this out. Hope this helps

<div id="single" dir="rtl">
    <div class="common">Single</div>
</div>

<div id="both" dir="ltr">
    <div class="common">Both</div>
</div>



#single, #both{
    width: 100px;
    height: 100px;
    overflow: auto;
    margin: 0 auto;
    border: 1px solid gray;
}


.common{
    height: 150px;
    width: 150px;
}

Ruby convert Object to Hash

Implement #to_hash?

class Gift
  def to_hash
    hash = {}
    instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) }
    hash
  end
end


h = Gift.new("Book", 19).to_hash

Matplotlib tight_layout() doesn't take into account figure suptitle

You could manually adjust the spacing using plt.subplots_adjust(top=0.85):

import numpy as np
import matplotlib.pyplot as plt

f = np.random.random(100)
g = np.random.random(100)
fig = plt.figure()
fig.suptitle('Long Suptitle', fontsize=24)
plt.subplot(121)
plt.plot(f)
plt.title('Very Long Title 1', fontsize=20)
plt.subplot(122)
plt.plot(g)
plt.title('Very Long Title 2', fontsize=20)
plt.subplots_adjust(top=0.85)
plt.show()

How to change Apache Tomcat web server port number

You need to edit the Tomcat/conf/server.xml and change the connector port. The connector setting should look something like this:

<Connector port="8080" maxHttpHeaderSize="8192"
           maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
           enableLookups="false" redirectPort="8443" acceptCount="100"
           connectionTimeout="20000" disableUploadTimeout="true" />

Just change the connector port from default 8080 to another valid port number.

Can I use jQuery to check whether at least one checkbox is checked?

$("#frmTest").submit(function(){
    var checked = $("#frmText input:checked").length > 0;
    if (!checked){
        alert("Please check at least one checkbox");
        return false;
    }
});

How to set Java SDK path in AndroidStudio?

C:\Program Files\Android\Android Studio\jre\bin>java -version
openjdk version "1.8.0_76-release"
OpenJDK Runtime Environment (build 1.8.0_76-release-b03)
OpenJDK 64-Bit Server VM (build 25.76-b03, mixed mode)

Somehow the Studio installer would install another version under:

C:\Program Files\Android\Android Studio\jre\jre\bin>java -version
openjdk version "1.8.0_76-release"
OpenJDK Runtime Environment (build 1.8.0_76-release-b03)
OpenJDK 64-Bit Server VM (build 25.76-b03, mixed mode)

where the latest version was installed the Java DevKit installer in:

C:\Program Files\Java\jre1.8.0_121\bin>java -version
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)

Need to clean up the Android Studio so it would use the proper latest 1.8.0 versions.

According to How to set Java SDK path in AndroidStudio? one could override with a specific JDK but when I renamed

C:\Program Files\Android\Android Studio\jre\jre\

to:

C:\Program Files\Android\Android Studio\jre\oldjre\

And restarted Android Studio, it would complain that the jre was invalid. When I tried to aecify an JDK to pick the one in C:\Program Files\Java\jre1.8.0_121\bin or:

C:\Program Files\Java\jre1.8.0_121\

It said that these folders are invalid. So I guess that the embedded version must have some special purpose.

ValueError : I/O operation on closed file

I had this problem when I was using an undefined variable inside the with open(...) as f:. I removed (or I defined outside) the undefined variable and the problem disappeared.

How can I create a marquee effect?

The accepted answers animation does not work on Safari, I've updated it using translate instead of padding-left which makes for a smoother, bulletproof animation.

Also, the accepted answers demo fiddle has a lot of unnecessary styles.

So I created a simple version if you just want to cut and paste the useful code and not spend 5 mins clearing through the demo.

http://jsfiddle.net/e8ws12pt/

_x000D_
_x000D_
.marquee {_x000D_
    margin: 0 auto;_x000D_
    white-space: nowrap;_x000D_
    overflow: hidden;_x000D_
    box-sizing: border-box;_x000D_
    padding: 0;_x000D_
    height: 16px;_x000D_
    display: block;_x000D_
}_x000D_
.marquee span {_x000D_
    display: inline-block;_x000D_
    text-indent: 0;_x000D_
    overflow: hidden;_x000D_
    -webkit-transition: 15s;_x000D_
    transition: 15s;_x000D_
    -webkit-animation: marquee 15s linear infinite;_x000D_
    animation: marquee 15s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes marquee {_x000D_
    0% { transform: translate(100%, 0); -webkit-transform: translateX(100%); }_x000D_
    100% { transform: translate(-100%, 0); -webkit-transform: translateX(-100%); }_x000D_
}
_x000D_
<p class="marquee"><span>Simple CSS Marquee - Lorem ipsum dolor amet tattooed squid microdosing taiyaki cardigan polaroid single-origin coffee iPhone. Edison bulb blue bottle neutra shabby chic. Kitsch affogato you probably haven't heard of them, keytar forage plaid occupy pitchfork. Enamel pin crucifix tilde fingerstache, lomo unicorn chartreuse plaid XOXO yr VHS shabby chic meggings pinterest kickstarter.</span></p>
_x000D_
_x000D_
_x000D_

How do I remove the space between inline/inline-block elements?

I had this problem right now and from font-size:0; I've found that in Internet Explorer 7 the problem remains because Internet Explorer thinks "Font Size 0?!?! WTF are you crazy man?" - So, in my case I've Eric Meyer's CSS reset and with font-size:0.01em; I have a difference of 1 pixel from Internet Explorer 7 to Firefox 9, so, I think this can be a solution.

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

I was finding the same error complaining about mixing google play services version when switching from 8.3 to 8.4. Bizarrely I saw reference to the app-measurement lib which I wasn't using.

I thought maybe one of my app's dependencies was referencing the older version so I ran ./gradlew app:dependencies to find the offending library (non were).

But at the top of task output I found a error message saying that the google plugin could not be found and defaulting to google play services 8.3. I used the sample project @TheYann linked to compare. My setup was identical except I applied the apply plugin: 'com.google.gms.google-services' at the top my app's build.gradle file. I moved to bottom of the file and that fixed the gradle compile error.

for or while loop to do something n times

but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?

That is what xrange(n) is for. It avoids creating a list of numbers, and instead just provides an iterator object.

In Python 3, xrange() was renamed to range() - if you want a list, you have to specifically request it via list(range(n)).

Saving results with headers in Sql Server Management Studio

Another possibility is to use the clipboard to copy and paste the results directly into Excel. Just be careful with General type Excel columns, as they can sometimes have unpredictable results, depending on your data. CTL-A anywhere in the result grid, and then right-click:

enter image description here

If you have trouble with Excel's General format doing undesired conversions, select the blank columns in Excel before you paste and change the format to "text".

SQL - Select first 10 rows only?

SELECT *  
  FROM (SELECT ROW_NUMBER () OVER (ORDER BY user_id) user_row_no, a.* FROM temp_emp a)  
 WHERE user_row_no > 1 and user_row_no <11  

This worked for me.If i may,i have few useful dbscripts that you can have look at

Useful Dbscripts

MySQL wait_timeout Variable - GLOBAL vs SESSION

As noted by Riedsio, the session variables do not change after connecting unless you specifically set them; setting the global variable only changes the session value of your next connection.

For example, if you have 100 connections and you lower the global wait_timeout then it will not affect the existing connections, only new ones after the variable was changed.

Specifically for the wait_timeout variable though, there is a twist. If you are using the mysql client in the interactive mode, or the connector with CLIENT_INTERACTIVE set via mysql_real_connect() then you will see the interactive_timeout set for @@session.wait_timeout

Here you can see this demonstrated:

> ./bin/mysql -Bsse 'select @@session.wait_timeout, @@session.interactive_timeout, @@global.wait_timeout, @@global.interactive_timeout' 
70      60      70      60

> ./bin/mysql -Bsse 'select @@wait_timeout'                                                                                                 
70

> ./bin/mysql                                                                                                                               
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 5.7.12-5 MySQL Community Server (GPL)

Copyright (c) 2009-2016 Percona LLC and/or its affiliates
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> select @@wait_timeout;
+----------------+
| @@wait_timeout |
+----------------+
|             60 |
+----------------+
1 row in set (0.00 sec)

So, if you are testing this using the client it is the interactive_timeout that you will see when connecting and not the value of wait_timeout

how to concat two columns into one with the existing column name in mysql?

Instead of getting all the table columns using * in your sql statement, you use to specify the table columns you need.

You can use the SQL statement something like:

SELECT CONCAT(FIRSTNAME, ' ', LASTNAME) AS FIRSTNAME FROM customer;

BTW, why couldn't you use FullName instead of FirstName? Like this:

SELECT CONCAT(FIRSTNAME, ' ', LASTNAME) AS 'CUSTOMER NAME' FROM customer;

Easy way to test an LDAP User's Credentials

ldapwhoami -vvv -h <hostname> -p <port> -D <binddn> -x -w <passwd>, where binddn is the DN of the person whose credentials you are authenticating.

On success (i.e., valid credentials), you get Result: Success (0). On failure, you get ldap_bind: Invalid credentials (49).

java Arrays.sort 2d array

It is really simple, there are just some syntax you have to keep in mind.

Arrays.sort(contests, (a, b) -> Integer.compare(a[0],b[0]));//increasing order ---1

Arrays.sort(contests, (b, a) -> Integer.compare(b[0],a[0]));//increasing order ---2

Arrays.sort(contests, (a, b) -> Integer.compare(b[0],a[0]));//decreasing order ---3

Arrays.sort(contests, (b, a) -> Integer.compare(a[0],b[0]));//decreasing order ---4

If you notice carefully, then it's the change in the order of 'a' and 'b' that affects the result. For line 1, the set is of (a,b) and Integer.compare(a[0],b[0]), so it is increasing order. Now if we change the order of a and b in any one of them, suppose the set of (a,b) and Integer.compare(b[0],a[0]) as in line 3, we get decreasing order.

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

I had the same warning using the raster package.

> my_mask[my_mask[] != 1] <- NA
Error: cannot allocate vector of size 5.4 Gb

The solution is really simple and consist in increasing the storage capacity of R, here the code line:

##To know the current storage capacity
> memory.limit()
[1] 8103
## To increase the storage capacity
> memory.limit(size=56000)
[1] 56000    
## I did this to increase my storage capacity to 7GB

Hopefully, this will help you to solve the problem Cheers

How to remove a field completely from a MongoDB document?

Because I kept finding this page when looking for a way to remove a field using MongoEngine, I guess it might be helpful to post the MongoEngine way here too:

Example.objects.all().update(unset__tags__words=1)

How to get text and a variable in a messagebox

I wanto to display the count of rows in the excel sheet after the filter option has been applied.

So I declared the count of last rows as a variable that can be added to the Msgbox

Sub lastrowcall()
Dim hm As Worksheet
Dim dm As Worksheet
Set dm = ActiveWorkbook.Sheets("datecopy")
Set hm = ActiveWorkbook.Sheets("Home")
Dim lngStart As String, lngEnd As String
lngStart = hm.Range("E23").Value
lngEnd = hm.Range("E25").Value
Dim last_row As String
last_row = dm.Cells(Rows.Count, 1).End(xlUp).Row

MsgBox ("Number of test results between the selected dates " + lngStart + " 
and " + lngEnd + " are " + last_row + ". Please Select Yes to continue 
Analysis")


End Sub

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

The getPosts() function seems to be expecting $con to be global, but you're not declaring it as such.

A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.

How to make a great R reproducible example

Guidelines:


Your main objective in crafting your questions should be to make it as easy as possible for readers to understand and reproduce your problem on their systems. To do so:

  1. Provide input data
  2. Provide expected output
  3. Explain your problem succinctly
    • if you have over 20 lines of text + code, you can probably go back and simplify
    • simplify your code as much as possible while preserving the problem/error

This does take some work, but it seems like a fair trade-off since you ask others to do work for you.

Providing Data:


Built-in Data Sets

The best option by far is to rely on built-in datasets. This makes it very easy for others to work on your problem. Type data() at the R prompt to see what data is available to you. Some classic examples:

  • iris
  • mtcars
  • ggplot2::diamonds (external package, but almost everyone has it)

Inspect the built-in datasets to find one suitable for your problem.

If you can rephrase your problem to use the built-in datasets, you are much more likely to get good answers (and upvotes).

Self Generated Data

If your problem is specific to a type of data that is not represented in the existing data sets, then provide the R code that generates the smallest possible dataset that your problem manifests itself on. For example

set.seed(1)  # important to make random data reproducible
myData <- data.frame(a=sample(letters[1:5], 20, rep=T), b=runif(20))

Someone trying to answer my question can copy/paste those two lines and start working on the problem immediately.

dput

As a last resort, you can use dput to transform a data object to R code (e.g. dput(myData)). I say as a "last resort" because the output of dput is often fairly unwieldy, annoying to copy-paste, and obscures the rest of your question.

Provide Expected Output:


Someone once said:

A picture of expected output is worth 1000 words

-- a sage person

If you can add something like "I expected to get this result":

   cyl   mean.hp
1:   6 122.28571
2:   4  82.63636
3:   8 209.21429

to your question, people are much more likely to understand what you are trying to do quickly. If your expected result is large and unwieldy, then you probably haven't thought enough about how to simplify your problem (see next).

Explain Your Problem Succinctly


The main thing to do is simplify your problem as much as possible before you ask your question. Re-framing the problem to work with the built-in datasets will help a lot in this regard. You will also often find that just by going through the process of simplification, you will answer your own problem.

Here are some examples of good questions:

In both cases, the user's problems are almost certainly not with the simple examples they provide. Rather they abstracted the nature of their problem and applied it to a simple data set to ask their question.

Why Yet Another Answer To This Question?


This answer focuses on what I think is the best practice: use built-in data sets and provide what you expect as a result in a minimal form. The most prominent answers focus on other aspects. I don't expect this answer to rising to any prominence; this is here solely so that I can link to it in comments to newbie questions.

Python script to copy text to clipboard

GTK3:

#!/usr/bin/python3

from gi.repository import Gtk, Gdk


class Hello(Gtk.Window):

    def __init__(self):
        super(Hello, self).__init__()
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text("hello world", -1)
        Gtk.main_quit()


def main():
    Hello()
    Gtk.main()

if __name__ == "__main__":
    main()

Best practices with STDIN in Ruby?

while STDIN.gets
  puts $_
end

while ARGF.gets
  puts $_
end

This is inspired by Perl:

while(<STDIN>){
  print "$_\n"
}

How to put an image next to each other

Change div to span. And space the icons using &nbsp; HTML

 <div class="nav3" style="height:705px;">
 <span class="icons"><a href="http://www.facebook.com/"><img src="images/facebook.png"></a>
 </span>&nbsp;&nbsp;&nbsp;
 <span class="icons"><a href="https://twitter.com"><img src="images/twitter.png"></a>
 </span>
 </div>

CSS

.nav3 {
background-color: #E9E8C7;
height: auto;
width: 150px;
float: left;
padding-left: 20px;
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
color: #333333;
padding-top: 20px;
padding-right: 20px;
}

.icons{
display:inline-block;
width: 64px; 
height: 64px; 
}

 a.icons:hover {
 background: #C93;
 }

span does not break line, div does.

How do I make a fixed size formatted string in python?

Sure, use the .format method. E.g.,

print('{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34))

will print

xxx        123    98.00
yyyy         3     1.00
zz          42   123.34

You can adjust the field sizes as desired. Note that .format works independently of print to format a string. I just used print to display the strings. Brief explanation:

10s format a string with 10 spaces, left justified by default

3d format an integer reserving 3 spaces, right justified by default

7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.

There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.

Update for f-string mode. E.g.,

text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d}  {other_number:7.2f}')

For right alignment

print(f'{text:>10} {number:3d}  {other_number:7.2f}')

How do I change the ID of a HTML element with JavaScript?

It does work in Firefox (including 2.0.0.20). See http://jsbin.com/akili (add /edit to the url to edit):

<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>

The first click changes the id to "two", the second click errors because the element with id="one" now can't be found!

Perhaps you have another element already with id="two" (FYI you can't have more than one element with the same id).

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

I would start by adding the following dependency:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.1.4.Final</version>
</dependency>

and

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>5.2.3.Final</version>
</dependency>

UPDATE: Or simply add the following dependency.

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

This worked for me.

app.get('/', function (req, res) {

    res.header("Access-Control-Allow-Origin", "*");
    res.send('hello world')
})

You can change * to fit your needs. Hope this can help.

Compare two different files line by line in python

Yet another example...

from __future__ import print_function #Only for Python2

with open('file1.txt') as f1, open('file2.txt') as f2, open('outfile.txt', 'w') as outfile:
    for line1, line2 in zip(f1, f2):
        if line1 == line2:
            print(line1, end='', file=outfile)

And if you want to eliminate common blank lines, just change the if statement to:

if line1.strip() and line1 == line2:

.strip() removes all leading and trailing whitespace, so if that's all that's on a line, it will become an empty string "", which is considered false.

Get all inherited classes of an abstract class

This is such a common problem, especially in GUI applications, that I'm surprised there isn't a BCL class to do this out of the box. Here's how I do it.

public static class ReflectiveEnumerator
{
    static ReflectiveEnumerator() { }

    public static IEnumerable<T> GetEnumerableOfType<T>(params object[] constructorArgs) where T : class, IComparable<T>
    {
        List<T> objects = new List<T>();
        foreach (Type type in 
            Assembly.GetAssembly(typeof(T)).GetTypes()
            .Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(T))))
        {
            objects.Add((T)Activator.CreateInstance(type, constructorArgs));
        }
        objects.Sort();
        return objects;
    }
}

A few notes:

  • Don't worry about the "cost" of this operation - you're only going to be doing it once (hopefully) and even then it's not as slow as you'd think.
  • You need to use Assembly.GetAssembly(typeof(T)) because your base class might be in a different assembly.
  • You need to use the criteria type.IsClass and !type.IsAbstract because it'll throw an exception if you try to instantiate an interface or abstract class.
  • I like forcing the enumerated classes to implement IComparable so that they can be sorted.
  • Your child classes must have identical constructor signatures, otherwise it'll throw an exception. This typically isn't a problem for me.

Bootstrap 3 and Youtube in Modal

For Bootstrap 4, which handles videos, images and pages...

http://jsfiddle.net/c4j5pzua/

_x000D_
_x000D_
$('a[data-modal]').on('click',function(){_x000D_
 var $page = $(this).data('page');_x000D_
 var $image = $(this).data('image');_x000D_
 var $video = $(this).data('video');_x000D_
 var $title = $(this).data('title');_x000D_
 var $size = $(this).data('size');_x000D_
 $('#quickview .modal-title').text($title);_x000D_
 if ($size) { $('#quickview .modal-dialog').addClass('modal-'+$size); }_x000D_
 if ($image) {_x000D_
  $('#quickview .modal-body').html('<div class="text-center"><img class="img-fluid" src="'+$image+'" alt="'+$title+'"></div>');_x000D_
 } else if ($video) {_x000D_
  $('#quickview .modal-body').html('<div class="embed-responsive embed-responsive-16by9"><iframe class="embed-responsive-item" src="https://www.youtube-nocookie.com/embed/'+$video+'?autoplay=1" allowfullscreen></iframe></div>');_x000D_
 }_x000D_
 if ($page) {_x000D_
  $('#quickview .modal-body').load($page,function(){_x000D_
   $('#quickview').modal({show:true});_x000D_
  });_x000D_
 } else {_x000D_
  $('#quickview').modal({show:true});_x000D_
 }_x000D_
 $('#quickview').on('hidden.bs.modal', function(){_x000D_
  $('#quickview .modal-title').text('');_x000D_
  $('#quickview .modal-body').html('');_x000D_
  if ($size) { $('#quickview .modal-dialog').removeClass('modal-'+$size); }_x000D_
 });_x000D_
});
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>_x000D_
_x000D_
<div class="container my-4">_x000D_
_x000D_
<h3 class="mb-4">Bootstrap 4 Modal YouTube Videos, Images & Pages</h3>_x000D_
_x000D_
<a href="javascript:;" class="btn btn-primary" data-modal data-video="zpOULjyy-n8" data-title="Video Title" data-size="xl">Video</a>_x000D_
_x000D_
<a href="javascript:;" class="btn btn-primary" data-modal data-image="https://v4-alpha.getbootstrap.com/assets/brand/bootstrap-social-logo.png" data-title="Image Title" data-size="">Image</a>_x000D_
_x000D_
<a href="javascript:;" class="btn btn-primary" data-modal data-page="https://getbootstrap.com" data-title="Page Title" data-size="lg">Page *</a>_x000D_
_x000D_
<p class="mt-4">* Clicking this will break it, but it'll work using a local page!</p>_x000D_
_x000D_
</div>_x000D_
_x000D_
<div class="modal fade" id="quickview" tabindex="-1" role="dialog" aria-labelledby="quickview" aria-hidden="true">_x000D_
<div class="modal-dialog modal-dialog-scrollable modal-dialog-centered" role="document">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<h5 class="modal-title">Title</h5>_x000D_
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>_x000D_
</div>_x000D_
<div class="modal-body"></div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

iOS 7 UIBarButton back button arrow color

You can set the color on the entire app navigation's bar using the method

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:
(NSDictionary *)launchOptions{
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
}

Auto height of div

According to this, you need to assign a height to the element in which the div is contained in order for 100% height to work. Does that work for you?

How do I REALLY reset the Visual Studio window layout?

Have you tried this? In Visual Studio go to Tools > Import and Export Settings > Reset all settings

Be sure you back up your settings before you do this. I made the mistake of trying this to fix an issue and didn't realize it would undo all my appearance settings and toolbars as well. Took a lot of time to get back to the way I like things.

Adding padding to a tkinter widget only on one side

The padding options padx and pady of the grid and pack methods can take a 2-tuple that represent the left/right and top/bottom padding.

Here's an example:

import tkinter as tk

class MyApp():
    def __init__(self):
        self.root = tk.Tk()
        l1 = tk.Label(self.root, text="Hello")
        l2 = tk.Label(self.root, text="World")
        l1.grid(row=0, column=0, padx=(100, 10))
        l2.grid(row=1, column=0, padx=(10, 100)) 

app = MyApp()
app.root.mainloop()

How to change a TextView's style at runtime

Like Jonathan suggested, using textView.setTextTypeface works, I just used it in an app a few seconds ago.

textView.setTypeface(null, Typeface.BOLD); // Typeface.NORMAL, Typeface.ITALIC etc.

How to set session timeout dynamically in Java web applications?

As another anwsers told, you can change in a Session Listener. But you can change it directly in your servlet, for example.

getRequest().getSession().setMaxInactiveInterval(123);

Is there a job scheduler library for node.js?

I am the auhor of node-runnr . It have a very simple approach to create job. Also its very easy and clear to declare time and interval. For example, to execute a job at every 10min 20sec,

Runnr.addIntervalJob('10:20', function(){...}, 'myjob')

To do a job at 10am and 3pm daily,

Runnr.addDailyJob(['10:0:0', '15:0:0'], function(){...}, 'myjob')

Its that simple. For further detail: https://github.com/Saquib764/node-runnr

shell script. how to extract string using regular expressions

One way would be with sed. For example:

echo $name | sed -e 's?http://www\.??'

Normally the sed regular expressions are delimited by `/', but you can use '?' since you're searching for '/'. Here's another bash trick. @DigitalTrauma's answer reminded me that I ought to suggest it. It's similar:

echo ${name#http://www.}

(DigitalTrauma also gets credit for reminding me that the "http://" needs to be handled.)

Can I style an image's ALT text with CSS?

as this question is the first result at search engines

There are a problem with the selected -and right by the way- solution, is that if you want to add style that will apply to images like ( borders for example ) .

for example :

_x000D_
_x000D_
img {_x000D_
  color:#fff;_x000D_
  border: 1px solid black;_x000D_
  padding: 5px;_x000D_
  background-color: #ccc;_x000D_
}
_x000D_
<img src="http://badsrc.com/blah" alt="BLAH BLAH BLAH" /> <hr />_x000D_
<img src="https://cdn4.iconfinder.com/data/icons/miu-square-flat-social/60/stackoverflow-square-social-media-128.png" alt="BLAH BLAH BLAH" />
_x000D_
_x000D_
_x000D_

as you can see, all of images will apply the same style


there is another approach to easily work around such an issue, using onerror and injecting some special class to deal with the interrupted images :

_x000D_
_x000D_
.invalidImageSrc {_x000D_
  color:#fff;_x000D_
  border: 1px solid black;_x000D_
  padding: 5px;_x000D_
  background-color: #ccc;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
_x000D_
<img onerror="$(this).addClass('invalidImageSrc')" src="http://badsrc.com/blah" alt="BLAH BLAH BLAH" /> <hr />_x000D_
<img onerror="$(this).addClass('invalidImageSrc')" src="https://cdn4.iconfinder.com/data/icons/miu-square-flat-social/60/stackoverflow-square-social-media-128.png" alt="BLAH BLAH BLAH" />
_x000D_
_x000D_
_x000D_

How to get absolute value from double - c-language

Use fabs() (in math.h) to get absolute-value for double:

double d1 = fabs(-3.8951);

How do I perform HTML decoding/encoding using Python/Django?

For html encoding, there's cgi.escape from the standard library:

>> help(cgi.escape)
cgi.escape = escape(s, quote=None)
    Replace special characters "&", "<" and ">" to HTML-safe sequences.
    If the optional flag quote is true, the quotation mark character (")
    is also translated.

For html decoding, I use the following:

import re
from htmlentitydefs import name2codepoint
# for some reason, python 2.5.2 doesn't have this one (apostrophe)
name2codepoint['#39'] = 39

def unescape(s):
    "unescape HTML code refs; c.f. http://wiki.python.org/moin/EscapingHtml"
    return re.sub('&(%s);' % '|'.join(name2codepoint),
              lambda m: unichr(name2codepoint[m.group(1)]), s)

For anything more complicated, I use BeautifulSoup.

How to use execvp()

The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.

For example:

char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;

execvp(cmd, argv); //This will run "ls -la" as if it were a command

Print an ArrayList with a for-each loop

import java.util.ArrayList;
import java.util.List;

class ArrLst{

    public static void main(String args[]){

        List l=new ArrayList();
        l.add(10);
        l.add(11);
        l.add(12);
        l.add(13);
        l.add(14);
        l.forEach((a)->System.out.println(a));
    }
}

Determine what user created objects in SQL Server

If you need a small and specific mechanism, you can search for DLL Triggers info.

Difference between Pragma and Cache-Control headers?

There is no difference, except that Pragma is only defined as applicable to the requests by the client, whereas Cache-Control may be used by both the requests of the clients and the replies of the servers.

So, as far as standards go, they can only be compared from the perspective of the client making a requests and the server receiving a request from the client. The http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32 defines the scenario as follows:

HTTP/1.1 caches SHOULD treat "Pragma: no-cache" as if the client had sent "Cache-Control: no-cache". No new Pragma directives will be defined in HTTP.

  Note: because the meaning of "Pragma: no-cache as a response
  header field is not actually specified, it does not provide a
  reliable replacement for "Cache-Control: no-cache" in a response

The way I would read the above:

  • if you're writing a client and need no-cache:

    • just use Pragma: no-cache in your requests, since you may not know if Cache-Control is supported by the server;
    • but in replies, to decide on whether to cache, check for Cache-Control
  • if you're writing a server:

    • in parsing requests from the clients, check for Cache-Control; if not found, check for Pragma: no-cache, and execute the Cache-Control: no-cache logic;
    • in replies, provide Cache-Control.

Of course, reality might be different from what's written or implied in the RFC!

Could not resolve placeholder in string value

I got same error in my Micro-service, whenever you declare @Value annotation in program i.e @Value("${project.api.key}")

make sure that your application.properties file with same values should not be blank project.api.key= add some values

MostIMP :otherwise it will throw error "Error creating bean with name 'ServiceFTP': Injection of autowired dependencies"

How to pad a string to a fixed length with spaces in Python?

First check to see if the string's length needs to be shortened, then add spaces until it is as long as the field length.

fieldLength = 15
string1 = string1[0:15] # If it needs to be shortened, shorten it
while len(string1) < fieldLength:
    rand += " "

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

I'll leave the discussion of the difference between Build Tools, Platform Tools, and Tools to others. From a practical standpoint, you only need to know the answer to your second question:

Which version should be used?

Answer: Use the most recent version.

For those using Android Studio with Gradle, the buildToolsVersion has to be set in the build.gradle (Module: app) file.

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    ...
}

Where do I get the most recent version number of Build Tools?

Open the Android SDK Manager.

  • In Android Studio go to Tools > Android > SDK Manager > Appearance & Behavior > System Settings > Android SDK
  • Choose the SDK Tools tab.
  • Select Android SDK Build Tools from the list
  • Check Show Package Details.

The last item will show the most recent version.

enter image description here

Make sure it is installed and then write that number as the buildToolsVersion in build.gradle (Module: app).

Define the selected option with the old input in Laravel / Blade

<option value="{{ $key }}" {{ Input::old('title') == $key ? 'selected="selected"' : '' }}>{{ $val }}</option>

I get exception when using Thread.sleep(x) or wait()

As other users have said you should surround your call with a try{...} catch{...} block. But since Java 1.5 was released, there is TimeUnit class which do the same as Thread.sleep(millis) but is more convenient. You can pick time unit for sleep operation.

try {
    TimeUnit.NANOSECONDS.sleep(100);
    TimeUnit.MICROSECONDS.sleep(100);
    TimeUnit.MILLISECONDS.sleep(100);
    TimeUnit.SECONDS.sleep(100);
    TimeUnit.MINUTES.sleep(100);
    TimeUnit.HOURS.sleep(100);
    TimeUnit.DAYS.sleep(100);
} catch (InterruptedException e) {
    //Handle exception
}

Also it has additional methods: TimeUnit Oracle Documentation

How to use clock() in C++

#include <iostream>
#include <ctime>
#include <cstdlib> //_sleep()  --- just a function that waits a certain amount of milliseconds

using namespace std;

int main()
{

    clock_t cl;     //initializing a clock type

    cl = clock();   //starting time of clock

    _sleep(5167);   //insert code here

    cl = clock() - cl;  //end point of clock

    _sleep(1000);   //testing to see if it actually stops at the end point

    cout << cl/(double)CLOCKS_PER_SEC << endl;  //prints the determined ticks per second (seconds passed)


    return 0;
}

//outputs "5.17"

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

AndroidManifest.xml:

<uses-sdk
    android:minSdkVersion=...
    android:targetSdkVersion="11" />

and

Project Properties -> Project Build Target = 11 or above

These 2 things fixed the problem for me!

What is the meaning of CTOR?

To expand a little more, there are two kinds of constructors: instance initializers (.ctor), type initializers (.cctor). Build the code below, and explore the IL code in ildasm.exe. You will notice that the static field 'b' will be initialized through .cctor() whereas the instance field will be initialized through .ctor()

internal sealed class CtorExplorer
{
   protected int a = 0;
   protected static int b = 0;
}

useState set method not reflecting change immediately

useEffect has its own state/lifecycle, it will not update until you pass a function in parameters or effect destroyed.

object and array spread or rest will not work inside useEffect.

React.useEffect(() => {
    console.log("effect");
    (async () => {
        try {
            let result = await fetch("/query/countries");
            const res = await result.json();
            let result1 = await fetch("/query/projects");
            const res1 = await result1.json();
            let result11 = await fetch("/query/regions");
            const res11 = await result11.json();
            setData({
                countries: res,
                projects: res1,
                regions: res11
            });
        } catch {}
    })(data)
}, [setData])
# or use this
useEffect(() => {
    (async () => {
        try {
            await Promise.all([
                fetch("/query/countries").then((response) => response.json()),
                fetch("/query/projects").then((response) => response.json()),
                fetch("/query/regions").then((response) => response.json())
            ]).then(([country, project, region]) => {
                // console.log(country, project, region);
                setData({
                    countries: country,
                    projects: project,
                    regions: region
                });
            })
        } catch {
            console.log("data fetch error")
        }
    })()
}, [setData]);

Xcode is not currently available from the Software Update server

I faced same problem of Can't install the software because it is currently not available from the Software Update Server. You may try following steps instead to make the Software Update initiate update for the Command Line Tools.

  1. Check if Command Line Tools Update is mentioned in your list of softwares to be updated by using following command: softwareupdate -l
  2. If Command Line Tools Update is not mentioned in that list, then manually make it part of the list using following command which will create a temporary file: sudo touch /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress
  3. Verify that the list now has the Command Line Tools mentioned by running softwareupdate -l again.
  4. Now, press Cmd+Space to initiate Mac's Spotlight Search. Search for Software Update. Start the Software Update.
  5. That will show you following kind of dialog for installing the Command Line Tools. Install away the update and be merry. :) enter image description here
  6. Remove the temporary file created in Step 2: sudo rm /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress.

Border color on default input style

You can use jquery for this by utilizing addClass() method

CSS

 .defaultInput
    {
     width: 100px;
     height:25px;
     padding: 5px;
    }

.error
{
 border:1px solid red;
}

<input type="text" class="defaultInput"/>

Jquery Code

$(document).ready({
  $('.defaultInput').focus(function(){
       $(this).addClass('error');
  });
});

Update: You can remove that error class using

$('.defaultInput').removeClass('error');

It won't remove that default style. It will remove .error class only

jQuery .ready in a dynamically inserted iframe

This was the exact issue I ran into with our client. I created a little jquery plugin that seems to work for iframe readiness. It uses polling to check the iframe document readyState combined with the inner document url combined with the iframe source to make sure the iframe is in fact "ready".

The issue with "onload" is that you need access to the actual iframe being added to the DOM, if you don't then you need to try to catch the iframe loading which if it is cached then you may not. What I needed was a script that could be called anytime, and determine whether or not the iframe was "ready" or not.

Here's the question:

Holy grail for determining whether or not local iframe has loaded

and here's the jsfiddle I eventually came up with.

https://jsfiddle.net/q0smjkh5/10/

In the jsfiddle above, I am waiting for onload to append an iframe to the dom, then checking iframe's inner document's ready state - which should be cross domain because it's pointed to wikipedia - but Chrome seems to report "complete". The plug-in's iready method then gets called when the iframe is in fact ready. The callback tries to check the inner document's ready state again - this time reporting a cross domain request (which is correct) - anyway it seems to work for what I need and hope it helps others.

<script>
  (function($, document, undefined) {
    $.fn["iready"] = function(callback) {
      var ifr = this.filter("iframe"),
          arg = arguments,
          src = this,
          clc = null, // collection
          lng = 50,   // length of time to wait between intervals
          ivl = -1,   // interval id
          chk = function(ifr) {
            try {
              var cnt = ifr.contents(),
                  doc = cnt[0],
                  src = ifr.attr("src"),
                  url = doc.URL;
              switch (doc.readyState) {
                case "complete":
                  if (!src || src === "about:blank") {
                    // we don't care about empty iframes
                    ifr.data("ready", "true");
                  } else if (!url || url === "about:blank") {
                    // empty document still needs loaded
                    ifr.data("ready", undefined);
                  } else {
                    // not an empty iframe and not an empty src
                    // should be loaded
                    ifr.data("ready", true);
                  }

                  break;
                case "interactive":
                  ifr.data("ready", "true");
                  break;
                case "loading":
                default:
                  // still loading
                  break;   
              }
            } catch (ignore) {
              // as far as we're concerned the iframe is ready
              // since we won't be able to access it cross domain
              ifr.data("ready", "true");
            }

            return ifr.data("ready") === "true";
          };

      if (ifr.length) {
        ifr.each(function() {
          if (!$(this).data("ready")) {
            // add to collection
            clc = (clc) ? clc.add($(this)) : $(this);
          }
        });
        if (clc) {
          ivl = setInterval(function() {
            var rd = true;
            clc.each(function() {
              if (!$(this).data("ready")) {
                if (!chk($(this))) {
                  rd = false;
                }
              }
            });

            if (rd) {
              clearInterval(ivl);
              clc = null;
              callback.apply(src, arg);
            }
          }, lng);
        } else {
          clc = null;
          callback.apply(src, arg);
        }
      } else {
        clc = null;
        callback.apply(this, arguments);
      }
      return this;
    };
  }(jQuery, document));
</script>