Programs & Examples On #Easyb

easyb is a behavior driven development framework for the Java platform. By using a specification based Domain Specific Language, easyb aims to enable executable, yet readable documentation.

No 'Access-Control-Allow-Origin' header is present on the requested resource - Resteasy

After facing a similar issue, below is what I did :

  • Created a class extending javax.ws.rs.core.Application and added a Cors Filter to it.

To the CORS filter, I added corsFilter.getAllowedOrigins().add("http://localhost:4200");.

Basically, you should add the URL which you want to allow Cross-Origin Resource Sharing. Ans you can also use "*" instead of any specific URL to allow any URL.

public class RestApplication
    extends Application
{
    private Set<Object> singletons = new HashSet<Object>();

    public MessageApplication()
    {
        singletons.add(new CalculatorService()); //CalculatorService is your specific service you want to add/use.
        CorsFilter corsFilter = new CorsFilter();
        // To allow all origins for CORS add following, otherwise add only specific urls.
        // corsFilter.getAllowedOrigins().add("*");
        System.out.println("To only allow restrcited urls ");
        corsFilter.getAllowedOrigins().add("http://localhost:4200");
        singletons = new LinkedHashSet<Object>();
        singletons.add(corsFilter);
    }

    @Override
    public Set<Object> getSingletons()
    {
        return singletons;
    }
}
  • And here is my web.xml:
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Restful Web Application</display-name>

    <!-- Auto scan rest service -->
    <context-param>
        <param-name>resteasy.scan</param-name>
        <param-value>true</param-value>
    </context-param>

    <context-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/rest</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
        </listener-class>
    </listener>

    <servlet>
        <servlet-name>resteasy-servlet</servlet-name>
        <servlet-class>
            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
        </servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.app.RestApplication</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>resteasy-servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>

The most important code which I was missing when I was getting this issue was, I was not adding my class extending javax.ws.rs.Application i.e RestApplication to the init-param of <servlet-name>resteasy-servlet</servlet-name>

   <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>com.app.RestApplication</param-value>
    </init-param>

And therefore my Filter was not able to execute and thus the application was not allowing CORS from the URL specified.

Read/Write String from/to a File in Android

For those looking for a general strategy for reading and writing a string to file:

First, get a file object

You'll need the storage path. For the internal storage, use:

File path = context.getFilesDir();

For the external storage (SD card), use:

File path = context.getExternalFilesDir(null);

Then create your file object:

File file = new File(path, "my-file-name.txt");

Write a string to the file

FileOutputStream stream = new FileOutputStream(file);
try {
    stream.write("text-to-write".getBytes());
} finally {
    stream.close();
}

Or with Google Guava

String contents = Files.toString(file, StandardCharsets.UTF_8);

Read the file to a string

int length = (int) file.length();

byte[] bytes = new byte[length];

FileInputStream in = new FileInputStream(file);
try {
    in.read(bytes);
} finally {
    in.close();
}

String contents = new String(bytes);   

Or if you are using Google Guava

String contents = Files.toString(file,"UTF-8");

For completeness I'll mention

String contents = new Scanner(file).useDelimiter("\\A").next();

which requires no libraries, but benchmarks 50% - 400% slower than the other options (in various tests on my Nexus 5).

Notes

For each of these strategies, you'll be asked to catch an IOException.

The default character encoding on Android is UTF-8.

If you are using external storage, you'll need to add to your manifest either:

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

or

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

Write permission implies read permission, so you don't need both.

PersistenceContext EntityManager injection NullPointerException

If the component is an EJB, then, there shouldn't be a problem injecting an EM.

But....In JBoss 5, the JAX-RS integration isn't great. If you have an EJB, you cannot use scanning and you must manually list in the context-param resteasy.jndi.resource. If you still have scanning on, Resteasy will scan for the resource class and register it as a vanilla JAX-RS service and handle the lifecycle.

This is probably the problem.

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

I found the game library Allegro easy to use back in the day. Might be worth a look.

What is the default initialization of an array in Java?

Every class in Java have a constructor ( a constructor is a method which is called when a new object is created, which initializes the fields of the class variables ). So when you are creating an instance of the class, constructor method is called while creating the object and all the data values are initialized at that time.

For object of integer array type all values in the array are initialized to 0(zero) in the constructor method. Similarly for object of boolean array, all values are initialized to false.

So Java is initializing the array by running its constructor method while creating the object

Creating an abstract class in Objective-C

The solution I came up with is:

  1. Create a protocol for everything you want in your "abstract" class
  2. Create a base class (or maybe call it abstract) that implements the protocol. For all the methods you want "abstract" implement them in the .m file, but not the .h file.
  3. Have your child class inherit from the base class AND implement the protocol.

This way the compiler will give you a warning for any method in the protocol that isn't implemented by your child class.

It's not as succinct as in Java, but you do get the desired compiler warning.

How to submit http form using C#

Response.Write("<script> try {this.submit();} catch(e){} </script>");

hasOwnProperty in JavaScript

hasOwnProperty() is a nice property to validate object keys. Example:

var obj = {a:1, b:2};

obj.hasOwnProperty('a') // true

error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

I upgraded from 2010 to 2013 and after changing all the projects' Platform Toolset, I need to right-click on the Solution and choose Retarget... to make it work.

openCV video saving in python

This is an answer was only tested in MacOS but it will probably also work in Linux and Windows.

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Get the Default resolutions
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))

# Define the codec and filename.
out = cv2.VideoWriter('output.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:

        # write the  frame
        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

In PowerShell, how can I test if a variable holds a numeric value?

You can check whether the variable is a number like this: $val -is [int]

This will work for numeric values, but not if the number is wrapped in quotes:

1 -is [int]
True
"1" -is [int]
False

Deprecated Java HttpClient - How hard can it be?

Use HttpClientBuilder to build the HttpClient instead of using DefaultHttpClient

ex:

MinimalHttpClient httpclient = new HttpClientBuilder().build();

 // Prepare a request object
 HttpGet httpget = new HttpGet("http://www.apache.org/");

Installing J2EE into existing eclipse IDE

For Mars (Eclipse 4.5) and WTP 3.7 use this link. http://download.eclipse.org/webtools/repository/mars/

  1. In Eclipse select Help - Install New Software.
  2. In the "Work with:" text box place the above link.
  3. Press Enter.
  4. Select the WTP version you need (3.7.0 or 3.7.1 as of today) & follow the prompts.

How to use bluetooth to connect two iPhone?

We cant connect to iPhones normally by bluetooth.it is so difficult.so,please try any other file transfers like zapya,xender.it seems good

MySQL query to get column names?

Use mysql_fetch_field() to view all column data. See manual.

$query = 'select * from myfield';
$result = mysql_query($query);
$i = 0;
while ($i < mysql_num_fields($result))
{
   $fld = mysql_fetch_field($result, $i);
   $myarray[]=$fld->name;
   $i = $i + 1;
}

"Warning This extension is deprecated as of PHP 5.5.0, and will be removed in the future."

How to parse the AndroidManifest.xml file inside an .apk package

In case it's useful, here's a C++ version of the Java snippet posted by Ribo:

struct decompressXML
{
    // decompressXML -- Parse the 'compressed' binary form of Android XML docs 
    // such as for AndroidManifest.xml in .apk files
    enum
    {
        endDocTag = 0x00100101,
        startTag =  0x00100102,
        endTag =    0x00100103
    };

    decompressXML(const BYTE* xml, int cb) {
    // Compressed XML file/bytes starts with 24x bytes of data,
    // 9 32 bit words in little endian order (LSB first):
    //   0th word is 03 00 08 00
    //   3rd word SEEMS TO BE:  Offset at then of StringTable
    //   4th word is: Number of strings in string table
    // WARNING: Sometime I indiscriminently display or refer to word in 
    //   little endian storage format, or in integer format (ie MSB first).
    int numbStrings = LEW(xml, cb, 4*4);

    // StringIndexTable starts at offset 24x, an array of 32 bit LE offsets
    // of the length/string data in the StringTable.
    int sitOff = 0x24;  // Offset of start of StringIndexTable

    // StringTable, each string is represented with a 16 bit little endian 
    // character count, followed by that number of 16 bit (LE) (Unicode) chars.
    int stOff = sitOff + numbStrings*4;  // StringTable follows StrIndexTable

    // XMLTags, The XML tag tree starts after some unknown content after the
    // StringTable.  There is some unknown data after the StringTable, scan
    // forward from this point to the flag for the start of an XML start tag.
    int xmlTagOff = LEW(xml, cb, 3*4);  // Start from the offset in the 3rd word.
    // Scan forward until we find the bytes: 0x02011000(x00100102 in normal int)
    for (int ii=xmlTagOff; ii<cb-4; ii+=4) {
      if (LEW(xml, cb, ii) == startTag) { 
        xmlTagOff = ii;  break;
      }
    } // end of hack, scanning for start of first start tag

    // XML tags and attributes:
    // Every XML start and end tag consists of 6 32 bit words:
    //   0th word: 02011000 for startTag and 03011000 for endTag 
    //   1st word: a flag?, like 38000000
    //   2nd word: Line of where this tag appeared in the original source file
    //   3rd word: FFFFFFFF ??
    //   4th word: StringIndex of NameSpace name, or FFFFFFFF for default NS
    //   5th word: StringIndex of Element Name
    //   (Note: 01011000 in 0th word means end of XML document, endDocTag)

    // Start tags (not end tags) contain 3 more words:
    //   6th word: 14001400 meaning?? 
    //   7th word: Number of Attributes that follow this tag(follow word 8th)
    //   8th word: 00000000 meaning??

    // Attributes consist of 5 words: 
    //   0th word: StringIndex of Attribute Name's Namespace, or FFFFFFFF
    //   1st word: StringIndex of Attribute Name
    //   2nd word: StringIndex of Attribute Value, or FFFFFFF if ResourceId used
    //   3rd word: Flags?
    //   4th word: str ind of attr value again, or ResourceId of value

    // TMP, dump string table to tr for debugging
    //tr.addSelect("strings", null);
    //for (int ii=0; ii<numbStrings; ii++) {
    //  // Length of string starts at StringTable plus offset in StrIndTable
    //  String str = compXmlString(xml, sitOff, stOff, ii);
    //  tr.add(String.valueOf(ii), str);
    //}
    //tr.parent();

    // Step through the XML tree element tags and attributes
    int off = xmlTagOff;
    int indent = 0;
    int startTagLineNo = -2;
    while (off < cb) {
      int tag0 = LEW(xml, cb, off);
      //int tag1 = LEW(xml, off+1*4);
      int lineNo = LEW(xml, cb, off+2*4);
      //int tag3 = LEW(xml, off+3*4);
      int nameNsSi = LEW(xml, cb, off+4*4);
      int nameSi = LEW(xml, cb, off+5*4);

      if (tag0 == startTag) { // XML START TAG
        int tag6 = LEW(xml, cb, off+6*4);  // Expected to be 14001400
        int numbAttrs = LEW(xml, cb, off+7*4);  // Number of Attributes to follow
        //int tag8 = LEW(xml, off+8*4);  // Expected to be 00000000
        off += 9*4;  // Skip over 6+3 words of startTag data
        std::string name = compXmlString(xml, cb, sitOff, stOff, nameSi);
        //tr.addSelect(name, null);
        startTagLineNo = lineNo;

        // Look for the Attributes
        std::string sb;
        for (int ii=0; ii<numbAttrs; ii++) {
          int attrNameNsSi = LEW(xml, cb, off);  // AttrName Namespace Str Ind, or FFFFFFFF
          int attrNameSi = LEW(xml, cb, off+1*4);  // AttrName String Index
          int attrValueSi = LEW(xml, cb, off+2*4); // AttrValue Str Ind, or FFFFFFFF
          int attrFlags = LEW(xml, cb, off+3*4);  
          int attrResId = LEW(xml, cb, off+4*4);  // AttrValue ResourceId or dup AttrValue StrInd
          off += 5*4;  // Skip over the 5 words of an attribute

          std::string attrName = compXmlString(xml, cb, sitOff, stOff, attrNameSi);
          std::string attrValue = attrValueSi!=-1
            ? compXmlString(xml, cb, sitOff, stOff, attrValueSi)
            : "resourceID 0x"+toHexString(attrResId);
          sb.append(" "+attrName+"=\""+attrValue+"\"");
          //tr.add(attrName, attrValue);
        }
        prtIndent(indent, "<"+name+sb+">");
        indent++;

      } else if (tag0 == endTag) { // XML END TAG
        indent--;
        off += 6*4;  // Skip over 6 words of endTag data
        std::string name = compXmlString(xml, cb, sitOff, stOff, nameSi);
        prtIndent(indent, "</"+name+">  (line "+toIntString(startTagLineNo)+"-"+toIntString(lineNo)+")");
        //tr.parent();  // Step back up the NobTree

      } else if (tag0 == endDocTag) {  // END OF XML DOC TAG
        break;

      } else {
        prt("  Unrecognized tag code '"+toHexString(tag0)
          +"' at offset "+toIntString(off));
        break;
      }
    } // end of while loop scanning tags and attributes of XML tree
    prt("    end at offset "+off);
    } // end of decompressXML


    std::string compXmlString(const BYTE* xml, int cb, int sitOff, int stOff, int strInd) {
      if (strInd < 0) return std::string("");
      int strOff = stOff + LEW(xml, cb, sitOff+strInd*4);
      return compXmlStringAt(xml, cb, strOff);
    }

    void prt(std::string str)
    {
        printf("%s", str.c_str());
    }
    void prtIndent(int indent, std::string str) {
        char spaces[46];
        memset(spaces, ' ', sizeof(spaces));
        spaces[min(indent*2,  sizeof(spaces) - 1)] = 0;
        prt(spaces);
        prt(str);
        prt("\n");
    }


    // compXmlStringAt -- Return the string stored in StringTable format at
    // offset strOff.  This offset points to the 16 bit string length, which 
    // is followed by that number of 16 bit (Unicode) chars.
    std::string compXmlStringAt(const BYTE* arr, int cb, int strOff) {
        if (cb < strOff + 2) return std::string("");
      int strLen = arr[strOff+1]<<8&0xff00 | arr[strOff]&0xff;
      char* chars = new char[strLen + 1];
      chars[strLen] = 0;
      for (int ii=0; ii<strLen; ii++) {
          if (cb < strOff + 2 + ii * 2)
          {
              chars[ii] = 0;
              break;
          }
        chars[ii] = arr[strOff+2+ii*2];
      }
      std::string str(chars);
      free(chars);
      return str;
    } // end of compXmlStringAt


    // LEW -- Return value of a Little Endian 32 bit word from the byte array
    //   at offset off.
    int LEW(const BYTE* arr, int cb, int off) {
      return (cb > off + 3) ? ( arr[off+3]<<24&0xff000000 | arr[off+2]<<16&0xff0000
          | arr[off+1]<<8&0xff00 | arr[off]&0xFF ) : 0;
    } // end of LEW

    std::string toHexString(DWORD attrResId)
    {
        char ch[20];
        sprintf_s(ch, 20, "%lx", attrResId);
        return std::string(ch);
    }
    std::string toIntString(int i)
    {
        char ch[20];
        sprintf_s(ch, 20, "%ld", i);
        return std::string(ch);
    }
};

How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)?

The proper function is int fileno(FILE *stream). It can be found in <stdio.h>, and is a POSIX standard but not standard C.

How to convert dataframe into time series?

See this question: Converting data.frame to xts order.by requires an appropriate time-based object, which suggests looking at argument to order.by,

Currently acceptable classes include: ‘Date’, ‘POSIXct’, ‘timeDate’, as well as ‘yearmon’ and ‘yearqtr’ where the index values remain unique.

And further suggests an explicit conversion using order.by = as.POSIXct,

df$Date <- as.POSIXct(strptime(df$Date,format),tz="UTC")
xts(df[, -1], order.by=as.POSIXct(df$Date))

Where your format is assigned elswhere,

format <- "%m/%d/%Y" #see strptime for details

How to select bottom most rows?

Sorry, but I don't think I see any correct answers in my opinion.

The TOP x function shows the records in undefined order. From that definition follows that a BOTTOM function can not be defined.

Independent of any index or sort order. When you do an ORDER BY y DESC you get the rows with the highest y value first. If this is an autogenerated ID, it should show the records last added to the table, as suggested in the other answers. However:

  • This only works if there is an autogenerated id column
  • It has a significant performance impact if you compare that with the TOP function

The correct answer should be that there is not, and cannot be, an equivalent to TOP for getting the bottom rows.

Why is using "for...in" for array iteration a bad idea?

It's not necessarily bad (based on what you're doing), but in the case of arrays, if something has been added to Array.prototype, then you're going to get strange results. Where you'd expect this loop to run three times:

var arr = ['a','b','c'];
for (var key in arr) { ... }

If a function called helpfulUtilityMethod has been added to Array's prototype, then your loop would end up running four times: key would be 0, 1, 2, and helpfulUtilityMethod. If you were only expecting integers, oops.

How to logout and redirect to login page using Laravel 5.4?

In 5.5

adding

Route::get('logout', 'Auth\LoginController@logout');

to my routes file works fine.

Why is System.Web.Mvc not listed in Add References?

I have had the same problem and here is the funny reason: My guess is that you expect System.Web.Mvc to be located under System.Web in the list. But the list is not alphabetical.

First sort the list and then look near the System.Web.

How to sparsely checkout only one single file from a git repository?

If you have edited a local version of a file and wish to revert to the original version maintained on the central server, this can be easily achieved using Git Extensions.

  • Initially the file will be marked for commit, since it has been modified
  • Select (double click) the file in the file tree menu
  • The revision tree for the single file is listed.
  • Select the top/HEAD of the tree and right click save as
  • Save the file to overwrite the modified local version of the file
  • The file now has the correct version and will no longer be marked for commit!

Easy!

How to return an array from an AJAX call?

Have a look at json_encode() in PHP. You can get $.ajax to recognize this with the dataType: "json" parameter.

How to use type: "POST" in jsonp ajax call

You can't POST using JSONP...it simply doesn't work that way, it creates a <script> element to fetch data...which has to be a GET request. There's not much you can do besides posting to your own domain as a proxy which posts to the other...but user's not going to be able to do this directly and see a response though.

right align an image using CSS HTML

To make the image move right:

float: right;

To make the text not wrapped:

clear: right;

For best practice, put the css code in your stylesheets file. Once you add more code, it will look messy and hard to edit.

Arduino Nano - "avrdude: ser_open():system can't open device "\\.\COM1": the system cannot find the file specified"

I was having this same issue this morning. When I checked my Device Manager, it showed COM4 properly, and when I checked in the Arduino IDE COM4 just wasn't an option. Only COM1 was listed.
I tried unplugging and plugging my Arduino in and out a couple more times and eventually COM4 showed up again in the IDE. I didn't have to change any settings.
Hopefully that helps somebody.

how to make jni.h be found?

It needs both jni.h and jni_md.h files, Try this

gcc -I/usr/lib/jvm/jdk1.7.0_07/include \
  -I/usr/lib/jvm/jdk1.7.0_07/include/linux filename.c

This will include both the broad JNI files and the ones necessary for linux

jQuery class within class selector

For this html:

<div class="outer">
     <div class="inner"></div>
</div>

This selector should work:

$('.outer > .inner')

Check if value is in select list with JQuery

Here is another similar option. In my case, I'm checking values in another box as I build a select list. I kept running into undefined values when I would compare, so I set my check this way:

if ( $("#select-box option[value='" + thevalue + "']").val() === undefined) { //do stuff }

I've no idea if this approach is more expensive.

How to use Morgan logger?

Just do this:

app.use(morgan('tiny'));

and it will work.

C: scanf to array

if (array[0]=1) should be if (array[0]==1).

The same with else if (array[0]=2).

Note that the expression of the assignment returns the assigned value, in this case if (array[0]=1) will be always true, that's why the code below the if-statement will be always executed if you don't change the = to ==.

= is the assignment operator, you want to compare, not to assign. So you need ==.

Another thing, if you want only one integer, why are you using array? You might want also to scanf("%d", &array[0]);

Get Image Height and Width as integer values?

getimagesize() returns an array containing the image properties.

list($width, $height) = getimagesize("path/to/image.jpg");

to just get the width and height or

list($width, $height, $type, $attr)

to get some more information.

Set Value of Input Using Javascript Function

document.getElementById('gadget_url').value = 'your value';

Combining CSS Pseudo-elements, ":after" the ":last-child"

You can combine pseudo-elements! Sorry guys, I figured this one out myself shortly after posting the question. Maybe it's less commonly used because of compatibility issues.

li:last-child:before { content: "and "; }

li:last-child:after { content: "."; }

This works swimmingly. CSS is kind of amazing.

How do I redirect users after submit button click?

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com/SpecificAction.php");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com/SpecificAction.php";

Can a main() method of class be invoked from another class in java

If you want to call the main method of another class you can do it this way assuming I understand the question.

public class MyClass {

    public static void main(String[] args) {

        System.out.println("main() method of MyClass");
        OtherClass obj = new OtherClass();
    }
}

class OtherClass {

    public OtherClass() {

        // Call the main() method of MyClass
        String[] arguments = new String[] {"123"};
        MyClass.main(arguments);
    }
}

Seedable JavaScript random number generator

Note: This code was originally included in the question above. In the interests of keeping the question short and focused, I've moved it to this Community Wiki answer.

I found this code kicking around and it appears to work fine for getting a random number and then using the seed afterward but I'm not quite sure how the logic works (e.g. where the 2345678901, 48271 & 2147483647 numbers came from).

function nextRandomNumber(){
  var hi = this.seed / this.Q;
  var lo = this.seed % this.Q;
  var test = this.A * lo - this.R * hi;
  if(test > 0){
    this.seed = test;
  } else {
    this.seed = test + this.M;
  }
  return (this.seed * this.oneOverM);
}

function RandomNumberGenerator(){
  var d = new Date();
  this.seed = 2345678901 + (d.getSeconds() * 0xFFFFFF) + (d.getMinutes() * 0xFFFF);
  this.A = 48271;
  this.M = 2147483647;
  this.Q = this.M / this.A;
  this.R = this.M % this.A;
  this.oneOverM = 1.0 / this.M;
  this.next = nextRandomNumber;
  return this;
}

function createRandomNumber(Min, Max){
  var rand = new RandomNumberGenerator();
  return Math.round((Max-Min) * rand.next() + Min);
}

//Thus I can now do:
var letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
var numbers = ['1','2','3','4','5','6','7','8','9','10'];
var colors = ['red','orange','yellow','green','blue','indigo','violet'];
var first = letters[createRandomNumber(0, letters.length)];
var second = numbers[createRandomNumber(0, numbers.length)];
var third = colors[createRandomNumber(0, colors.length)];

alert("Today's show was brought to you by the letter: " + first + ", the number " + second + ", and the color " + third + "!");

/*
  If I could pass my own seed into the createRandomNumber(min, max, seed);
  function then I could reproduce a random output later if desired.
*/

CSS: stretching background image to 100% width and height of screen?

You need to set the height of html to 100%

body {
    background-image:url("../images/myImage.jpg");
    background-repeat: no-repeat;
    background-size: 100% 100%;
}
html {
    height: 100%
}

http://jsfiddle.net/8XUjP/

Delete/Reset all entries in Core Data?

I've written a clearStores method that goes through every store and delete it both from the coordinator and the filesystem (error handling left aside):

NSArray *stores = [persistentStoreCoordinator persistentStores];

for(NSPersistentStore *store in stores) {
    [persistentStoreCoordinator removePersistentStore:store error:nil];
    [[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:nil];
}

[persistentStoreCoordinator release], persistentStoreCoordinator = nil;

This method is inside a coreDataHelper class that takes care of (among other things) creating the persistentStore when it's nil.

What is the easiest way to get current GMT time in Unix timestamp format?

#First Example:
from datetime import datetime, timezone    
timstamp1 =int(datetime.now(tz=timezone.utc).timestamp() * 1000)
print(timstamp1)

Output: 1572878043380

#second example:
import time
timstamp2 =int(time.time())
print(timstamp2)

Output: 1572878043

  • Here, we can see the first example gives more accurate time than second one.
  • Here I am using the first one.

PhpMyAdmin not working on localhost

STOP ALL SERVICES OF XAMPP Edit Apache(httpd.conf) file 1)"Listen 80" if its already 80 and not working then replace it by 81 2) "ServerName localhost:80" if its already 80 and not working then replace it by 81 SAVE EXIT RESTART [WINDOWS USER run as administrator]

Get text of the selected option with jQuery

Change your selector to

val = j$("#select_2 option:selected").text();

You're selecting the <select> instead of the <option>

How can I view a git log of just one user's commits?

git help log

gives you the manpage of git log. Search for "author" there by pressing / and then typing "author", followed by Enter. Type "n" a few times to get to the relevant section, which reveals:

git log --author="username"

as already suggested.

Note that this will give you the author of the commits, but in Git, the author can be someone different from the committer (for example in Linux kernel, if you submit a patch as an ordinary user, it might be committed by another administrative user.) See Difference between author and committer in Git? for more details)

Most of the time, what one refers to as the user is both the committer and the author though.

How do I align spans or divs horizontally?

I would do it something like this as it gives you 3 even sized columns, even spacing and (even) scales. Note: This is not tested so it might need tweaking for older browsers.

<style>
html, body {
    margin: 0;
    padding: 0;
}

.content {
    float: left;
    width: 30%;
    border:none;
}

.rightcontent {
    float: right;
    width: 30%;
    border:none
}

.hspacer {
    width:5%;
    float:left;
}

.clear {
    clear:both;
}
</style>

<div class="content">content</div>
<div class="hspacer">&nbsp;</div>
<div class="content">content</div>
<div class="hspacer">&nbsp;</div>
<div class="rightcontent">content</div>
<div class="clear"></div>

JQuery: if div is visible

You can use .is(':visible')

Selects all elements that are visible.

For example:

if($('#selectDiv').is(':visible')){

Also, you can get the div which is visible by:

$('div:visible').callYourFunction();

Live example:

_x000D_
_x000D_
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
  display: none;  _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
_x000D_
_x000D_

Convert int to ASCII and back in Python

What about BASE58 encoding the URL? Like for example flickr does.

# note the missing lowercase L and the zero etc.
BASE58 = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ' 
url = ''
while node_id >= 58:
    div, mod = divmod(node_id, 58)
    url = BASE58[mod] + url
    node_id = int(div)

return 'http://short.com/%s' % BASE58[node_id] + url

Turning that back into a number isn't a big deal either.

Ordering issue with date values when creating pivot tables

You need to select the entire column where you have the dates, so click the "text to columns" button, and select delimited > uncheck all the boxes and go until you click the button finish.

This will make the cell format and then the values will be readed as date.

Hope it will helped.

Link a .css on another folder

I think what you want to do is

_x000D_
_x000D_
<link rel="stylesheet" type="text/css" href="font/font-face/my-font-face.css">
_x000D_
_x000D_
_x000D_

MySQL show current connection info

You can use the status command in MySQL client.

mysql> status;
--------------
mysql  Ver 14.14 Distrib 5.5.8, for Win32 (x86)

Connection id:          1
Current database:       test
Current user:           ODBC@localhost
SSL:                    Not in use
Using delimiter:        ;
Server version:         5.5.8 MySQL Community Server (GPL)
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    latin1
Db     characterset:    latin1
Client characterset:    gbk
Conn.  characterset:    gbk
TCP port:               3306
Uptime:                 7 min 16 sec

Threads: 1  Questions: 21  Slow queries: 0  Opens: 33  Flush tables: 1  Open tables: 26  Queries per second avg: 0.48
--------------

mysql>

Find records with a date field in the last 24 hours

There are so many ways to do this. The listed ones work great, but here's another way if you have a datetime field:

SELECT [fields] 
FROM [table] 
WHERE timediff(now(), my_datetime_field) < '24:00:00'

timediff() returns a time object, so don't make the mistake of comparing it to 86400 (number of seconds in a day), or your output will be all kinds of wrong.

How do I change tab size in Vim?

:set tabstop=4
:set shiftwidth=4
:set expandtab

This will insert four spaces instead of a tab character. Spaces are a bit more “stable”, meaning that text indented with spaces will show up the same in the browser and any other application.

How to get parameter on Angular2 route in Angular way?

Update: Sep 2019

As a few people have mentioned, the parameters in paramMap should be accessed using the common MapAPI:

To get a snapshot of the params, when you don't care that they may change:

this.bankName = this.route.snapshot.paramMap.get('bank');

To subscribe and be alerted to changes in the parameter values (typically as a result of the router's navigation)

this.route.paramMap.subscribe( paramMap => {
    this.bankName = paramMap.get('bank');
})

Update: Aug 2017

Since Angular 4, params have been deprecated in favor of the new interface paramMap. The code for the problem above should work if you simply substitute one for the other.

Original Answer

If you inject ActivatedRoute in your component, you'll be able to extract the route parameters

    import {ActivatedRoute} from '@angular/router';
    ...
    
    constructor(private route:ActivatedRoute){}
    bankName:string;
    
    ngOnInit(){
        // 'bank' is the name of the route parameter
        this.bankName = this.route.snapshot.params['bank'];
    }

If you expect users to navigate from bank to bank directly, without navigating to another component first, you ought to access the parameter through an observable:

    ngOnInit(){
        this.route.params.subscribe( params =>
            this.bankName = params['bank'];
        )
    }

For the docs, including the differences between the two check out this link and search for "activatedroute"

'python' is not recognized as an internal or external command

Another helpful but simple solution might be restarting your computer after doing the download if Python is in the PATH variable. This has been a mistake I usually make when downloading Python onto a new machine.

Makefile, header dependencies

The following works for me:

DEPS := $(OBJS:.o=.d)

-include $(DEPS)

%.o: %.cpp
    $(CXX) $(CFLAGS) -MMD -c -o $@ $<

Gradle task - pass arguments to Java application

Sorry for answering so late.

I figured an answer alike to @xlm 's:

task run (type: JavaExec, dependsOn: classes){
    if(project.hasProperty('myargs')){
        args(myargs.split(','))
    }
    description = "Secure algorythm testing"
    main = "main.Test"
    classpath = sourceSets.main.runtimeClasspath
}

And invoke like:

gradle run -Pmyargs=-d,s

storing user input in array

You have at least these 3 issues:

  1. you are not getting the element's value properly
  2. The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
  3. Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.

You can save all three values at once by doing:

var title=new Array();
var names=new Array();//renamed to names -added an S- 
                      //to avoid conflicts with the input named "name"
var tickets=new Array();

function insert(){
    var titleValue = document.getElementById('title').value;
    var actorValue = document.getElementById('name').value;
    var ticketsValue = document.getElementById('tickets').value;
    title[title.length]=titleValue;
    names[names.length]=actorValue;
    tickets[tickets.length]=ticketsValue;
  }

And then change the show function to:

function show() {
  var content="<b>All Elements of the Arrays :</b><br>";
  for(var i = 0; i < title.length; i++) {
     content +=title[i]+"<br>";
  }
  for(var i = 0; i < names.length; i++) {
     content +=names[i]+"<br>";
  }
  for(var i = 0; i < tickets.length; i++) {
     content +=tickets[i]+"<br>";
  }
  document.getElementById('display').innerHTML = content; //note that I changed 
                                                    //to 'display' because that's
                                              //what you have in your markup
}

Here's a jsfiddle for you to play around.

How to create multidimensional array

I've created an npm module to do this with some added flexibility:

// create a 3x3 array
var twodimensional = new MultiDimensional([3, 3])

// create a 3x3x4 array
var threedimensional = new MultiDimensional([3, 3, 4])

// create a 4x3x4x2 array
var fourdimensional = new MultiDimensional([4, 3, 4, 2])

// etc...

You can also initialize the positions with any value:

// create a 3x4 array with all positions set to 0
var twodimensional = new MultiDimensional([3, 4], 0)

// create a 3x3x4 array with all positions set to 'Default String'
var threedimensionalAsStrings = new MultiDimensional([3, 3, 4], 'Default String')

Or more advanced:

// create a 3x3x4 array with all positions set to a unique self-aware objects.
var threedimensional = new MultiDimensional([3, 3, 4], function(position, multidimensional) {
    return {
        mydescription: 'I am a cell at position ' + position.join(),
        myposition: position,
        myparent: multidimensional
    }
})

Get and set values at positions:

// get value
threedimensional.position([2, 2, 2])

// set value
threedimensional.position([2, 2, 2], 'New Value')

How to detect the swipe left or Right in Android?

here is generic swipe left detector for any view in kotlin using databinding

@BindingAdapter("onSwipeLeft")
fun View.setOnSwipeLeft(runnable: Runnable) {
    setOnTouchListener(object : View.OnTouchListener {
        var x0 = 0F; var y0 = 0F; var t0 = 0L
        val defaultClickDuration = 200

        override fun onTouch(v: View?, motionEvent: MotionEvent?): Boolean {
            motionEvent?.let { event ->
                when(event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        x0 = event.x; y0 = event.y; t0 = System.currentTimeMillis()
                    }
                    MotionEvent.ACTION_UP -> {
                        val x1 = event.x; val y1 = event.y; val t1 = System.currentTimeMillis()

                        if (x0 == x1 && y0 == y1 && (t1 - t0) < defaultClickDuration) {
                            performClick()
                            return false
                        }
                        if (x0 > x1) { runnable.run() }
                    }
                    else -> {}
                }
            }
            return true
        }
    })
}

and then to use it in your layout:

app:onSwipeLeft="@{() -> viewModel.swipeLeftHandler()}"

ImportError: No module named 'MySQL'

For 64-bit windows

install using wheel

pip install wheel download from http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python

For python 3.x:

pip install mysqlclient-xxxxxxxxx-win_amd64.whl

For python 2.7:

pip install mysqlclient-xxxxxxxxx-win_amd64.whl

ActiveMQ or RabbitMQ or ZeroMQ or

More information than you would want to know:

http://wiki.secondlife.com/wiki/Message_Queue_Evaluation_Notes


UPDATE

Just elaborating what Paul added in comment. The page mentioned above is dead after 2010, so read with a pinch of salt. Lot of stuff has been been changed in 3 years.

History of Wiki Page

Pass a javascript variable value into input type hidden value

<script type="text/javascript">
  function product(x,y)
  {
   return x*y;
  }
 document.getElementById('myvalue').value = product(x,y);
 </script>

 <input type="hidden" value="THE OUTPUT OF PRODUCT FUNCTION" id="myvalue">

How to use Visual Studio Code as Default Editor for Git

You need to use command:

git config --global core.editor "'C:\Program Files\Microsoft VS Code\code.exe' -n -w"

Make sure you can start your editor from Git Bash

If you want to use Code.exe with short path, you can do this by adding the following line to your .bash_profile:

alias vscode="C:/Program\ Files/Microsoft\ VS\ Code/Code.exe"

And now, you can call it using only vscode command(or whatever you named it)

Some additional info:

Setup will add Visual Studio Code to your %PATH%, so from the console you can type 'code' to open VS Code on that folder. You will need to restart your console after the installation for the change to the %PATH% environmental variable to take effect.

How to redirect output to a file and stdout

Using tail -f output should work.

Differences between TCP sockets and web sockets, one more time

When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer. If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. With WebSockets, the data that is passed to the send method is always either sent as a whole "message" or not at all. Also, browser WebSocket implementations do not block on the send call.

But there are more important differences on the receiving side of things. When the receiver does a recv (or read) on a TCP socket, there is no guarantee that the number of bytes returned corresponds to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the recipient of a message is event-driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.

Note that you can do message based communication using TCP sockets, but you need some extra layer/encapsulation that is adding framing/message boundary data to the messages so that the original messages can be re-assembled from the pieces. In fact, WebSockets is built on normal TCP sockets and uses frame headers that contains the size of each frame and indicate which frames are part of a message. The WebSocket API re-assembles the TCP chunks of data into frames which are assembled into messages before invoking the message event handler once per message.

Insert new item in array on any position in PHP

Try this one:

$colors = array('red', 'blue', 'yellow');

$colors = insertElementToArray($colors, 'green', 2);


function insertElementToArray($arr = array(), $element = null, $index = 0)
{
    if ($element == null) {
        return $arr;
    }

    $arrLength = count($arr);
    $j = $arrLength - 1;

    while ($j >= $index) {
        $arr[$j+1] = $arr[$j];
        $j--;
    }

    $arr[$index] = $element;

    return $arr;
}

Ruby combining an array into one string

Here's my solution:

@arr = ['<p>Hello World</p>', '<p>This is a test</p>']
@arr.reduce(:+)
=> <p>Hello World</p><p>This is a test</p>

Redirect parent window from an iframe action

@MIP is right, but with newer versions of Safari, you will need to add sandbox attribute(HTML5) to give redirect access to the iFrame. There are a few specific values that can be added with a space between them.

Reference(you will need to scroll): https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe

Ex:

<iframe sandbox="allow-top-navigation" src="http://google.com/"></iframe>

How to pass variable number of arguments to a PHP function

Since PHP 5.6, a variable argument list can be specified with the ... operator.

function do_something($first, ...$all_the_others)
{
    var_dump($first);
    var_dump($all_the_others);
}

do_something('this goes in first', 2, 3, 4, 5);

#> string(18) "this goes in first"
#>
#> array(4) {
#>   [0]=>
#>   int(2)
#>   [1]=>
#>   int(3)
#>   [2]=>
#>   int(4)
#>   [3]=>
#>   int(5)
#> }

As you can see, the ... operator collects the variable list of arguments in an array.

If you need to pass the variable arguments to another function, the ... can still help you.

function do_something($first, ...$all_the_others)
{
    do_something_else($first, ...$all_the_others);
    // Which is translated to:
    // do_something_else('this goes in first', 2, 3, 4, 5);
}

Since PHP 7, the variable list of arguments can be forced to be all of the same type too.

function do_something($first, int ...$all_the_others) { /**/ }

Post-increment and Pre-increment concept?

No one has answered the question: Why is this concept confusing?

As an undergrad Computer Science major it took me awhile to understand this because of the way I read the code.

The following is not correct!


x = y++

X is equal to y post increment. Which would logically seem to mean X is equal to the value of Y after the increment operation is done. Post meaning after.

or

x = ++y
X is equal to y pre-increment. Which would logically seem to mean X is equal to the value of Y before the increment operation is done. Pre meaning before.


The way it works is actually the opposite. This concept is confusing because the language is misleading. In this case we cannot use the words to define the behavior.
x=++y is actually read as X is equal to the value of Y after the increment.
x=y++ is actually read as X is equal to the value of Y before the increment.

The words pre and post are backwards with respect to semantics of English. They only mean where the ++ is in relation Y. Nothing more.

Personally, if I had the choice I would switch the meanings of ++y and y++. This is just an example of a idiom that I had to learn.

If there is a method to this madness I'd like to know in simple terms.

Thanks for reading.

"installation of package 'FILE_PATH' had non-zero exit status" in R

I have had the same problem with a specific package in R and the solution was I should install in the ubuntu terminal libcurl. Look at the information that appears above explaining to us that curl package has error installation.

I knew this about the message:

Configuration failed because libcurl was not found. Try installing:
 * deb: libcurl4-openssl-dev (Debian, Ubuntu, etc)
 * rpm: libcurl-devel (Fedora, CentOS, RHEL)
 * csw: libcurl_dev (Solaris)
If libcurl is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libcurl.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'

To install it I used the net command:

sudo apt-get install libcurl4-openssl-dev

Sometimes we can not install a specific package in R because we have problems with packages that must be installed previously as curl package. To know if we should install it we should check the warning errors such as: installation of package ‘curl’ had non-zero exit status.

I hope I have been helpful

Fastest way to count number of occurrences in a Python list

a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
print a.count("1")

It's probably optimized heavily at the C level.

Edit: I randomly generated a large list.

In [8]: len(a)
Out[8]: 6339347

In [9]: %timeit a.count("1")
10 loops, best of 3: 86.4 ms per loop

Edit edit: This could be done with collections.Counter

a = Counter(your_list)
print a['1']

Using the same list in my last timing example

In [17]: %timeit Counter(a)['1']
1 loops, best of 3: 1.52 s per loop

My timing is simplistic and conditional on many different factors, but it gives you a good clue as to performance.

Here is some profiling

In [24]: profile.run("a.count('1')")
         3 function calls in 0.091 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.091    0.091 <string>:1(<module>)
        1    0.091    0.091    0.091    0.091 {method 'count' of 'list' objects}

        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}



In [25]: profile.run("b = Counter(a); b['1']")
         6339356 function calls in 2.143 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.143    2.143 <string>:1(<module>)
        2    0.000    0.000    0.000    0.000 _weakrefset.py:68(__contains__)
        1    0.000    0.000    0.000    0.000 abc.py:128(__instancecheck__)
        1    0.000    0.000    2.143    2.143 collections.py:407(__init__)
        1    1.788    1.788    2.143    2.143 collections.py:470(update)
        1    0.000    0.000    0.000    0.000 {getattr}
        1    0.000    0.000    0.000    0.000 {isinstance}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}
  6339347    0.356    0.000    0.356    0.000 {method 'get' of 'dict' objects}

Print the data in ResultSet along with column names

For what you are trying to do, instead of PreparedStatement you can use Statement. Your code may be modified as-

String sql = "SELECT column_name from information_schema.columns where table_name='suppliers';";

Statement s  = connection.createStatement();
ResultSet rs = s.executeQuery(sql);

Hope this helps.

How do I fix a Git detached head?

The detached HEAD means that you are currently not on any branch. If you want to KEEP your current changes and simply create a new branch, this is what you do:

git commit -m "your commit message"
git checkout -b new_branch

Afterwards, you potentially want to merge this new branch with other branches. Always helpful is the git "a dog" command:

git log --all --decorate --oneline --graph

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

I resolve this is by changing the version no of recyleview to recyclerview-v7:24.2.1. Please check your dependencies and use the proper version number.

in a "using" block is a SqlConnection closed on return or exception?

  1. Yes
  2. Yes.

Either way, when the using block is exited (either by successful completion or by error) it is closed.

Although I think it would be better to organize like this because it's a lot easier to see what is going to happen, even for the new maintenance programmer who will support it later:

using (SqlConnection connection = new SqlConnection(connectionString)) 
{    
    int employeeID = findEmployeeID();    
    try    
    {
        connection.Open();
        SqlCommand command = new SqlCommand("UpdateEmployeeTable", connection);
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));
        command.CommandTimeout = 5;

        command.ExecuteNonQuery();    
    } 
    catch (Exception) 
    { 
        /*Handle error*/ 
    }
}

Count with IF condition in MySQL query

This should work:

count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, NULL))

count() only check if the value exists or not. 0 is equivalent to an existent value, so it counts one more, while NULL is like a non-existent value, so is not counted.

Temporarily switch working copy to a specific Git commit

In addition to the other answers here showing you how to git checkout <the-hash-you-want> it's worth knowing you can switch back to where you were using:

git checkout @{-1}

This is often more convenient than:

git checkout what-was-that-original-branch-called-again-question-mark

As you might anticipate, git checkout @{-2} will take you back to the branch you were at two git checkouts ago, and similarly for other numbers. If you can remember where you were for bigger numbers, you should get some kind of medal for that.


Sadly for productivity, git checkout @{1} does not take you to the branch you will be on in future, which is a shame.

Getting the name of a variable as a string

If the goal is to help you keep track of your variables, you can write a simple function that labels the variable and returns its value and type. For example, suppose i_f=3.01 and you round it to an integer called i_n to use in a code, and then need a string i_s that will go into a report.

def whatis(string, x):
    print(string+' value=',repr(x),type(x))
    return string+' value='+repr(x)+repr(type(x))
i_f=3.01
i_n=int(i_f)
i_s=str(i_n)
i_l=[i_f, i_n, i_s]
i_u=(i_f, i_n, i_s)

## make report that identifies all types
report='\n'+20*'#'+'\nThis is the report:\n'
report+= whatis('i_f ',i_f)+'\n'
report+=whatis('i_n ',i_n)+'\n'
report+=whatis('i_s ',i_s)+'\n'
report+=whatis('i_l ',i_l)+'\n'
report+=whatis('i_u ',i_u)+'\n'
print(report)

This prints to the window at each call for debugging purposes and also yields a string for the written report. The only downside is that you have to type the variable twice each time you call the function.

I am a Python newbie and found this very useful way to log my efforts as I program and try to cope with all the objects in Python. One flaw is that whatis() fails if it calls a function described outside the procedure where it is used. For example, int(i_f) was a valid function call only because the int function is known to Python. You could call whatis() using int(i_f**2), but if for some strange reason you choose to define a function called int_squared it must be declared inside the procedure where whatis() is used.

Select last row in MySQL

If you want the most recently added one, add a timestamp and select ordered in reverse order by highest timestamp, limit 1. If you want to go by ID, sort by ID. If you want to use the one you JUST added, use mysql_insert_id.

How to call Stored Procedure in Entity Framework 6 (Code-First)?

It work for me at code first. It return a list with matching property of view model(StudentChapterCompletionViewModel)

var studentIdParameter = new SqlParameter
{
     ParameterName = "studentId",
     Direction = ParameterDirection.Input,
     SqlDbType = SqlDbType.BigInt,
     Value = studentId
 };

 var results = Context.Database.SqlQuery<StudentChapterCompletionViewModel>(
                "exec dbo.sp_StudentComplettion @studentId",
                 studentIdParameter
                ).ToList();

Updated for Context

Context is the instance of the class that Inherit DbContext like below.

public class ApplicationDbContext : DbContext
{
    public DbSet<City> City { get; set; }
}

var Context = new  ApplicationDbContext();

Merging multiple PDFs using iTextSharp in c#.net

Merge byte arrays of multiple PDF files:

    public static byte[] MergePDFs(List<byte[]> pdfFiles)
    {  
        if (pdfFiles.Count > 1)
        {
            PdfReader finalPdf;
            Document pdfContainer;
            PdfWriter pdfCopy;
            MemoryStream msFinalPdf = new MemoryStream();

            finalPdf = new PdfReader(pdfFiles[0]);
            pdfContainer = new Document();
            pdfCopy = new PdfSmartCopy(pdfContainer, msFinalPdf);

            pdfContainer.Open();

            for (int k = 0; k < pdfFiles.Count; k++)
            {
                finalPdf = new PdfReader(pdfFiles[k]);
                for (int i = 1; i < finalPdf.NumberOfPages + 1; i++)
                {
                    ((PdfSmartCopy)pdfCopy).AddPage(pdfCopy.GetImportedPage(finalPdf, i));
                }
                pdfCopy.FreeReader(finalPdf);

            }
            finalPdf.Close();
            pdfCopy.Close();
            pdfContainer.Close();

            return msFinalPdf.ToArray();
        }
        else if (pdfFiles.Count == 1)
        {
            return pdfFiles[0];
        }
        return null;
    }

Auto Resize Image in CSS FlexBox Layout and keeping Aspect Ratio?

In the second image it looks like you want the image to fill the box, but the example you created DOES keep the aspect ratio (the pets look normal, not slim or fat).

I have no clue if you photoshopped those images as example or the second one is "how it should be" as well (you said IS, while the first example you said "should")

Anyway, I have to assume:

If "the images are not resized keeping the aspect ration" and you show me an image which DOES keep the aspect ratio of the pixels, I have to assume you are trying to accomplish the aspect ratio of the "cropping" area (the inner of the green) WILE keeping the aspect ratio of the pixels. I.e. you want to fill the cell with the image, by enlarging and cropping the image.

If that's your problem, the code you provided does NOT reflect "your problem", but your starting example.

Given the previous two assumptions, what you need can't be accomplished with actual images if the height of the box is dynamic, but with background images. Either by using "background-size: contain" or these techniques (smart paddings in percents that limit the cropping or max sizes anywhere you want): http://fofwebdesign.co.uk/template/_testing/scale-img/scale-img.htm

The only way this is possible with images is if we FORGET about your second iimage, and the cells have a fixed height, and FORTUNATELY, judging by your sample images, the height stays the same!

So if your container's height doesn't change, and you want to keep your images square, you just have to set the max-height of the images to that known value (minus paddings or borders, depending on the box-sizing property of the cells)

Like this:

<div class="content">
  <div class="row">    
      <div class="cell">    
          <img src="http://lorempixel.com/output/people-q-c-320-320-2.jpg"/>
      </div>
      <div class="cell">    
          <img src="http://lorempixel.com/output/people-q-c-320-320-7.jpg"/>
      </div>
    </div>
</div>

And the CSS:

.content {
    background-color: green;
}

.row {
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;

    -webkit-box-orient: horizontal; 
    -moz-box-orient: horizontal;
    box-orient: horizontal;
    flex-direction: row;

    -webkit-box-pack: center;
    -moz-box-pack: center;
    box-pack: center;
    justify-content: center;

    -webkit-box-align: center;
    -moz-box-align: center;
    box-align: center;  
    align-items: center;

}

.cell {
    -webkit-box-flex: 1;
    -moz-box-flex: 1;
    box-flex: 1;
    -webkit-flex: 1 1 auto;
    flex: 1 1 auto;
    padding: 10px;
    border: solid 10px red;
    text-align: center;
    height: 300px;
    display: flex;
    align-items: center;
    box-sizing: content-box;
}
img {
    margin: auto;
    width: 100%;
    max-width: 300px;
    max-height:100%
}

http://jsfiddle.net/z25heocL/

Your code is invalid (opening tags are instead of closing ones, so they output NESTED cells, not siblings, he used a SCREENSHOT of your images inside the faulty code, and the flex box is not holding the cells but both examples in a column (you setup "row" but the corrupt code nesting one cell inside the other resulted in a flex inside a flex, finally working as COLUMNS. I have no idea what you wanted to accomplish, and how you came up with that code, but I'm guessing what you want is this.

I added display: flex to the cells too, so the image gets centered (I think display: table could have been used here as well with all this markup)

Add colorbar to existing axis

The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the cax kwarg to tell fig.colorbar to use the new axes.

For example:

import numpy as np
import matplotlib.pyplot as plt

data = np.arange(100, 0, -1).reshape(10, 10)

fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])

im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im, cax=cax, orientation='horizontal')
plt.show()

enter image description here

How to download file from database/folder using php

here is the code to download file with how much % it is downloaded

<?php
$ch = curl_init();
$downloadFile = fopen( 'file name here', 'w' );
curl_setopt($ch, CURLOPT_URL, "file link here");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_BUFFERSIZE, 65536);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'downloadProgress'); 
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt( $ch, CURLOPT_FILE, $downloadFile );
curl_exec($ch);
curl_close($ch);

function downloadProgress ($resource, $download_size, $downloaded_size, $upload_size, $uploaded_size) {

    if($download_size!=0){
    $percen= (($downloaded_size/$download_size)*100);
    echo $percen."<br>";

}

}
?>

Android SDK installation doesn't find JDK

There is too many ways for doing it:

Way number one

If Java is installed perfectly in your machine, then please close the installer and try to reinstall it.

When you open it for the second time, it will find JAVA.

Way number 2

Set up an environment variable like this-

Environment variables for java installation

And then try again.

It should work :)

How to combine GROUP BY, ORDER BY and HAVING

Your code should be contain WHILE before group by and having :

SELECT Email, COUNT(*)

FROM user_log

WHILE Email IS NOT NULL

GROUP BY Email

HAVING COUNT(*) > 1

ORDER BY UpdateDate DESC

What is the height of Navigation Bar in iOS 7?

There is a difference between the navigation bar and the status bar. The confusing part is that it looks like one solid feature at the top of the screen, but the areas can actually be separated into two distinct views; a status bar and a navigation bar. The status bar spans from y=0 to y=20 points and the navigation bar spans from y=20 to y=64 points. So the navigation bar (which is where the page title and navigation buttons go) has a height of 44 points, but the status bar and navigation bar together have a total height of 64 points.

Here is a great resource that addresses this question along with a number of other sizing idiosyncrasies in iOS7: http://ivomynttinen.com/blog/the-ios-7-design-cheat-sheet/

Bootstrap DatePicker, how to set the start date for tomorrow?

There is no official datepicker for bootstrap; as such, you should explicitly state which one you're using.

If you're using eternicode/bootstrap-datepicker, there's a startDate option. As discussed directly under the Options section in the README:

All options that take a "Date" can handle a Date object; a String formatted according to the given format; or a timedelta relative to today, eg '-1d', '+6m +1y', etc, where valid units are 'd' (day), 'w' (week), 'm' (month), and 'y' (year).

So you would do:

$('#datepicker').datepicker({
    startDate: '+1d'
})

Under what circumstances can I call findViewById with an Options Menu / Action Bar item?

I am trying to obtain a handle on one of the views in the Action Bar

I will assume that you mean something established via android:actionLayout in your <item> element of your <menu> resource.

I have tried calling findViewById(R.id.menu_item)

To retrieve the View associated with your android:actionLayout, call findItem() on the Menu to retrieve the MenuItem, then call getActionView() on the MenuItem. This can be done any time after you have inflated the menu resource.

Generating a random hex color code with PHP

If someone wants to generate light colors

sprintf('#%06X', mt_rand(0xFF9999, 0xFFFF00));

How to convert a HTMLElement to a string

The most easy way to do is copy innerHTML of that element to tmp variable and make it empty, then append new element, and after that copy back tmp variable to it. Here is an example I used to add jquery script to top of head.

var imported = document.createElement('script');
imported.src = 'http://code.jquery.com/jquery-1.7.1.js';
var tmpHead = document.head.innerHTML;
document.head.innerHTML = "";
document.head.append(imported);
document.head.innerHTML += tmpHead;

That simple :)

Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

I got this error when I was trying to create a virtualenv with command virtualenv myVirtualEnv. I just added a sudo before the command; it solved everything.

How to override the [] operator in Python?

You are looking for the __getitem__ method. See http://docs.python.org/reference/datamodel.html, section 3.4.6

How to check queue length in Python

Use queue.rear+1 to get the length of the queue

Change package name for Android in React Native

Simply using the search and replace tool of my IDE did the trick.

drag drop files into standard html file input

_x000D_
_x000D_
//----------App.js---------------------//_x000D_
$(document).ready(function() {_x000D_
    var holder = document.getElementById('holder');_x000D_
    holder.ondragover = function () { this.className = 'hover'; return false; };_x000D_
    holder.ondrop = function (e) {_x000D_
      this.className = 'hidden';_x000D_
      e.preventDefault();_x000D_
      var file = e.dataTransfer.files[0];_x000D_
      var reader = new FileReader();_x000D_
      reader.onload = function (event) {_x000D_
          document.getElementById('image_droped').className='visible'_x000D_
          $('#image_droped').attr('src', event.target.result);_x000D_
      }_x000D_
      reader.readAsDataURL(file);_x000D_
    };_x000D_
});
_x000D_
.holder_default {_x000D_
    width:500px; _x000D_
    height:150px; _x000D_
    border: 3px dashed #ccc;_x000D_
}_x000D_
_x000D_
#holder.hover { _x000D_
    width:400px; _x000D_
    height:150px; _x000D_
    border: 3px dashed #0c0 !important; _x000D_
}_x000D_
_x000D_
.hidden {_x000D_
    visibility: hidden;_x000D_
}_x000D_
_x000D_
.visible {_x000D_
    visibility: visible;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
_x000D_
<html>_x000D_
    <head>_x000D_
        <title> HTML 5 </title>_x000D_
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>_x000D_
    </head>_x000D_
    <body>_x000D_
      <form method="post" action="http://example.com/">_x000D_
        <div id="holder" style="" id="holder" class="holder_default">_x000D_
          <img src="" id="image_droped" width="200" style="border: 3px dashed #7A97FC;" class=" hidden"/>_x000D_
        </div>_x000D_
      </form>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Matplotlib different size subplots

Probably the simplest way is using subplot2grid, described in Customizing Location of Subplot Using GridSpec.

ax = plt.subplot2grid((2, 2), (0, 0))

is equal to

import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2, 2)
ax = plt.subplot(gs[0, 0])

so bmu's example becomes:

import numpy as np
import matplotlib.pyplot as plt

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
fig = plt.figure(figsize=(8, 6))
ax0 = plt.subplot2grid((1, 3), (0, 0), colspan=2)
ax0.plot(x, y)
ax1 = plt.subplot2grid((1, 3), (0, 2))
ax1.plot(y, x)

plt.tight_layout()
plt.savefig('grid_figure.pdf')

Add multiple items to already initialized arraylist in java

If you needed to add a lot of integers it'd proabbly be easiest to use a for loop. For example, adding 28 days to a daysInFebruary array.

ArrayList<Integer> daysInFebruary = new ArrayList<>();

for(int i = 1; i <= 28; i++) {
    daysInFebruary.add(i);
}

Parsing a JSON string in Ruby

This looks like JavaScript Object Notation (JSON). You can parse JSON that resides in some variable, e.g. json_string, like so:

require 'json'
JSON.parse(json_string)

If you’re using an older Ruby, you may need to install the json gem.


There are also other implementations of JSON for Ruby that may fit some use-cases better:

Unrecognized escape sequence for path string containing backslashes

If your string is a file path, as in your example, you can also use Unix style file paths:

string foo = "D:/Projects/Some/Kind/Of/Pathproblem/wuhoo.xml";

But the other answers have the more general solutions to string escaping in C#.

jquery onclick change css background image

I think this should be:

$('.home').click(function() {
     $(this).css('background', 'url(images/tabs3.png)');
 });

and remove this:

<div class="home" onclick="function()">
     //-----------^^^^^^^^^^^^^^^^^^^^---------no need for this

You have to make sure you have a correct path to your image.

Validate decimal numbers in JavaScript - IsNumeric()

It can be done without RegExp as

function IsNumeric(data){
    return parseFloat(data)==data;
}

Left align block of equations

You can use \begin{flalign}, like the example bellow:

\begin{flalign}
    &f(x) = -1.25x^{2} + 1.5x&
\end{flalign}

JavaScript code to stop form submission

I would recommend not using onsubmit and instead attaching an event in the script.

var submit = document.getElementById("submitButtonId");
if (submit.addEventListener) {
  submit.addEventListener("click", returnToPreviousPage);
} else {
  submit.attachEvent("onclick", returnToPreviousPage);
}

Then use preventDefault() (or returnValue = false for older browsers).

function returnToPreviousPage (e) {
  e = e || window.event;
  // validation code

  // if invalid
  if (e.preventDefault) {
    e.preventDefault();
  } else {
    e.returnValue = false;
  }
}

python error: no module named pylab

What you've done by following those directions is created an entirely new Python installation, separate from the system Python that is managed by Ubuntu packages.

Modules you had installed in the system Python (e.g. installed via packages, or by manual installation using the system Python to run the setup process) will not be available, since your /usr/local-based python is configured to look in its own module directories, not the system Python's.

You can re-add missing modules now by building them and installing them using your new /usr/local-based Python.

In Javascript/jQuery what does (e) mean?

$(this).click(function(e) {
    // does something
});

In reference to the above code
$(this) is the element which as some variable.
click is the event that needs to be performed.
the parameter e is automatically passed from js to your function which holds the value of $(this) value and can be used further in your code to do some operation.

How to get a random value from dictionary?

To select 50 random key values from a dictionary set dict_data:

sample = random.sample(set(dict_data.keys()), 50)

How to detect DataGridView CheckBox event change?

It's all about editing the cell, the problem that is the cell didn't edited actually, so you need to save The changes of the cell or the row to get the event when you click the check box so you can use this function:

datagridview.CommitEdit(DataGridViewDataErrorContexts.CurrentCellChange)

with this you can use it even with a different event.

Compile to stand alone exe for C# app in Visual Studio 2010

You just compile it. In the bin\Release (or bin\Debug) folder, the .exe will be in there.

If you're asking how to make an executable which does not rely on the .NET framework at all, then that's a lot harder and you'll need to purchase something like RemoteSoft's Salamader. In general, it's not really worth the bother: Windows Vista comes with .NET framework 2.0 pre-installed already so if you're worried about that, you can just target the 2.0 framework (then only XP users would have to install the framework).

Bootstrap - How to add a logo to navbar class?

Use a image style width and height 100% . This will do the trick, because the image can be resized based on the container.

Example:

<a class="navbar-brand" href="#" style="padding: 4px;margin:auto"> <img src="images/logo.png" style="height:100%;width: auto;" title="mycompanylogo"></a>

Access parent URL from iframe

The problem with the PHP $_SERVER['HTTP_REFFERER'] is that it gives the fully qualified page url of the page that brought you to the parent page. That's not the same as the parent page, itself. Worse, sometimes there is no http_referer, because the person typed in the url of the parent page. So, if I get to your parent page from yahoo.com, then yahoo.com becomes the http_referer, not your page.

Can you put two conditions in an xslt test attribute?

Maybe this is a no-brainer for the xslt-professional, but for me at beginner/intermediate level, this got me puzzled. I wanted to do exactly the same thing, but I had to test a responsetime value from an xml instead of a plain number. Following this thread, I tried this:

<xsl:when test="responsetime/@value &gt;= 5000 and responsetime/@value &lt;= 8999"> 

which generated an error. This works:

<xsl:when test="number(responsetime/@value) &gt;= 5000 and number(responsetime/@value) &lt;= 8999">

Don't really understand why it doesn't work without number(), though. Could it be that without number() the value is treated as a string and you can't compare numbers with a string?

Anyway, hope this saves someone a lot of searching...

Formatting floats in a numpy array

[ round(x,2) for x in [2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01]]

Wildcard string comparison in Javascript

You should use RegExp (they are awesome) an easy solution is:

if( /^bird/.test(animals[i]) ){
    // a bird :D
}

Finding multiple occurrences of a string within a string in Python

>>> for n,c in enumerate(text):
...   try:
...     if c+text[n+1] == "ll": print n
...   except: pass
...
1
10
16

How to set custom header in Volley Request

try this

{
    @Override
       public Map<String, String> getHeaders() throws AuthFailureError {
           String bearer = "Bearer ".concat(token);
            Map<String, String> headersSys = super.getHeaders();
            Map<String, String> headers = new HashMap<String, String>();
            headersSys.remove("Authorization");
            headers.put("Authorization", bearer);
            headers.putAll(headersSys);
            return headers;
       }
};

Automated testing for REST Api

At my work we have recently put together a couple of test suites written in Java to test some RESTful APIs we built. Our Services could invoke other RESTful APIs they depend on. We split it into two suites.


  • Suite 1 - Testing each service in isolation
    • Mock any peer services the API depends on using restito. Other alternatives include rest-driver, wiremock and betamax.
    • Tests the service we are testing and the mocks all run in a single JVM
    • Launches the service in Jetty

I would definitely recommend doing this. It has worked really well for us. The main advantages are:

  • Peer services are mocked, so you needn't perform any complicated data setup. Before each test you simply use restito to define how you want peer services to behave, just like you would with classes in unit tests with Mockito.
  • You can ask the mocked peer services if they were called. You can't do these asserts as easily with real peer services.
  • The suite is super fast as mocked services serve pre-canned in-memory responses. So we can get good coverage without the suite taking an age to run.
  • The suite is reliable and repeatable as its isolated in it's own JVM, so no need to worry about other suites/people mucking about with an shared environment at the same time the suite is running and causing tests to fail.

  • Suite 2 - Full End to End
    • Suite runs against a full environment deployed across several machines
    • API deployed on Tomcat in environment
    • Peer services are real 'as live' full deployments

This suite requires us to do data set up in peer services which means tests generally take more time to write. As much as possible we use REST clients to do data set up in peer services.

Tests in this suite usually take longer to write, so we put most of our coverage in Suite 1. That being said there is still clear value in this suite as our mocks in Suite 1 may not be behaving quite like the real services.


How to install "ifconfig" command in my ubuntu docker image?

You could also consider:

RUN apt-get update && apt-get install -y iputils-ping

(as Contango comments: you must first run apt-get update, to avoid error with missing repository).

See "Replacing ifconfig with ip"

it is most often recommended to move forward with the command that has replaced ifconfig. That command is ip, and it does a great job of stepping in for the out-of-date ifconfig.

But as seen in "Getting a Docker container's IP address from the host", using docker inspect can be more useful depending on your use case.

Batch: Remove file extension

Without looping

I am using this if I simply want to strip the extension from a filename or variable (without listing any directories or existing files):

for %%f in ("%filename%") do set filename=%%~nf

If you want to strip the extension from a full path, use %%dpnf instead:

for %%f in ("%path%") do set path=%%~dpnf

Example:

(Use directly in the console)

@for %f in ("file name.dat") do @echo %~nf
@for %f in ("C:\Dir\file.dat") do @echo %~dpnf

OUTPUT:

file name
C:\Dir\file

how to get current datetime in SQL?

SYSDATETIME() 2007-04-30 13:10:02.0474381
SYSDATETIMEOFFSET()2007-04-30 13:10:02.0474381 -07:00
SYSUTCDATETIME() 2007-04-30 20:10:02.0474381
CURRENT_TIMESTAMP 2007-04-30 13:10:02.047 +
GETDATE() 2007-04-30 13:10:02.047 
GETUTCDATE() 2007-04-30 20:10:02.047

I guess NOW() doesn't work sometime and gives error 'NOW' is not a recognized built-in function name.

Hope it helps!!! Thank You. https://docs.microsoft.com/en-us/sql/t-sql/functions/getdate-transact-sql

tsconfig.json: Build:No inputs were found in config file

I'm not using TypeScript in this project at all so it's quite frustrating having to deal with this. I fixed this by adding a tsconfig.json and an empty file.ts file to the project root. The tsconfig.json contains this:

{
  "compilerOptions": {

    "allowJs": false,
    "noEmit": true // Do not compile the JS (or TS) files in this project on build

  },
  "compileOnSave": false,
  "exclude": [ "src", "wwwroot" ],
  "include": [ "file.ts" ]
}

java doesn't run if structure inside of onclick listener

both your conditions are the same:

if(s < f) {     calc = f - s;     n = s; }else if(f > s){     calc =  s - f;     n = f;  } 

so

if(s < f)   

and

}else if(f > s){ 

are the same

change to

}else if(f < s){ 

How to copy a dictionary and only edit the copy

While dict.copy() and dict(dict1) generates a copy, they are only shallow copies. If you want a deep copy, copy.deepcopy(dict1) is required. An example:

>>> source = {'a': 1, 'b': {'m': 4, 'n': 5, 'o': 6}, 'c': 3}
>>> copy1 = x.copy()
>>> copy2 = dict(x)
>>> import copy
>>> copy3 = copy.deepcopy(x)
>>> source['a'] = 10  # a change to first-level properties won't affect copies
>>> source
{'a': 10, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}
>>> copy1
{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}
>>> copy2
{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}
>>> copy3
{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}
>>> source['b']['m'] = 40  # a change to deep properties WILL affect shallow copies 'b.m' property
>>> source
{'a': 10, 'c': 3, 'b': {'m': 40, 'o': 6, 'n': 5}}
>>> copy1
{'a': 1, 'c': 3, 'b': {'m': 40, 'o': 6, 'n': 5}}
>>> copy2
{'a': 1, 'c': 3, 'b': {'m': 40, 'o': 6, 'n': 5}}
>>> copy3  # Deep copy's 'b.m' property is unaffected
{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}

Regarding shallow vs deep copies, from the Python copy module docs:

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Client to send SOAP request and receive response

The best practice is to reference the WSDL and use it like a web service reference. It's easier and works better, but if you don't have the WSDL, the XSD definitions are a good piece of code.

How to convert a String to Bytearray

In C# running this

UnicodeEncoding encoding = new UnicodeEncoding();
byte[] bytes = encoding.GetBytes("Hello");

Will create an array with

72,0,101,0,108,0,108,0,111,0

byte array

For a character which the code is greater than 255 it will look like this

byte array

If you want a very similar behavior in JavaScript you can do this (v2 is a bit more robust solution, while the original version will only work for 0x00 ~ 0xff)

_x000D_
_x000D_
var str = "Hello?";_x000D_
var bytes = []; // char codes_x000D_
var bytesv2 = []; // char codes_x000D_
_x000D_
for (var i = 0; i < str.length; ++i) {_x000D_
  var code = str.charCodeAt(i);_x000D_
  _x000D_
  bytes = bytes.concat([code]);_x000D_
  _x000D_
  bytesv2 = bytesv2.concat([code & 0xff, code / 256 >>> 0]);_x000D_
}_x000D_
_x000D_
// 72, 101, 108, 108, 111, 31452_x000D_
console.log('bytes', bytes.join(', '));_x000D_
_x000D_
// 72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 220, 122_x000D_
console.log('bytesv2', bytesv2.join(', '));
_x000D_
_x000D_
_x000D_

Can a normal Class implement multiple interfaces?

An interface can extend other interfaces. Also an interface cannot implement any other interface. When it comes to a class, it can extend one other class and implement any number of interfaces.

class A extends B implements C,D{...}

How do I check (at runtime) if one class is a subclass of another?

According to the Python doc, we can also use class.__mro__ attribute or class.mro() method:

class Suit:
    pass
class Heart(Suit):
    pass
class Spade(Suit):
    pass
class Diamond(Suit):
    pass
class Club(Suit):
    pass

>>> Heart.mro()
[<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>]
>>> Heart.__mro__
(<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>)

Suit in Heart.mro()  # True
object in Heart.__mro__  # True
Spade in Heart.mro()  # False

In Java, how to find if first character in a string is upper case without regex

Assuming s is non-empty:

Character.isUpperCase(s.charAt(0))

or, as mentioned by divec, to make it work for characters with code points above U+FFFF:

Character.isUpperCase(s.codePointAt(0));

What is default list styling (CSS)?

You cannot. Whenever there is any style sheet being applied that assigns a property to an element, there is no way to get to the browser defaults, for any instance of the element.

The (disputable) idea of reset.css is to get rid of browser defaults, so that you can start your own styling from a clean desk. No version of reset.css does that completely, but to the extent they do, the author using reset.css is supposed to completely define the rendering.

Tomcat 7 is not running on browser(http://localhost:8080/ )

Double click on the Tomcat Server under the Servers tab in Eclipse Doing that opens a window in the editor with the top heading being Overview opens (there are 2 tabs-Overview and Modules). In that change the options under Server Locations, and g

How to format a date using ng-model?

Since you have used datepicker as a class I'm assuming you are using a Jquery datepicker or something similar.

There is a way to do what you are intending without using moment.js at all, purely using just datepicker and angularjs directives.

I've given a example here in this Fiddle

Excerpts from the fiddle here:

  1. Datepicker has a different format and angularjs format is different, need to find the appropriate match so that date is preselected in the control and is also populated in the input field while the ng-model is bound. The below format is equivalent to 'mediumDate' format of AngularJS.

    $(element).find(".datepicker")
              .datepicker({
                 dateFormat: 'M d, yy'
              }); 
    
  2. The date input directive needs to have an interim string variable to represent the human readable form of date.

  3. Refreshing across different sections of page should happen via events, like $broadcast and $on.

  4. Using filter to represent date in human readable form is possible in ng-model as well but with a temporary model variable.

    $scope.dateValString = $filter('date')($scope.dateVal, 'mediumDate');
    

urlencoded Forward slash is breaking URL

Use a different character and replace the slashes server side

e.g. Drupal.org uses %21 (the excalamation mark character !) to represent the slash in a url parameter.

Both of the links below work:

https://api.drupal.org/api/drupal/includes%21common.inc/7

https://api.drupal.org/api/drupal/includes!common.inc/7

If you're worried that the character may clash with a character in the parameter then use a combination of characters.

So your url would be http://project_name/browse_by_exam/type/tutor_search/keyword/one_-!two/new_search/1/search_exam/0/search_subject/0

change it out with js and convert it back to a slash server side.

CSS white space at bottom of page despite having both min-height and height tag

The problem is the background image on the html element. You appear to have set it to "null" which is not valid. Try removing that CSS rule entirely, or at least setting background-image:none

EDIT: the CSS file says it is "generated" so I don't know exactly what you will be able to edit. The problem is this line:

html { background-color:null !important; background-position:null !important; background-repeat:repeat !important; background-image:url('http://images.freewebs.com/Images/null.gif') !important; }

I'm guessing you've put null as a value and it has set the background to a GIF called 'null'.

Test if a string contains a word in PHP?

_x000D_
_x000D_
use _x000D_
_x000D_
if(stripos($str,'job')){_x000D_
   // do your work_x000D_
}
_x000D_
_x000D_
_x000D_

Cannot resolve symbol 'AppCompatActivity'

Easist Way

  • Open app level build.gradle and remove appcompact-v7 dependency & Sync.
  • Add dependency again & Sync.

Error gone!

Before

before

After

after

How to identify whether a grammar is LL(1), LR(0) or SLR(1)?

With these two steps we can check if it LL(1) or not. Both of them have to be satisfied.

1.If we have the production:A->a1|a2|a3|a4|.....|an. Then,First(a(i)) intersection First(a(j)) must be phi(empty set)[a(i)-a subscript i.]

2.For every non terminal 'A',if First(A) contains epsilon Then First(A) intersection Follow(A) must be phi(empty set).

SSL Proxy/Charles and Android trouble

Thanks for @bkurzius's answer and this update is for Charles 3.10+. (The reason is here)

  1. Open Charles
  2. Go to Proxy > SSL Proxy Settings...
  3. Check “Enable SSL Proxying”
  4. Select “Add location” and enter the host name and port (if needed)
  5. Click ok and make sure the option is checked
  6. Go to Help > SSL Proxying > Install Charles Root Certificate on a Mobile Device or Remote Browser..., and just follow the instruction. (use the Android's browser to download and install the certificate.)
  7. In “Name the certificate” enter whatever you want
  8. Click OK and you should get a message that the certificate was installed

Hibernate: best practice to pull all lazy collections

When having to fetch multiple collections, you need to:

  1. JOIN FETCH one collection
  2. Use the Hibernate.initialize for the remaining collections.

So, in your case, you need a first JPQL query like this one:

MyEntity entity = session.createQuery("select e from MyEntity e join fetch e.addreses where e.id 
= :id", MyEntity.class)
.setParameter("id", entityId)
.getSingleResult();

Hibernate.initialize(entity.persons);

This way, you can achieve your goal with 2 SQL queries and avoid a Cartesian Product.

Android DialogFragment vs Dialog

You can create generic DialogFragment subclasses like YesNoDialog and OkDialog, and pass in title and message if you use dialogs a lot in your app.

public class YesNoDialog extends DialogFragment
{
    public static final String ARG_TITLE = "YesNoDialog.Title";
    public static final String ARG_MESSAGE = "YesNoDialog.Message";

    public YesNoDialog()
    {

    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        Bundle args = getArguments();
        String title = args.getString(ARG_TITLE);
        String message = args.getString(ARG_MESSAGE);

        return new AlertDialog.Builder(getActivity())
            .setTitle(title)
            .setMessage(message)
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, null);
                }
            })
            .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_CANCELED, null);
                }
            })
            .create();
    }
}

Then call it using the following:

    DialogFragment dialog = new YesNoDialog();
    Bundle args = new Bundle();
    args.putString(YesNoDialog.ARG_TITLE, title);
    args.putString(YesNoDialog.ARG_MESSAGE, message);
    dialog.setArguments(args);
    dialog.setTargetFragment(this, YES_NO_CALL);
    dialog.show(getFragmentManager(), "tag");

And handle the result in onActivityResult.

Using pip behind a proxy with CNTLM

A simpler approach might be:

  1. Create a folder named "pip" in your $HOME directory.
  2. Create a file named "pip.ini" (Windows) or "pip.conf" (Linux) in the directory created in step 1
  3. Copy & paste the following lines under the pip.ini/pip.conf:

    [global]
    trusted-host = pypi.python.org
                   pypi.org
                   files.pythonhosted.org 
    

Regular expression to match URLs in Java

The best way to do it now is:

android.util.Patterns.WEB_URL.matcher(linkUrl).matches();

EDIT: Code of Patterns from https://github.com/android/platform_frameworks_base/blob/master/core/java/android/util/Patterns.java :

/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Commonly used regular expression patterns.
 */
public class Patterns {
    /**
     *  Regular expression to match all IANA top-level domains.
     *  List accurate as of 2011/07/18.  List taken from:
     *  http://data.iana.org/TLD/tlds-alpha-by-domain.txt
     *  This pattern is auto-generated by frameworks/ex/common/tools/make-iana-tld-pattern.py
     *
     *  @deprecated Due to the recent profileration of gTLDs, this API is
     *  expected to become out-of-date very quickly. Therefore it is now
     *  deprecated.
     */
    @Deprecated
    public static final String TOP_LEVEL_DOMAIN_STR =
        "((aero|arpa|asia|a[cdefgilmnoqrstuwxz])"
        + "|(biz|b[abdefghijmnorstvwyz])"
        + "|(cat|com|coop|c[acdfghiklmnoruvxyz])"
        + "|d[ejkmoz]"
        + "|(edu|e[cegrstu])"
        + "|f[ijkmor]"
        + "|(gov|g[abdefghilmnpqrstuwy])"
        + "|h[kmnrtu]"
        + "|(info|int|i[delmnoqrst])"
        + "|(jobs|j[emop])"
        + "|k[eghimnprwyz]"
        + "|l[abcikrstuvy]"
        + "|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])"
        + "|(name|net|n[acefgilopruz])"
        + "|(org|om)"
        + "|(pro|p[aefghklmnrstwy])"
        + "|qa"
        + "|r[eosuw]"
        + "|s[abcdeghijklmnortuvyz]"
        + "|(tel|travel|t[cdfghjklmnoprtvwz])"
        + "|u[agksyz]"
        + "|v[aceginu]"
        + "|w[fs]"
        + "|(\u03b4\u03bf\u03ba\u03b9\u03bc\u03ae|\u0438\u0441\u043f\u044b\u0442\u0430\u043d\u0438\u0435|\u0440\u0444|\u0441\u0440\u0431|\u05d8\u05e2\u05e1\u05d8|\u0622\u0632\u0645\u0627\u06cc\u0634\u06cc|\u0625\u062e\u062a\u0628\u0627\u0631|\u0627\u0644\u0627\u0631\u062f\u0646|\u0627\u0644\u062c\u0632\u0627\u0626\u0631|\u0627\u0644\u0633\u0639\u0648\u062f\u064a\u0629|\u0627\u0644\u0645\u063a\u0631\u0628|\u0627\u0645\u0627\u0631\u0627\u062a|\u0628\u06be\u0627\u0631\u062a|\u062a\u0648\u0646\u0633|\u0633\u0648\u0631\u064a\u0629|\u0641\u0644\u0633\u0637\u064a\u0646|\u0642\u0637\u0631|\u0645\u0635\u0631|\u092a\u0930\u0940\u0915\u094d\u0937\u093e|\u092d\u093e\u0930\u0924|\u09ad\u09be\u09b0\u09a4|\u0a2d\u0a3e\u0a30\u0a24|\u0aad\u0abe\u0ab0\u0aa4|\u0b87\u0ba8\u0bcd\u0ba4\u0bbf\u0baf\u0bbe|\u0b87\u0bb2\u0b99\u0bcd\u0b95\u0bc8|\u0b9a\u0bbf\u0b99\u0bcd\u0b95\u0baa\u0bcd\u0baa\u0bc2\u0bb0\u0bcd|\u0baa\u0bb0\u0bbf\u0b9f\u0bcd\u0b9a\u0bc8|\u0c2d\u0c3e\u0c30\u0c24\u0c4d|\u0dbd\u0d82\u0d9a\u0dcf|\u0e44\u0e17\u0e22|\u30c6\u30b9\u30c8|\u4e2d\u56fd|\u4e2d\u570b|\u53f0\u6e7e|\u53f0\u7063|\u65b0\u52a0\u5761|\u6d4b\u8bd5|\u6e2c\u8a66|\u9999\u6e2f|\ud14c\uc2a4\ud2b8|\ud55c\uad6d|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)"
        + "|y[et]"
        + "|z[amw])";

    /**
     *  Regular expression pattern to match all IANA top-level domains.
     *  @deprecated This API is deprecated. See {@link #TOP_LEVEL_DOMAIN_STR}.
     */
    @Deprecated
    public static final Pattern TOP_LEVEL_DOMAIN =
        Pattern.compile(TOP_LEVEL_DOMAIN_STR);

    /**
     *  Regular expression to match all IANA top-level domains for WEB_URL.
     *  List accurate as of 2011/07/18.  List taken from:
     *  http://data.iana.org/TLD/tlds-alpha-by-domain.txt
     *  This pattern is auto-generated by frameworks/ex/common/tools/make-iana-tld-pattern.py
     *
     *  @deprecated This API is deprecated. See {@link #TOP_LEVEL_DOMAIN_STR}.
     */
    @Deprecated
    public static final String TOP_LEVEL_DOMAIN_STR_FOR_WEB_URL =
        "(?:"
        + "(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])"
        + "|(?:biz|b[abdefghijmnorstvwyz])"
        + "|(?:cat|com|coop|c[acdfghiklmnoruvxyz])"
        + "|d[ejkmoz]"
        + "|(?:edu|e[cegrstu])"
        + "|f[ijkmor]"
        + "|(?:gov|g[abdefghilmnpqrstuwy])"
        + "|h[kmnrtu]"
        + "|(?:info|int|i[delmnoqrst])"
        + "|(?:jobs|j[emop])"
        + "|k[eghimnprwyz]"
        + "|l[abcikrstuvy]"
        + "|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])"
        + "|(?:name|net|n[acefgilopruz])"
        + "|(?:org|om)"
        + "|(?:pro|p[aefghklmnrstwy])"
        + "|qa"
        + "|r[eosuw]"
        + "|s[abcdeghijklmnortuvyz]"
        + "|(?:tel|travel|t[cdfghjklmnoprtvwz])"
        + "|u[agksyz]"
        + "|v[aceginu]"
        + "|w[fs]"
        + "|(?:\u03b4\u03bf\u03ba\u03b9\u03bc\u03ae|\u0438\u0441\u043f\u044b\u0442\u0430\u043d\u0438\u0435|\u0440\u0444|\u0441\u0440\u0431|\u05d8\u05e2\u05e1\u05d8|\u0622\u0632\u0645\u0627\u06cc\u0634\u06cc|\u0625\u062e\u062a\u0628\u0627\u0631|\u0627\u0644\u0627\u0631\u062f\u0646|\u0627\u0644\u062c\u0632\u0627\u0626\u0631|\u0627\u0644\u0633\u0639\u0648\u062f\u064a\u0629|\u0627\u0644\u0645\u063a\u0631\u0628|\u0627\u0645\u0627\u0631\u0627\u062a|\u0628\u06be\u0627\u0631\u062a|\u062a\u0648\u0646\u0633|\u0633\u0648\u0631\u064a\u0629|\u0641\u0644\u0633\u0637\u064a\u0646|\u0642\u0637\u0631|\u0645\u0635\u0631|\u092a\u0930\u0940\u0915\u094d\u0937\u093e|\u092d\u093e\u0930\u0924|\u09ad\u09be\u09b0\u09a4|\u0a2d\u0a3e\u0a30\u0a24|\u0aad\u0abe\u0ab0\u0aa4|\u0b87\u0ba8\u0bcd\u0ba4\u0bbf\u0baf\u0bbe|\u0b87\u0bb2\u0b99\u0bcd\u0b95\u0bc8|\u0b9a\u0bbf\u0b99\u0bcd\u0b95\u0baa\u0bcd\u0baa\u0bc2\u0bb0\u0bcd|\u0baa\u0bb0\u0bbf\u0b9f\u0bcd\u0b9a\u0bc8|\u0c2d\u0c3e\u0c30\u0c24\u0c4d|\u0dbd\u0d82\u0d9a\u0dcf|\u0e44\u0e17\u0e22|\u30c6\u30b9\u30c8|\u4e2d\u56fd|\u4e2d\u570b|\u53f0\u6e7e|\u53f0\u7063|\u65b0\u52a0\u5761|\u6d4b\u8bd5|\u6e2c\u8a66|\u9999\u6e2f|\ud14c\uc2a4\ud2b8|\ud55c\uad6d|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)"
        + "|y[et]"
        + "|z[amw]))";

    /**
     * Good characters for Internationalized Resource Identifiers (IRI).
     * This comprises most common used Unicode characters allowed in IRI
     * as detailed in RFC 3987.
     * Specifically, those two byte Unicode characters are not included.
     */
    public static final String GOOD_IRI_CHAR =
        "a-zA-Z0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF";

    public static final Pattern IP_ADDRESS
        = Pattern.compile(
            "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4]"
            + "[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]"
            + "[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}"
            + "|[1-9][0-9]|[0-9]))");

    /**
     * RFC 1035 Section 2.3.4 limits the labels to a maximum 63 octets.
     */
    private static final String IRI
        = "[" + GOOD_IRI_CHAR + "]([" + GOOD_IRI_CHAR + "\\-]{0,61}[" + GOOD_IRI_CHAR + "]){0,1}";

    private static final String GOOD_GTLD_CHAR =
        "a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF";
    private static final String GTLD = "[" + GOOD_GTLD_CHAR + "]{2,63}";
    private static final String HOST_NAME = "(" + IRI + "\\.)+" + GTLD;

    public static final Pattern DOMAIN_NAME
        = Pattern.compile("(" + HOST_NAME + "|" + IP_ADDRESS + ")");

    /**
     *  Regular expression pattern to match most part of RFC 3987
     *  Internationalized URLs, aka IRIs.  Commonly used Unicode characters are
     *  added.
     */
    public static final Pattern WEB_URL = Pattern.compile(
        "((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)"
        + "\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_"
        + "\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?"
        + "(?:" + DOMAIN_NAME + ")"
        + "(?:\\:\\d{1,5})?)" // plus option port number
        + "(\\/(?:(?:[" + GOOD_IRI_CHAR + "\\;\\/\\?\\:\\@\\&\\=\\#\\~"  // plus option query params
        + "\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?"
        + "(?:\\b|$)"); // and finally, a word boundary or end of
                        // input.  This is to stop foo.sure from
                        // matching as foo.su

    public static final Pattern EMAIL_ADDRESS
        = Pattern.compile(
            "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
            "\\@" +
            "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
            "(" +
                "\\." +
                "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
            ")+"
        );

    /**
     * This pattern is intended for searching for things that look like they
     * might be phone numbers in arbitrary text, not for validating whether
     * something is in fact a phone number.  It will miss many things that
     * are legitimate phone numbers.
     *
     * <p> The pattern matches the following:
     * <ul>
     * <li>Optionally, a + sign followed immediately by one or more digits. Spaces, dots, or dashes
     * may follow.
     * <li>Optionally, sets of digits in parentheses, separated by spaces, dots, or dashes.
     * <li>A string starting and ending with a digit, containing digits, spaces, dots, and/or dashes.
     * </ul>
     */
    public static final Pattern PHONE
        = Pattern.compile(                      // sdd = space, dot, or dash
                "(\\+[0-9]+[\\- \\.]*)?"        // +<digits><sdd>*
                + "(\\([0-9]+\\)[\\- \\.]*)?"   // (<digits>)<sdd>*
                + "([0-9][0-9\\- \\.]+[0-9])"); // <digit><digit|sdd>+<digit>

    /**
     *  Convenience method to take all of the non-null matching groups in a
     *  regex Matcher and return them as a concatenated string.
     *
     *  @param matcher      The Matcher object from which grouped text will
     *                      be extracted
     *
     *  @return             A String comprising all of the non-null matched
     *                      groups concatenated together
     */
    public static final String concatGroups(Matcher matcher) {
        StringBuilder b = new StringBuilder();
        final int numGroups = matcher.groupCount();

        for (int i = 1; i <= numGroups; i++) {
            String s = matcher.group(i);

            if (s != null) {
                b.append(s);
            }
        }

        return b.toString();
    }

    /**
     * Convenience method to return only the digits and plus signs
     * in the matching string.
     *
     * @param matcher      The Matcher object from which digits and plus will
     *                     be extracted
     *
     * @return             A String comprising all of the digits and plus in
     *                     the match
     */
    public static final String digitsAndPlusOnly(Matcher matcher) {
        StringBuilder buffer = new StringBuilder();
        String matchingRegion = matcher.group();

        for (int i = 0, size = matchingRegion.length(); i < size; i++) {
            char character = matchingRegion.charAt(i);

            if (character == '+' || Character.isDigit(character)) {
                buffer.append(character);
            }
        }
        return buffer.toString();
    }

    /**
     * Do not create this static utility class.
     */
    private Patterns() {}
}

Using Panel or PlaceHolder

As mentioned in other answers, the Panel generates a <div> in HTML, while the PlaceHolder does not. But there are a lot more reasons why you could choose either one.

Why a PlaceHolder?

Since it generates no tag of it's own you can use it safely inside other element that cannot contain a <div>, for example:

<table>
    <tr>
        <td>Row 1</td>
    </tr>
    <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</table>

You can also use a PlaceHolder to control the Visibility of a group of Controls without wrapping it in a <div>

<asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible="false">
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    <br />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</asp:PlaceHolder>

Why a Panel

It generates it's own <div> and can also be used to wrap a group of Contols. But a Panel has a lot more properties that can be useful to format it's content:

<asp:Panel ID="Panel1" runat="server" Font-Bold="true"
    BackColor="Green" ForeColor="Red" Width="200"
    Height="200" BorderColor="Black" BorderStyle="Dotted">
    Red text on a green background with a black dotted border.
</asp:Panel>

But the most useful feature is the DefaultButton property. When the ID matches a Button in the Panel it will trigger a Form Post with Validation when enter is pressed inside a TextBox. Now a user can submit the Form without pressing the Button.

<asp:Panel ID="Panel1" runat="server" DefaultButton="Button1">
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <br />
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
        ErrorMessage="Input is required" ValidationGroup="myValGroup"
        Display="Dynamic" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
    <br />
    <asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="myValGroup" />
</asp:Panel>

Try the above snippet by pressing enter inside TextBox1

Spring jUnit Testing properties file

Firstly, application.properties in the @PropertySource should read application-test.properties if that's what the file is named (matching these things up matters):

@PropertySource("classpath:application-test.properties ")

That file should be under your /src/test/resources classpath (at the root).

I don't understand why you'd specify a dependency hard coded to a file called application-test.properties. Is that component only to be used in the test environment?

The normal thing to do is to have property files with the same name on different classpaths. You load one or the other depending on whether you are running your tests or not.

In a typically laid out application, you'd have:

src/test/resources/application.properties

and

src/main/resources/application.properties

And then inject it like this:

@PropertySource("classpath:application.properties")

The even better thing to do would be to expose that property file as a bean in your spring context and then inject that bean into any component that needs it. This way your code is not littered with references to application.properties and you can use anything you want as a source of properties. Here's an example: how to read properties file in spring project?

How to delete Tkinter widgets from a window?


clear_btm=Button(master,text="Clear") #this button will delete the widgets 
clear_btm["command"] = lambda one = button1, two = text1, three = entry1: clear(one,two,three) #pass the widgets
clear_btm.pack()

def clear(*widgets):
    for widget in widgets:
        widget.destroy() #finally we are deleting the widgets.

Getting IP address of client

As @martin and this answer explained, it is complicated. There is no bullet-proof way of getting the client's ip address.

The best that you can do is to try to parse "X-Forwarded-For" and rely on request.getRemoteAddr();

public static String getClientIpAddress(HttpServletRequest request) {
    String xForwardedForHeader = request.getHeader("X-Forwarded-For");
    if (xForwardedForHeader == null) {
        return request.getRemoteAddr();
    } else {
        // As of https://en.wikipedia.org/wiki/X-Forwarded-For
        // The general format of the field is: X-Forwarded-For: client, proxy1, proxy2 ...
        // we only want the client
        return new StringTokenizer(xForwardedForHeader, ",").nextToken().trim();
    }
}

How do I get a value of datetime.today() in Python that is "timezone aware"?

Here's a stdlib solution that works on both Python 2 and 3:

from datetime import datetime

now = datetime.now(utc) # Timezone-aware datetime.utcnow()
today = datetime(now.year, now.month, now.day, tzinfo=utc) # Midnight

where today is an aware datetime instance representing the beginning of the day (midnight) in UTC and utc is a tzinfo object (example from the documentation):

from datetime import tzinfo, timedelta

ZERO = timedelta(0)

class UTC(tzinfo):
    def utcoffset(self, dt):
        return ZERO

    def tzname(self, dt):
        return "UTC"

    def dst(self, dt):
        return ZERO

utc = UTC()

Related: performance comparison of several ways to get midnight (start of a day) for a given UTC time. Note: it is more complex, to get midnight for a time zone with a non-fixed UTC offset.

OracleCommand SQL Parameters Binding

string strConn = "Data Source=ORCL134; User ID=user; Password=psd;";

System.Data.OracleClient.OracleConnection con = newSystem.Data.OracleClient.OracleConnection(strConn);
    con.Open();

    System.Data.OracleClient.OracleCommand Cmd = 
        new System.Data.OracleClient.OracleCommand(
            "SELECT * FROM TBLE_Name WHERE ColumnName_year= :year", con);

//for oracle..it is :object_name and for sql it s @object_name
    Cmd.Parameters.Add(new System.Data.OracleClient.OracleParameter("year", (txtFinYear.Text).ToString()));

    System.Data.OracleClient.OracleDataAdapter da = new System.Data.OracleClient.OracleDataAdapter(Cmd);
    DataSet myDS = new DataSet();
    da.Fill(myDS);
    try
    {
        lblBatch.Text = "Batch Number is : " + Convert.ToString(myDS.Tables[0].Rows[0][19]);
        lblBatch.ForeColor = System.Drawing.Color.Green;
        lblBatch.Visible = true;
    }
    catch 
    {
        lblBatch.Text = "No Data Found for the Year : " + txtFinYear.Text;
        lblBatch.ForeColor = System.Drawing.Color.Red;
        lblBatch.Visible = true;   
    }
    da.Dispose();
    con.Close();

Gradle: Could not determine java version from '11.0.2'

Because wrapper version does not support 11+ you can make simple trick to cheat newer version of InteliJ forever.

  press3x Shift -> type "Switch Boot JDK" -> and change for java 8. 

https://blog.jetbrains.com/idea/2015/05/intellij-idea-14-1-4-eap-141-1192-is-available/

Or If you want to work with java 11+ you simply have to update wrapper version to 4.8+

How can moment.js be imported with typescript?

You need to import moment() the function and Moment the class separately in TS.

I found a note in the typescript docs here.

/*~ Note that ES6 modules cannot directly export callable functions
*~ This file should be imported using the CommonJS-style:
*~ import x = require('someLibrary');

So the code to import moment js into typescript actually looks like this:

import { Moment } from 'moment'
....
let moment = require('moment');
...
interface SomeTime {
  aMoment: Moment,
}
...
fn() {
  ...
  someTime.aMoment = moment(...);
  ...
}

How do I execute external program within C code in linux with arguments?

In C

#include <stdlib.h>

system("./foo 1 2 3");

In C++

#include <cstdlib>

std::system("./foo 1 2 3");

Then open and read the file as usual.

System.Data.SqlClient.SqlException: Invalid object name 'dbo.Projects'

This maybe due to an incorrect table name from where you are fetching the data. Please verify the name of the table you mentioned in asmx file and the table created in database.

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

go to "Project-Properties-Configuration Properties-Linker-input-Additional dependencies" then go to the end and type ";ws2_32.lib".

How do you add a JToken to an JObject?

I think you're getting confused about what can hold what in JSON.Net.

  • A JToken is a generic representation of a JSON value of any kind. It could be a string, object, array, property, etc.
  • A JProperty is a single JToken value paired with a name. It can only be added to a JObject, and its value cannot be another JProperty.
  • A JObject is a collection of JProperties. It cannot hold any other kind of JToken directly.

In your code, you are attempting to add a JObject (the one containing the "banana" data) to a JProperty ("orange") which already has a value (a JObject containing {"colour":"orange","size":"large"}). As you saw, this will result in an error.

What you really want to do is add a JProperty called "banana" to the JObject which contains the other fruit JProperties. Here is the revised code:

JObject foodJsonObj = JObject.Parse(jsonText);
JObject fruits = foodJsonObj["food"]["fruit"] as JObject;
fruits.Add("banana", JObject.Parse(@"{""colour"":""yellow"",""size"":""medium""}"));

C# An established connection was aborted by the software in your host machine

This problem appear if two software use same port for connecting to the server
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse or your Software.

Printing all global variables/local variables?

In addition, since info locals does not display the arguments to the function you're in, use

(gdb) info args

For example:

int main(int argc, char *argv[]) {
    argc = 6*7;    //Break here.
    return 0;
}

argc and argv won't be shown by info locals. The message will be "No locals."

Reference: info locals command.

Java: Integer equals vs. ==

The JVM is caching Integer values. Hence the comparison with == only works for numbers between -128 and 127.

Refer: #Immutable_Objects_.2F_Wrapper_Class_Caching

private final static attribute vs private final attribute

Static variable belongs to the class (which means all the objects share that variable). Non static variable belongs to each objects.

public class ExperimentFinal {

private final int a;
private static final int b = 999; 

public ExperimentFinal(int a) {
    super();
    this.a = a;
}
public int getA() {
    return a;
}
public int getB() {
    return b;
}
public void print(int a, int b) {
    System.out.println("final int: " + a + " \nstatic final int: " + b);
}
public static void main(String[] args) {
    ExperimentFinal test = new ExperimentFinal(9);
    test.print(test.getA(), test.getB());
} }

As you can see above example, for "final int" we can assign our variable for each instance (object) of the class, however for "static final int", we should assign a variable in the class (static variable belongs to the class).

Inheriting constructors

This is straight from Bjarne Stroustrup's page:

If you so choose, you can still shoot yourself in the foot by inheriting constructors in a derived class in which you define new member variables needing initialization:

struct B1 {
    B1(int) { }
};

struct D1 : B1 {
    using B1::B1; // implicitly declares D1(int)
    int x;
};

void test()
{
    D1 d(6);    // Oops: d.x is not initialized
    D1 e;       // error: D1 has no default constructor
}

Where can I set path to make.exe on Windows?

I had issues for a whilst not getting Terraform commands to run unless I was in the directory of the exe, even though I set the path correctly.

For anyone else finding this issue, I fixed it by moving the environment variable higher than others!

"Cannot update paths and switch to branch at the same time"

You should go the submodule dir and run git status.

You may see a lot of files were deleted. You may run

  1. git reset .

  2. git checkout .

  3. git fetch -p

  4. git rm --cached submodules //submoudles is your name

  5. git submoudle add ....

How to extract a string using JavaScript Regex?

This code works:

  let str = "governance[string_i_want]"; 
  let res = str.match(/[^governance\[](.*)[^\]]/g);

res will equal "string_i_want". However, in this example res is still an array, so do not treat res like a string.

By grouping the characters I do not want, using [^string], and matching on what is between the brackets, the code extracts the string I want!

You can try it out here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_match_regexp

Good luck.

How to remove single character from a String

public String missingChar(String str, int n) {
  String front = str.substring(0, n);

// Start this substring at n+1 to omit the char.
// Can also be shortened to just str.substring(n+1)
// which goes through the end of the string.

String back = str.substring(n+1, str.length());
  return front + back;
}

OR operator in switch-case?

You cannot use || operators in between 2 case. But you can use multiple case values without using a break between them. The program will then jump to the respective case and then it will look for code to execute until it finds a "break". As a result these cases will share the same code.

switch(value) 
{ 
    case 0: 
    case 1: 
        // do stuff for if case 0 || case 1 
        break; 
    // other cases 
    default: 
        break; 
}

Compare and contrast REST and SOAP web services?

SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.

Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.

By way of illustration here are few calls and their appropriate home with commentary.

getUser(User);

This is a rest operation as you are accessing a resource (data).

switchCategory(User, OldCategory, NewCategory)

REST permits many different data formats where as SOAP only permits XML. While this may seem like it adds complexity to REST because you need to handle multiple formats, in my experience it has actually been quite beneficial. JSON usually is a better fit for data and parses much faster. REST allows better support for browser clients due to it’s support for JSON.

Sleeping in a batch file

UPDATE

The timeout command, available from Windows Vista and onwards should be the command used, as described in another answer to this question. What follows here is an old answer.

Old answer

If you have Python installed, or don't mind installing it (it has other uses too :), just create the following sleep.py script and add it somewhere in your PATH:

import time, sys

time.sleep(float(sys.argv[1]))

It will allow sub-second pauses (for example, 1.5 sec, 0.1, etc.), should you have such a need. If you want to call it as sleep rather than sleep.py, then you can add the .PY extension to your PATHEXT environment variable. On Windows XP, you can edit it in:

My Computer ? Properties (menu) ? Advanced (tab) ? Environment Variables (button) ? System variables (frame)

How to update two tables in one statement in SQL Server 2005?

You can't update multiple tables in one statement, however, you can use a transaction to make sure that two UPDATE statements are treated atomically. You can also batch them to avoid a round trip.

BEGIN TRANSACTION;

UPDATE Table1
  SET Table1.LastName = 'DR. XXXXXX' 
FROM Table1 T1, Table2 T2
WHERE T1.id = T2.id
and T1.id = '011008';

UPDATE Table2
SET Table2.WAprrs = 'start,stop'
FROM Table1 T1, Table2 T2
WHERE T1.id = T2.id
and T1.id = '011008';

COMMIT;

How do I get user IP address in django?

You can use django-ipware which supports Python 2 & 3 and handles IPv4 & IPv6.

Install:

pip install django-ipware

Simple Usage:

# In a view or a middleware where the `request` object is available

from ipware import get_client_ip
ip, is_routable = get_client_ip(request)
if ip is None:
    # Unable to get the client's IP address
else:
    # We got the client's IP address
    if is_routable:
        # The client's IP address is publicly routable on the Internet
    else:
        # The client's IP address is private

# Order of precedence is (Public, Private, Loopback, None)

Advanced Usage:

  • Custom Header - Custom request header for ipware to look at:

    i, r = get_client_ip(request, request_header_order=['X_FORWARDED_FOR'])
    i, r = get_client_ip(request, request_header_order=['X_FORWARDED_FOR', 'REMOTE_ADDR'])
    
  • Proxy Count - Django server is behind a fixed number of proxies:

    i, r = get_client_ip(request, proxy_count=1)
    
  • Trusted Proxies - Django server is behind one or more known & trusted proxies:

    i, r = get_client_ip(request, proxy_trusted_ips=('177.2.2.2'))
    
    # For multiple proxies, simply add them to the list
    i, r = get_client_ip(request, proxy_trusted_ips=('177.2.2.2', '177.3.3.3'))
    
    # For proxies with fixed sub-domain and dynamic IP addresses, use partial pattern
    i, r = get_client_ip(request, proxy_trusted_ips=('177.2.', '177.3.'))
    

Note: read this notice.

How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe?

To simplify Kirubaharan's answer a bit:

df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])
df = df.set_index('Datetime')

And to get rid of unwanted columns (as OP did but did not specify per se in the question):

df = df.drop(['date','time'], axis=1)

Get image dimensions

<?php 
    list($width, $height) = getimagesize("http://site.com/image.png"); 
    $arr = array('h' => $height, 'w' => $width );
?>

Disable vertical scroll bar on div overflow: auto

if you want to disable the scrollbar, but still able to scroll the content of inner DIV, use below code in css,

.divHideScroll::-webkit-scrollbar {
    width: 0 !important
}
.divHideScroll {
    overflow: -moz-scrollbars-none;
}
.divHideScroll {
    -ms-overflow-style: none;
}

divHideScroll is the class name of the target div.

It will work in all major browser (Chrome, Safari, Mozilla, Opera, and IE)

How to make for loops in Java increase by increments other than 1

for(j = 0; j<=90; j = j+3)
{

}

j+3 will not assign the new value to j, add j=j+3 will assign the new value to j and the loop will move up by 3.

j++ is like saying j = j+1, so in that case your assigning the new value to j just like the one above.

Send POST request using NSURLSession

Teja Kumar Bethina's code changed for Swift 3:

    let urlStr = "http://url_to_manage_post_requests"
    let url = URL(string: urlStr)

    var request: URLRequest = URLRequest(url: url!)

    request.httpMethod = "POST"

    request.setValue("application/json", forHTTPHeaderField:"Content-Type")
    request.timeoutInterval = 60.0

    //additional headers
    request.setValue("deviceIDValue", forHTTPHeaderField:"DeviceId")

    let bodyStr = "string or data to add to body of request"
    let bodyData = bodyStr.data(using: String.Encoding.utf8, allowLossyConversion: true)
    request.httpBody = bodyData

    let task = URLSession.shared.dataTask(with: request) {
        (data: Data?, response: URLResponse?, error: Error?) -> Void in

        if let httpResponse = response as? HTTPURLResponse {
            print("responseCode \(httpResponse.statusCode)")
        }

        if error != nil {

            // You can handle error response here
            print("\(error)")
        } else {
            //Converting response to collection formate (array or dictionary)
            do {
                let jsonResult = (try JSONSerialization.jsonObject(with: data!, options:
                    JSONSerialization.ReadingOptions.mutableContainers))

                //success code
            } catch {
                //failure code
            }
        }
    }

    task.resume()

How to get child element by index in Jquery?

var node = document.getElementsByClassName("second")[0].firstElementChild

Disclaimer: Browser compliance on getElementsByClassName and firstElementChild are shaky. DOM-shims fix those problems though.

javascript scroll event for iPhone/iPad?

For iOS you need to use the touchmove event as well as the scroll event like this:

document.addEventListener("touchmove", ScrollStart, false);
document.addEventListener("scroll", Scroll, false);

function ScrollStart() {
    //start of scroll event for iOS
}

function Scroll() {
    //end of scroll event for iOS
    //and
    //start/end of scroll event for other browsers
}

input file appears to be a text format dump. Please use psql

The answer above didn't work for me, this worked:

psql db_development < postgres_db.dump

How to configure the web.config to allow requests of any length

It will also generate error when you pass large string in ajax call parameter.

so for that alway use type post in ajax will resolve your issue 100% and no need to set the length in web.config.

// var UserId= array of 1000 userids

$.ajax({ global: false, url: SitePath + "/User/getAussizzMembersData", "data": { UserIds: UserId}, "type": "POST", "dataType": "JSON" }}

Plotting categorical data with pandas and matplotlib

To plot multiple categorical features as bar charts on the same plot, I would suggest:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(
    {
        "colour": ["red", "blue", "green", "red", "red", "yellow", "blue"],
        "direction": ["up", "up", "down", "left", "right", "down", "down"],
    }
)

categorical_features = ["colour", "direction"]
fig, ax = plt.subplots(1, len(categorical_features))
for i, categorical_feature in enumerate(df[categorical_features]):
    df[categorical_feature].value_counts().plot("bar", ax=ax[i]).set_title(categorical_feature)
fig.show()

enter image description here

Android device is not connected to USB for debugging (Android studio)

The solution for me was following the instructions at https://developer.android.com/studio/run/oem-usb.html#InstallingDriver. Specifically, the key part from that link that helped me to find the solution was this: "Install a USB Driver. First, find the appropriate driver for your device from the OEM drivers table below." This means that you cannot find a single link that applies to everyone as the solution. It will depend on your device! "So I visited the page to get OEM Drivers at https://developer.android.com/studio/run/oem-usb.html#Drivers. In my case, the device I was using was an LG K8 LTE. I had to go to http://www.lg.com/us/support/software-firmware-drivers#, Browse by product and I found the driver I needed under the Model Number "LGAS375 KG K8 ACG - AS375", Cell Phone Product. From http://www.lg.com/us/support-mobile/lg-LGAS375 I used the "Install the USB DRIVER" for Windows (http://tool.lime.gdms.lge.com/dn/downloader.dev?fileKey=UW00120120425).

Depending on the device model you are using, you will need to find the specific drivers that work for your phone, and that should work.

AngularJS toggle class using ng-class

How to use conditional in ng-class:

Solution 1:

<i ng-class="{'icon-autoscroll': autoScroll, 'icon-autoscroll-disabled': !autoScroll}"></i>

Solution 2:

<i ng-class="{true: 'icon-autoscroll', false: 'icon-autoscroll-disabled'}[autoScroll]"></i>

Solution 3 (angular v.1.1.4+ introduced support for ternary operator):

<i ng-class="autoScroll ? 'icon-autoscroll' : 'icon-autoscroll-disabled'"></i>

Plunker

How do I merge my local uncommitted changes into another Git branch?

If it were about committed changes, you should have a look at git-rebase, but as pointed out in comment by VonC, as you're talking about local changes, git-stash would certainly be the good way to do this.

Python Socket Multiple Clients

This program will open 26 sockets where you would be able to connect a lot of TCP clients to it.

#!usr/bin/python
from thread import *
import socket
import sys

def clientthread(conn):
    buffer=""
    while True:
        data = conn.recv(8192)
        buffer+=data
        print buffer
    #conn.sendall(reply)
    conn.close()

def main():
    try:
        host = '192.168.1.3'
        port = 6666
        tot_socket = 26
        list_sock = []
        for i in range(tot_socket):
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
            s.bind((host, port+i))
            s.listen(10)
            list_sock.append(s)
            print "[*] Server listening on %s %d" %(host, (port+i))

        while 1:
            for j in range(len(list_sock)):
                conn, addr = list_sock[j].accept()
                print '[*] Connected with ' + addr[0] + ':' + str(addr[1])
                start_new_thread(clientthread ,(conn,))
        s.close()

    except KeyboardInterrupt as msg:
        sys.exit(0)


if __name__ == "__main__":
    main()

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

The issue has been resolved while installation of the maven settings is provided as External in Eclipse. The navigation settings are Window --> Preferences --> Installations. Select the External as installation Type, provide the Installation home and name and click on Finish. Finally select this as default installations.

Spark RDD to DataFrame python

Try if that works

sc = spark.sparkContext

# Infer the schema, and register the DataFrame as a table.
schemaPeople = spark.createDataFrame(RddName)
schemaPeople.createOrReplaceTempView("RddName")

Convert Text to Uppercase while typing in Text box

I use to do this thing (Code Behind) ASP.NET using VB.NET:

1) Turn AutoPostBack = True in properties of said Textbox

2) Code for Textbox (Event : TextChanged) Me.TextBox1.Text = Me.TextBox1.Text.ToUpper

3) Observation After entering the string variables in TextBox1, when user leaves TextBox1, AutoPostBack fires the code when Text was changed during "TextChanged" event.

What is the point of "Initial Catalog" in a SQL Server connection string?

This is the initial database of the data source when you connect.

Edited for clarity:

If you have multiple databases in your SQL Server instance and you don't want to use the default database, you need some way to specify which one you are going to use.

Recreating a Dictionary from an IEnumerable<KeyValuePair<>>

If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:

Dictionary<string, ArrayList> result = target.GetComponents()
                                      .ToDictionary(x => x.Key, x => x.Value);

There's no such thing as an IEnumerable<T1, T2> but a KeyValuePair<TKey, TValue> is fine.

Oracle Error ORA-06512

The variable pCv is of type VARCHAR2 so when you concat the insert you aren't putting it inside single quotes:

 EXECUTE IMMEDIATE  'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('''||pCv||''', '||pSup||', '||pIdM||')';

Additionally the error ORA-06512 raise when you are trying to insert a value too large in a column. Check the definiton of the table M_pNum_GR and the parameters that you are sending. Just for clarify if you try to insert the value 100 on a NUMERIC(2) field the error will raise.

What is the size of an enum in C?

Just set the last value of the enum to a value large enough to make it the size you would like the enum to be, it should then be that size:

enum value{a=0,b,c,d,e,f,g,h,i,j,l,m,n,last=0xFFFFFFFFFFFFFFFF};

Error: vector does not name a type

Also you can add #include<vector> in the header. When two of the above solutions don't work.

MySQL Data Source not appearing in Visual Studio

I tried to install to VS 2015 using the Web installer. It seemed to work, but there was still no MySQL entry for Data Connections. I ended up going to http://dev.mysql.com/downloads/windows/visualstudio/, using it to uninstall then re-install the connector. Not it works as expected.

Check if string ends with one of the strings from a list

I just came across this, while looking for something else.

I would recommend to go with the methods in the os package. This is because you can make it more general, compensating for any weird case.

You can do something like:

import os

the_file = 'aaaa/bbbb/ccc.ddd'

extensions_list = ['ddd', 'eee', 'fff']

if os.path.splitext(the_file)[-1] in extensions_list:
    # Do your thing.

Multiple selector chaining in jQuery?

If we want to apply the same functionality and features to more than one selectors then we use multiple selector options. I think we can say this feature is used like reusability. write a jquery function and just add multiple selectors in which we want the same features.

Kindly take a look in below example:

_x000D_
_x000D_
$( "div, span, .paragraph, #paraId" ).css( {"font-family": "tahoma", "background": "red"} );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div>Div element</div>_x000D_
<p class="paragraph">Paragraph with class selector</p>_x000D_
<p id="paraId">Paragraph with id selector</p>_x000D_
<span>Span element</span>
_x000D_
_x000D_
_x000D_

I hope it will help you. Namaste

Best way to serialize/unserialize objects in JavaScript?

I had a similar problem and since I couldn't find a sufficient solution, I also created a serialization library for javascript: https://github.com/wavesoft/jbb (as a matter of fact it's a bit more, since it's mainly intended for bundling resources)

It is close to Binary-JSON but it adds a couple of additional features, such as metadata for the objects being encoded and some extra optimizations like data de-duplication, cross-referencing to other bundles and structure-level compression.

However there is a catch: In order to keep the bundle size small there are no type information in the bundle. Such information are provided in a separate "profile" that describes your objects for encoding and decoding. For optimization reasons this information is given in a form of script.

But you can make your life easier using the gulp-jbb-profile (https://github.com/wavesoft/gulp-jbb-profile) utility for generating the encodeing/decoding scripts from simple YAML object specifications like this:

# The 'Person' object has the 'age' and 'isOld'
# properties
Person:
  properties:
    - age
    - isOld

For example you can have a look on the jbb-profile-three profile. When you have your profile ready, you can use JBB like this:

var JBBEncoder = require('jbb/encode');
var MyEncodeProfile = require('profile/profile-encode');

// Create a new bundle
var bundle = new JBBEncoder( 'path/to/bundle.jbb' );

// Add one or more profile(s) in order for JBB
// to understand your custom objects
bundle.addProfile(MyEncodeProfile);

// Encode your object(s) - They can be any valid
// javascript object, or objects described in
// the profiles you added previously.

var p1 = new Person(77);
bundle.encode( p1, 'person' );

var people = [
        new Person(45),
        new Person(77),
        ...
    ];
bundle.encode( people, 'people' );

// Close the bundle when you are done
bundle.close();

And you can read it back like this:

var JBBDecoder = require('jbb/decode');
var MyDecodeProfile = require('profile/profile-decode');

// Instantiate a new binary decoder
var binaryLoader = new JBBDecoder( 'path/to/bundle' );

// Add your decoding profile
binaryLoader.addProfile( MyDecodeProfile );

// Add one or more bundles to load
binaryLoader.add( 'bundle.jbb' );

// Load and callback when ready
binaryLoader.load(function( error, database ) {

    // Your objects are in the database
    // and ready to use!
    var people = database['people'];

});

webpack is not recognized as a internal or external command,operable program or batch file

I had this issue for a long time too. (webpack installed globally etc. but still not recognized) It turned out that I haven't specified enviroment variable for npm (where is file webpack.cmd sitting) So I add to my Path variable

%USERPROFILE%\AppData\Roaming\npm\

If you are using Powershell, you can type the following command to effectively add to your path :

[Environment]::SetEnvironmentVariable("Path", "$env:Path;%USERPROFILE%\AppData\Roaming\npm\", "User")

IMPORTANT : Don't forget to close and re-open your powershell window in order to apply this.

Hope it helps.

Oracle - Best SELECT statement for getting the difference in minutes between two DateTime columns?

By default, oracle date subtraction returns a result in # of days.

So just multiply by 24 to get # of hours, and again by 60 for # of minutes.

Example:

select
  round((second_date - first_date) * (60 * 24),2) as time_in_minutes
from
  (
  select
    to_date('01/01/2008 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as first_date
   ,to_date('01/06/2008 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as second_date
  from
    dual
  ) test_data

How to get selected path and name of the file opened with file dialog?

Sub GetFilePath()

Set myFile = Application.FileDialog(msoFileDialogOpen)

With myFile

.Title = "Choose File"

.AllowMultiSelect = False

If .Show <> -1 Then

Exit Sub

End If

FileSelected = Replace(.SelectedItems(1), .InitialFileName, "")

End With

ActiveSheet.Range("A1") = FileSelected

End Sub

Unbalanced calls to begin/end appearance transitions for <UITabBarController: 0x197870>

As @danh suggested, my issue was that I was presenting the modal vc before the UITabBarController was ready. However, I felt uncomfortable relying on a fixed delay before presenting the view controller (from my testing, I needed to use a 0.05-0.1s delay in performSelector:withDelay:). My solution is to add a block that gets called on UITabBarController's viewDidAppear: method:

PRTabBarController.h:

@interface PRTabBarController : UITabBarController

@property (nonatomic, copy) void (^viewDidAppearBlock)(BOOL animated);

@end

PRTabBarController.m:

#import "PRTabBarController.h"

@implementation PRTabBarController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (self.viewDidAppearBlock) {
        self.viewDidAppearBlock(animated);
    }
}

@end

Now in application:didFinishLaunchingWithOptions:

PRTabBarController *tabBarController = [[PRTabBarController alloc] init];

// UIWindow initialization, etc.

__weak typeof(tabBarController) weakTabBarController = tabBarController;
tabBarController.viewDidAppearBlock = ^(BOOL animated) {
    MyViewController *viewController = [MyViewController new];
    viewController.modalPresentationStyle = UIModalPresentationOverFullScreen;
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
    [weakTabBarController.tabBarController presentViewController:navigationController animated:NO completion:nil];
    weakTabBarController.viewDidAppearBlock = nil;
};

How to manually trigger validation with jQuery validate?

As written in the documentation, the way to trigger form validation programmatically is to invoke validator.form()

var validator = $( "#myform" ).validate();
validator.form();

Tricks to manage the available memory in an R session

Ensure you record your work in a reproducible script. From time-to-time, reopen R, then source() your script. You'll clean out anything you're no longer using, and as an added benefit will have tested your code.

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

An addition to the other answers that didn't work for me: In my case the error occurred due to permission errors. The project got deployed while the tomcat was running as root, later when started as tomcat user I got the error from the question title.

Solution in my case was to set the right permissions, e.x. on a unix system:

cd <tomcat-dir>
chown -R <tomcat-user> *

What is the difference between . (dot) and $ (dollar sign)?

The most important part about $ is that it has the lowest operator precedence.

If you type info you'll see this:

?> :info ($)
($) :: (a -> b) -> a -> b
    -- Defined in ‘GHC.Base’
infixr 0 $

This tells us it is an infix operator with right-associativity that has the lowest possible precedence. Normal function application is left-associative and has highest precedence (10). So $ is something of the opposite.

So then we use it where normal function application or using () doesn't work.

So, for example, this works:

?> head . sort $ "example"
?> e

but this does not:

?> head . sort "example"

because . has lower precedence than sort and the type of (sort "example") is [Char]

?> :type (sort "example")
(sort "example") :: [Char]

But . expects two functions and there isn't a nice short way to do this because of the order of operations of sort and .