Programs & Examples On #Bmp

The BMP File Format, also known as Bitmap Image File or Device Independent Bitmap (DIB) file format or simply a Bitmap, is a Raster graphics image file format used to store bitmap digital images, independently of the display device (such as a graphics adapter), especially on Microsoft Windows and OS/2 operating systems.

Writing BMP image in pure c/c++ without other libraries

C++ answer, flexible API, assumes little-endian system to code-golf it a bit. Note this uses the bmp native y-axis (0 at the bottom).

#include <vector>
#include <fstream>

struct image
{   
    image(int width, int height)
    :   w(width), h(height), rgb(w * h * 3)
    {}
    uint8_t & r(int x, int y) { return rgb[(x + y*w)*3 + 2]; }
    uint8_t & g(int x, int y) { return rgb[(x + y*w)*3 + 1]; }
    uint8_t & b(int x, int y) { return rgb[(x + y*w)*3 + 0]; }

    int w, h;
    std::vector<uint8_t> rgb;
};

template<class Stream>
Stream & operator<<(Stream & out, image const& img)
{   
    uint32_t w = img.w, h = img.h;
    uint32_t pad = w * -3 & 3;
    uint32_t total = 54 + 3*w*h + pad*h;
    uint32_t head[13] = {total, 0, 54, 40, w, h, (24<<16)|1};
    char const* rgb = (char const*)img.rgb.data();

    out.write("BM", 2);
    out.write((char*)head, 52);
    for(uint32_t i=0 ; i<h ; i++)
    {   out.write(rgb + (3 * w * i), 3 * w);
        out.write((char*)&pad, pad);
    }
    return out;
}

int main()
{
    image img(100, 100);
    for(int x=0 ; x<100 ; x++)
    {   for(int y=0 ; y<100 ; y++)
        {   img.r(x,y) = x;
            img.g(x,y) = y;
            img.b(x,y) = 100-x;
        }
    }
    std::ofstream("/tmp/out.bmp") << img;
}

Splitting a string at every n-th character

I recently encountered this issue, and here is the solution I came up with

final int LENGTH = 10;
String test = "Here is a very long description, it is going to be past 10";

Map<Integer,StringBuilder> stringBuilderMap = new HashMap<>();
for ( int i = 0; i < test.length(); i++ ) {
    int position = i / LENGTH; // i<10 then 0, 10<=i<19 then 1, 20<=i<30 then 2, etc.

    StringBuilder currentSb = stringBuilderMap.computeIfAbsent( position, pos -> new StringBuilder() ); // find sb, or create one if not present
    currentSb.append( test.charAt( i ) ); // add the current char to our sb
}

List<String> comments = stringBuilderMap.entrySet().stream()
        .sorted( Comparator.comparing( Map.Entry::getKey ) )
        .map( entrySet -> entrySet.getValue().toString() )
        .collect( Collectors.toList() );
//done



// here you can see the data
comments.forEach( cmt -> System.out.println( String.format( "'%s' ... length= %d", cmt, cmt.length() ) ) );
// PRINTS:
// 'Here is a ' ... length= 10
// 'very long ' ... length= 10
// 'descriptio' ... length= 10
// 'n, it is g' ... length= 10
// 'oing to be' ... length= 10
// ' past 10' ... length= 8

// make sure they are equal
String joinedString = String.join( "", comments );
System.out.println( "\nOriginal strings are equal " + joinedString.equals( test ) );
// PRINTS: Original strings are equal true

Center Oversized Image in Div

based on @Guffa answer
because I lost more than 2 hours to center a very wide image,
for me with a image dimendion of 2500x100px and viewport 1600x1200 or Full HD 1900x1200 works centered like that:

 .imageContainer {
  height: 100px;
  overflow: hidden;
  position: relative;
 }
 .imageCenter {
  width: auto;
  position: absolute;
  left: -10%;
  top: 0;
  margin-left: -500px;
 }
.imageCenter img {
 display: block;
 margin: 0 auto;
 }

I Hope this helps others to finish faster the task :)

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

I actually found something that worked for me. It converts the text to binary and then to UTF8.

Source Text that has encoding issues: If ‘Yes’, what was your last

SELECT CONVERT(CAST(CONVERT(
    (SELECT CONVERT(CAST(CONVERT(english_text USING LATIN1) AS BINARY) USING UTF8) AS res FROM m_translation WHERE id = 865) 
USING LATIN1) AS BINARY) USING UTF8) AS 'result';

Corrected Result text: If ‘Yes’, what was your last

My source was wrongly encoded twice so I had two do it twice. For one time you can use:

SELECT CONVERT(CAST(CONVERT(column_name USING latin1) AS BINARY) USING UTF8) AS res FROM m_translation WHERE id = 865;

Please excuse me for any formatting mistakes

Serialize JavaScript object into JSON string

    function ArrayToObject( arr ) {
    var obj = {};
    for (var i = 0; i < arr.length; ++i){
        var name = arr[i].name;
        var value = arr[i].value;
        obj[name] = arr[i].value;
    }
    return obj;
    }

      var form_data = $('#my_form').serializeArray();
            form_data = ArrayToObject( form_data );
            form_data.action = event.target.id;
            form_data.target = event.target.dataset.event;
            console.log( form_data );
            $.post("/api/v1/control/", form_data, function( response ){
                console.log(response);
            }).done(function( response ) {
                $('#message_box').html('SUCCESS');
            })
            .fail(function(  ) { $('#message_box').html('FAIL'); })
            .always(function(  ) { /*$('#message_box').html('SUCCESS');*/ });

Best IDE for HTML5, Javascript, CSS, Jquery support with GUI building tools

Just as an FYI - "best" questions aren't the norm at SO, but I will give you a list of options, just as a service.

OK then. These two are the ones I used:

Komodo Edit

Aptana Studio 3

and then there is always Eclipse.

*UPDATE 20 March 2013 *

Well, Sublime Text 2 is the one to heavily consider. Heavily.

How can I get CMake to find my alternative Boost installation?

I was finally able to get what I wanted with

cmake -DCMAKE_INSTALL_PREFIX=$TARGET \
    -DBoost_NO_BOOST_CMAKE=TRUE \
    -DBoost_NO_SYSTEM_PATHS=TRUE \
    -DBOOST_ROOT:PATHNAME=$TARGET \
    -DBoost_LIBRARY_DIRS:FILEPATH=${TARGET}/lib

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

The answer from Constantin is spot on but for more background this behavior is inherited from Matlab.

The Matlab behavior is explained in the Figure Setup - Displaying Multiple Plots per Figure section of the Matlab documentation.

subplot(m,n,i) breaks the figure window into an m-by-n matrix of small subplots and selects the ithe subplot for the current plot. The plots are numbered along the top row of the figure window, then the second row, and so forth.

How to submit http form using C#

You can use the HttpWebRequest class to do so.

Example here:

using System;
using System.Net;
using System.Text;
using System.IO;


    public class Test
    {
        // Specify the URL to receive the request.
        public static void Main (string[] args)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);

            // Set some reasonable limits on resources used by this request
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            // Set credentials to use for this request.
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

            Console.WriteLine ("Content length is {0}", response.ContentLength);
            Console.WriteLine ("Content type is {0}", response.ContentType);

            // Get the stream associated with the response.
            Stream receiveStream = response.GetResponseStream ();

            // Pipes the stream to a higher level stream reader with the required encoding format. 
            StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

            Console.WriteLine ("Response stream received.");
            Console.WriteLine (readStream.ReadToEnd ());
            response.Close ();
            readStream.Close ();
        }
    }

/*
The output from this example will vary depending on the value passed into Main 
but will be similar to the following:

Content length is 1542
Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>

*/

The entity type <type> is not part of the model for the current context

Delete the .edmx file and add it again. Especially, if you have upgraded the Entity Framework.

How to use apply a custom drawable to RadioButton?

Give your radiobutton a custom style:

<style name="MyRadioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton">
    <item name="android:button">@drawable/custom_btn_radio</item>
</style>

custom_btn_radio.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_window_focused="false"
          android:drawable="@drawable/btn_radio_on" />
    <item android:state_checked="false" android:state_window_focused="false"
          android:drawable="@drawable/btn_radio_off" />

    <item android:state_checked="true" android:state_pressed="true"
          android:drawable="@drawable/btn_radio_on_pressed" />
    <item android:state_checked="false" android:state_pressed="true"
          android:drawable="@drawable/btn_radio_off_pressed" />

    <item android:state_checked="true" android:state_focused="true"
          android:drawable="@drawable/btn_radio_on_selected" />
    <item android:state_checked="false" android:state_focused="true"
          android:drawable="@drawable/btn_radio_off_selected" />

    <item android:state_checked="false" android:drawable="@drawable/btn_radio_off" />
    <item android:state_checked="true" android:drawable="@drawable/btn_radio_on" />
</selector>

Replace the drawables with your own.

Turning multiple lines into one comma separated line

Using paste command:

paste -d, -s file

The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel

There are multiple ways you can handle this:

  1. If you insist on using PUT you can change the form action to POST and add a hidden method_field that has a value PUTand a hidden csrf field (if you are using blade then you just need to add @csrf_field and {{ method_field('PUT') }}). This way the form would accept the request.

  2. You can simply change the route and form method to POST. It will work just fine since you are the one defining the route and not using the resource group.

A reference to the dll could not be added

My answer is a bit late, but as a quick test, make sure you are using the latest version of libraries.

In my case after updating a nuget library that was referencing another library causing the problem the problem disappeared.

Various ways to remove local Git changes

Use:

git checkout -- <file>

To discard the changes in the working directory.

How do I restrict my EditText input to numerical (possibly decimal and signed) input?

There's no reason to use setRawInputType(), just use setInputType(). However, you have to combine the class and flags with the OR operator:

edit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);

No assembly found containing an OwinStartupAttribute Error

I wanted to get rid of OWIN in the project:

  1. Delete OWIN references and Nuget packages from project
  2. Clean & Rebuild project
  3. Run app

Then I got OWIN error. These steps didn't work, because OWIN.dll was still in bin/ directory.

FIX:

  1. Delete bin/ directory manually
  2. Rebuild project

pass JSON to HTTP POST Request

You don't want multipart, but a "plain" POST request (with Content-Type: application/json) instead. Here is all you need:

var request = require('request');

var requestData = {
  request: {
    slice: [
      {
        origin: "ZRH",
        destination: "DUS",
        date: "2014-12-02"
      }
    ],
    passengers: {
      adultCount: 1,
      infantInLapCount: 0,
      infantInSeatCount: 0,
      childCount: 0,
      seniorCount: 0
    },
    solutions: 2,
    refundable: false
  }
};

request('https://www.googleapis.com/qpxExpress/v1/trips/search?key=myApiKey',
        { json: true, body: requestData },
        function(err, res, body) {
  // `body` is a js object if request was successful
});

cannot find zip-align when publishing app

On a mac with OSX 10.10.5,Android Studio and SDK installed the path is

/Users/mles/Library/Android/sdk/build-tools/23.0.1/zipalign

Hide div element when screen size is smaller than a specific size

The easiest approach I know of is using onresize() func:

   window.onresize = function(event) {
        ...
    }

Here is a fiddle for it

array filter in python?

tuple(set([6, 7, 8, 9, 10, 11, 12]).difference([6, 9, 12]))

How do I check if a file exists in Java?

There are multiple ways to achieve this.

  1. In case of just for existence. It could be file or a directory.

    new File("/path/to/file").exists();
    
  2. Check for file

    File f = new File("/path/to/file"); 
      if(f.exists() && f.isFile()) {}
    
  3. Check for Directory.

    File f = new File("/path/to/file"); 
      if(f.exists() && f.isDirectory()) {}
    
  4. Java 7 way.

    Path path = Paths.get("/path/to/file");
    Files.exists(path)  // Existence 
    Files.isDirectory(path)  // is Directory
    Files.isRegularFile(path)  // Regular file 
    Files.isSymbolicLink(path)  // Symbolic Link
    

What does "yield break;" do in C#?

Tells the iterator that it's reached the end.

As an example:

public interface INode
{
    IEnumerable<Node> GetChildren();
}

public class NodeWithTenChildren : INode
{
    private Node[] m_children = new Node[10];

    public IEnumerable<Node> GetChildren()
    {
        for( int n = 0; n < 10; ++n )
        {
            yield return m_children[ n ];
        }
    }
}

public class NodeWithNoChildren : INode
{
    public IEnumerable<Node> GetChildren()
    {
        yield break;
    }
}

Generate unique random numbers between 1 and 100

To avoid any long and unreliable shuffles, I'd do the following...

  1. Generate an array that contains the number between 1 and 100, in order.
  2. Generate a random number between 1 and 100
  3. Look up the number at this index in the array and store in your results
  4. Remove the elemnt from the array, making it one shorter
  5. Repeat from step 2, but use 99 as the upper limit of the random number
  6. Repeat from step 2, but use 98 as the upper limit of the random number
  7. Repeat from step 2, but use 97 as the upper limit of the random number
  8. Repeat from step 2, but use 96 as the upper limit of the random number
  9. Repeat from step 2, but use 95 as the upper limit of the random number
  10. Repeat from step 2, but use 94 as the upper limit of the random number
  11. Repeat from step 2, but use 93 as the upper limit of the random number

Voila - no repeated numbers.

I may post some actual code later, if anybody is interested.

Edit: It's probably the competitive streak in me but, having seen the post by @Alsciende, I couldn't resist posting the code that I promised.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>8 unique random number between 1 and 100</title>
<script type="text/javascript" language="Javascript">
    function pick(n, min, max){
        var values = [], i = max;
        while(i >= min) values.push(i--);
        var results = [];
        var maxIndex = max;
        for(i=1; i <= n; i++){
            maxIndex--;
            var index = Math.floor(maxIndex * Math.random());
            results.push(values[index]);
            values[index] = values[maxIndex];
        }
        return results;
    }
    function go(){
        var running = true;
        do{
            if(!confirm(pick(8, 1, 100).sort(function(a,b){return a - b;}))){
                running = false;
            }
        }while(running)
    }
</script>
</head>

<body>
    <h1>8 unique random number between 1 and 100</h1>
    <p><button onclick="go()">Click me</button> to start generating numbers.</p>
    <p>When the numbers appear, click OK to generate another set, or Cancel to stop.</p>
</body>

Windows equivalent of the 'tail' command

No exact equivalent. However there exist a native DOS command "more" that has a +n option that will start outputting the file after the nth line:

DOS Prompt:

C:\>more +2 myfile.txt

The above command will output everything after the first 2 lines.
This is actually the inverse of Unix head:

Unix console:

root@server:~$ head -2 myfile.txt

The above command will print only the first 2 lines of the file.

What are the differences between a superkey and a candidate key?

A super key of an entity set is a set of one or more attributes whose values uniquely determine each entity.

A candidate key of an entity set is a minimal super key.

Let's go on with customer, loan and borrower sets that you can find an image from the link == 1

  • Rectangles represent entity sets == 1
  • Diamonds represent relationship set == 1
  • Elipses represent attributes == 1
  • Underline indicates Primary Keys == 1

customer_id is the candidate key of the customer set, loan_number is the candidate key of the loan set.

Although several candidate keys may exist, one of the candidate keys is selected to be the primary key.

Borrower set is formed customer_id and loan_number as a relationship set.

reading from app.config file

Try to rebuild your project - It copies the content of App.config to "<YourProjectName.exe>.config" in the build library.

CMake: How to build external projects and include their targets

cmake's ExternalProject_Add indeed can used, but what I did not like about it - is that it performs something during build, continuous poll, etc... I would prefer to build project during build phase, nothing else. I have tried to override ExternalProject_Add in several attempts, unfortunately without success.

Then I have tried also to add git submodule, but that drags whole git repository, while in certain cases I need only subset of whole git repository. What I have checked - it's indeed possible to perform sparse git checkout, but that require separate function, which I wrote below.

#-----------------------------------------------------------------------------
#
# Performs sparse (partial) git checkout
#
#   into ${checkoutDir} from ${url} of ${branch}
#
# List of folders and files to pull can be specified after that.
#-----------------------------------------------------------------------------
function (SparseGitCheckout checkoutDir url branch)
    if(EXISTS ${checkoutDir})
        return()
    endif()

    message("-------------------------------------------------------------------")
    message("sparse git checkout to ${checkoutDir}...")
    message("-------------------------------------------------------------------")

    file(MAKE_DIRECTORY ${checkoutDir})

    set(cmds "git init")
    set(cmds ${cmds} "git remote add -f origin --no-tags -t master ${url}")
    set(cmds ${cmds} "git config core.sparseCheckout true")

    # This command is executed via file WRITE
    # echo <file or folder> >> .git/info/sparse-checkout")

    set(cmds ${cmds} "git pull --depth=1 origin ${branch}")

    # message("In directory: ${checkoutDir}")

    foreach( cmd ${cmds})
        message("- ${cmd}")
        string(REPLACE " " ";" cmdList ${cmd})

        #message("Outfile: ${outFile}")
        #message("Final command: ${cmdList}")

        if(pull IN_LIST cmdList)
            string (REPLACE ";" "\n" FILES "${ARGN}")
            file(WRITE ${checkoutDir}/.git/info/sparse-checkout ${FILES} )
        endif()

        execute_process(
            COMMAND ${cmdList}
            WORKING_DIRECTORY ${checkoutDir}
            RESULT_VARIABLE ret
        )

        if(NOT ret EQUAL "0")
            message("error: previous command failed, see explanation above")
            file(REMOVE_RECURSE ${checkoutDir})
            break()
        endif()
    endforeach()

endfunction()


SparseGitCheckout(${CMAKE_BINARY_DIR}/catch_197 https://github.com/catchorg/Catch2.git v1.9.7 single_include)
SparseGitCheckout(${CMAKE_BINARY_DIR}/catch_master https://github.com/catchorg/Catch2.git master single_include)

I have added two function calls below just to illustrate how to use the function.

Someone might not like to checkout master / trunk, as that one might be broken - then it's always possible to specify specific tag.

Checkout will be performed only once, until you clear the cache folder.

Xcode 9 error: "iPhone has denied the launch request"

It's an intermittent bug in Xcode - I just stopped and started all my devices and it magically worked (after messing about for 1/2 hour) I had upgraded MacOS overnight to 10.13.04 which obviously upset something! Xcode 9.3, iOS 11.3 watchOS 4.3

How to call another controller Action From a controller in Mvc

if the problem is to call. you can call it using this method.

yourController obj= new yourController();

obj.yourAction();

Meaning of Open hashing and Closed hashing

The use of "closed" vs. "open" reflects whether or not we are locked in to using a certain position or data structure (this is an extremely vague description, but hopefully the rest helps).

For instance, the "open" in "open addressing" tells us the index (aka. address) at which an object will be stored in the hash table is not completely determined by its hash code. Instead, the index may vary depending on what's already in the hash table.

The "closed" in "closed hashing" refers to the fact that we never leave the hash table; every object is stored directly at an index in the hash table's internal array. Note that this is only possible by using some sort of open addressing strategy. This explains why "closed hashing" and "open addressing" are synonyms.

Contrast this with open hashing - in this strategy, none of the objects are actually stored in the hash table's array; instead once an object is hashed, it is stored in a list which is separate from the hash table's internal array. "open" refers to the freedom we get by leaving the hash table, and using a separate list. By the way, "separate list" hints at why open hashing is also known as "separate chaining".

In short, "closed" always refers to some sort of strict guarantee, like when we guarantee that objects are always stored directly within the hash table (closed hashing). Then, the opposite of "closed" is "open", so if you don't have such guarantees, the strategy is considered "open".

Dropdownlist validation in Asp.net Using Required field validator

<asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID" Display="Dynamic" 
    ValidationGroup="g1" runat="server" ControlToValidate="ControlID"
    Text="*" ErrorMessage="ErrorMessage"></asp:RequiredFieldValidator>

How can I remove a trailing newline?

Try the method rstrip() (see doc Python 2 and Python 3)

>>> 'test string\n'.rstrip()
'test string'

Python's rstrip() method strips all kinds of trailing whitespace by default, not just one newline as Perl does with chomp.

>>> 'test string \n \r\n\n\r \n\n'.rstrip()
'test string'

To strip only newlines:

>>> 'test string \n \r\n\n\r \n\n'.rstrip('\n')
'test string \n \r\n\n\r '

There are also the methods strip(), lstrip() and strip():

>>> s = "   \n\r\n  \n  abc   def \n\r\n  \n  "
>>> s.strip()
'abc   def'
>>> s.lstrip()
'abc   def \n\r\n  \n  '
>>> s.rstrip()
'   \n\r\n  \n  abc   def'

How do I print the percent sign(%) in c

there's no explanation in this topic why to print a percentage sign one must type %% and not for example escape character with percentage - \%.

from comp.lang.c FAQ list · Question 12.6 :

The reason it's tricky to print % signs with printf is that % is essentially printf's escape character. Whenever printf sees a %, it expects it to be followed by a character telling it what to do next. The two-character sequence %% is defined to print a single %.

To understand why \% can't work, remember that the backslash \ is the compiler's escape character, and controls how the compiler interprets source code characters at compile time. In this case, however, we want to control how printf interprets its format string at run-time. As far as the compiler is concerned, the escape sequence \% is undefined, and probably results in a single % character. It would be unlikely for both the \ and the % to make it through to printf, even if printf were prepared to treat the \ specially.

so the reason why one must type printf("%%"); to print single % is that's what is defined in printf function. % is an escape character of printf's, and \ of compiler.

SQL count rows in a table

select sum([rows])
from sys.partitions
where object_id=object_id('tablename')
 and index_id in (0,1)

is very fast but very rarely inaccurate.

Remove scrollbar from iframe

This is a last resort, but worth mentioning - you can use the ::-webkit-scrollbar pseudo-element on the iframe's parent to get rid of those famous 90's scroll bars.

::-webkit-scrollbar {
    width: 0px;
    height: 0px;
}

Edit: though it's relatively supported, ::-webkit-scrollbar may not suit all browsers. use with caution :)

Count distinct values

You can do a distinct count as follows:

SELECT COUNT(DISTINCT column_name) FROM table_name;

EDIT:

Following your clarification and update to the question, I see now that it's quite a different question than we'd originally thought. "DISTINCT" has special meaning in SQL. If I understand correctly, you want something like this:

  • 2 customers had 1 pets
  • 3 customers had 2 pets
  • 1 customers had 3 pets

Now you're probably going to want to use a subquery:

select COUNT(*) column_name FROM (SELECT DISTINCT column_name);

Let me know if this isn't quite what you're looking for.

Simple way to query connected USB devices info in Python?

For a system with legacy usb coming back and libusb-1.0, this approach will work to retrieve the various actual strings. I show the vendor and product as examples. It can cause some I/O, because it actually reads the info from the device (at least the first time, anyway.) Some devices don't provide this information, so the presumption that they do will throw an exception in that case; that's ok, so we pass.

import usb.core
import usb.backend.libusb1

busses = usb.busses()
for bus in busses:
    devices = bus.devices
    for dev in devices:
        if dev != None:
            try:
                xdev = usb.core.find(idVendor=dev.idVendor, idProduct=dev.idProduct)
                if xdev._manufacturer is None:
                    xdev._manufacturer = usb.util.get_string(xdev, xdev.iManufacturer)
                if xdev._product is None:
                    xdev._product = usb.util.get_string(xdev, xdev.iProduct)
                stx = '%6d %6d: '+str(xdev._manufacturer).strip()+' = '+str(xdev._product).strip()
                print stx % (dev.idVendor,dev.idProduct)
            except:
                pass

jQuery ID starts with

try:

$("td[id^=" + value + "]")

What bitrate is used for each of the youtube video qualities (360p - 1080p), in regards to flowplayer?

Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:

                   240p       360p        480p        720p        1080p
Resolution      426 x 240   640 x 360   854x480     1280x720    1920x1080
Video Bitrates                   
Maximum         700 Kbps    1000 Kbps   2000 Kbps   4000 Kbps   6000 Kbps
Recommended     400 Kbps    750 Kbps    1000 Kbps   2500 Kbps   4500 Kbps
Minimum         300 Kbps    400 Kbps    500 Kbps    1500 Kbps   3000 Kbps

It would appear as though this is the case, although the numbers dont sync up to the google table above:

// the bitrates, video width and file names for this clip
      bitrates: [
        { url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
        { url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
        { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
      ],

AngularJS : Difference between the $observe and $watch methods

$observe() is a method on the Attributes object, and as such, it can only be used to observe/watch the value change of a DOM attribute. It is only used/called inside directives. Use $observe when you need to observe/watch a DOM attribute that contains interpolation (i.e., {{}}'s).
E.g., attr1="Name: {{name}}", then in a directive: attrs.$observe('attr1', ...).
(If you try scope.$watch(attrs.attr1, ...) it won't work because of the {{}}s -- you'll get undefined.) Use $watch for everything else.

$watch() is more complicated. It can observe/watch an "expression", where the expression can be either a function or a string. If the expression is a string, it is $parse'd (i.e., evaluated as an Angular expression) into a function. (It is this function that is called every digest cycle.) The string expression can not contain {{}}'s. $watch is a method on the Scope object, so it can be used/called wherever you have access to a scope object, hence in

  • a controller -- any controller -- one created via ng-view, ng-controller, or a directive controller
  • a linking function in a directive, since this has access to a scope as well

Because strings are evaluated as Angular expressions, $watch is often used when you want to observe/watch a model/scope property. E.g., attr1="myModel.some_prop", then in a controller or link function: scope.$watch('myModel.some_prop', ...) or scope.$watch(attrs.attr1, ...) (or scope.$watch(attrs['attr1'], ...)).
(If you try attrs.$observe('attr1') you'll get the string myModel.some_prop, which is probably not what you want.)

As discussed in comments on @PrimosK's answer, all $observes and $watches are checked every digest cycle.

Directives with isolate scopes are more complicated. If the '@' syntax is used, you can $observe or $watch a DOM attribute that contains interpolation (i.e., {{}}'s). (The reason it works with $watch is because the '@' syntax does the interpolation for us, hence $watch sees a string without {{}}'s.) To make it easier to remember which to use when, I suggest using $observe for this case also.

To help test all of this, I wrote a Plunker that defines two directives. One (d1) does not create a new scope, the other (d2) creates an isolate scope. Each directive has the same six attributes. Each attribute is both $observe'd and $watch'ed.

<div d1 attr1="{{prop1}}-test" attr2="prop2" attr3="33" attr4="'a_string'"
        attr5="a_string" attr6="{{1+aNumber}}"></div>

Look at the console log to see the differences between $observe and $watch in the linking function. Then click the link and see which $observes and $watches are triggered by the property changes made by the click handler.

Notice that when the link function runs, any attributes that contain {{}}'s are not evaluated yet (so if you try to examine the attributes, you'll get undefined). The only way to see the interpolated values is to use $observe (or $watch if using an isolate scope with '@'). Therefore, getting the values of these attributes is an asynchronous operation. (And this is why we need the $observe and $watch functions.)

Sometimes you don't need $observe or $watch. E.g., if your attribute contains a number or a boolean (not a string), just evaluate it once: attr1="22", then in, say, your linking function: var count = scope.$eval(attrs.attr1). If it is just a constant string – attr1="my string" – then just use attrs.attr1 in your directive (no need for $eval()).

See also Vojta's google group post about $watch expressions.

Parsing JSON array with PHP foreach

You maybe wanted to do the following:

foreach($user->data as $mydata)

    {
         echo $mydata->name . "\n";
         foreach($mydata->values as $values)
         {
              echo $values->value . "\n";
         }
    }        

What does yield mean in PHP?

yield keyword serves for definition of "generators" in PHP 5.5. Ok, then what is a generator?

From php.net:

Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.

A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over.

From this place: generators = generators, other functions (just a simple functions) = functions.

So, they are useful when:

  • you need to do things simple (or simple things);

    generator is really much simplier then implementing the Iterator interface. other hand is, ofcource, that generators are less functional. compare them.

  • you need to generate BIG amounts of data - saving memory;

    actually to save memory we can just generate needed data via functions for every loop iteration, and after iteration utilize garbage. so here main points is - clear code and probably performance. see what is better for your needs.

  • you need to generate sequence, which depends on intermediate values;

    this is extending of the previous thought. generators can make things easier in comparison with functions. check Fibonacci example, and try to make sequence without generator. Also generators can work faster is this case, at least because of storing intermediate values in local variables;

  • you need to improve performance.

    they can work faster then functions in some cases (see previous benefit);

javascript: pause setTimeout();

Typescript implementation based on top rated answer

/** Represents the `setTimeout` with an ability to perform pause/resume actions */
export class Timer {
    private _start: Date;
    private _remaining: number;
    private _durationTimeoutId?: NodeJS.Timeout;
    private _callback: (...args: any[]) => void;
    private _done = false;
    get done () {
        return this._done;
    }

    constructor(callback: (...args: any[]) => void, ms = 0) {
        this._callback = () => {
            callback();
            this._done = true;
        };
        this._remaining = ms;
        this.resume();
    }

    /** pauses the timer */
    pause(): Timer {
        if (this._durationTimeoutId && !this._done) {
            this._clearTimeoutRef();
            this._remaining -= new Date().getTime() - this._start.getTime();
        }
        return this;
    }

    /** resumes the timer */
    resume(): Timer {
        if (!this._durationTimeoutId && !this._done) {
            this._start = new Date;
            this._durationTimeoutId = setTimeout(this._callback, this._remaining);
        }
        return this;
    }

    /** 
     * clears the timeout and marks it as done. 
     * 
     * After called, the timeout will not resume
     */
    clearTimeout() {
        this._clearTimeoutRef();
        this._done = true;
    }

    private _clearTimeoutRef() {
        if (this._durationTimeoutId) {
            clearTimeout(this._durationTimeoutId);
            this._durationTimeoutId = undefined;
        }
    }

}

Installing the Android USB Driver in Windows 7

Just download and install "Samsung Kies" from this link. and everything would work as required.

Before installing, uninstall the drivers you have installed for your device.

Update:

Two possible solutions:

  1. Try with the Google USB driver which comes with the SDK.
  2. Download and install the Samsung USB driver from this link as suggested by Mauricio Gracia Gutierrez

Python - 'ascii' codec can't decode byte

Always encode from unicode to bytes.
In this direction, you get to choose the encoding.

>>> u"??".encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print _
??

The other way is to decode from bytes to unicode.
In this direction, you have to know what the encoding is.

>>> bytes = '\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print bytes
??
>>> bytes.decode('utf-8')
u'\u4f60\u597d'
>>> print _
??

This point can't be stressed enough. If you want to avoid playing unicode "whack-a-mole", it's important to understand what's happening at the data level. Here it is explained another way:

  • A unicode object is decoded already, you never want to call decode on it.
  • A bytestring object is encoded already, you never want to call encode on it.

Now, on seeing .encode on a byte string, Python 2 first tries to implicitly convert it to text (a unicode object). Similarly, on seeing .decode on a unicode string, Python 2 implicitly tries to convert it to bytes (a str object).

These implicit conversions are why you can get UnicodeDecodeError when you've called encode. It's because encoding usually accepts a parameter of type unicode; when receiving a str parameter, there's an implicit decoding into an object of type unicode before re-encoding it with another encoding. This conversion chooses a default 'ascii' decoder, giving you the decoding error inside an encoder.

In fact, in Python 3 the methods str.decode and bytes.encode don't even exist. Their removal was a [controversial] attempt to avoid this common confusion.

...or whatever coding sys.getdefaultencoding() mentions; usually this is 'ascii'

What is the difference between canonical name, simple name and class name in Java Class?

I've been confused by the wide range of different naming schemes as well, and was just about to ask and answer my own question on this when I found this question here. I think my findings fit it well enough, and complement what's already here. My focus is looking for documentation on the various terms, and adding some more related terms that might crop up in other places.

Consider the following example:

package a.b;
class C {
  static class D extends C {
  }
  D d;
  D[] ds;
}
  • The simple name of D is D. That's just the part you wrote when declaring the class. Anonymous classes have no simple name. Class.getSimpleName() returns this name or the empty string. It is possible for the simple name to contain a $ if you write it like this, since $ is a valid part of an identifier as per JLS section 3.8 (even if it is somewhat discouraged).

  • According to the JLS section 6.7, both a.b.C.D and a.b.C.D.D.D would be fully qualified names, but only a.b.C.D would be the canonical name of D. So every canonical name is a fully qualified name, but the converse is not always true. Class.getCanonicalName() will return the canonical name or null.

  • Class.getName() is documented to return the binary name, as specified in JLS section 13.1. In this case it returns a.b.C$D for D and [La.b.C$D; for D[].

  • This answer demonstrates that it is possible for two classes loaded by the same class loader to have the same canonical name but distinct binary names. Neither name is sufficient to reliably deduce the other: if you have the canonical name, you don't know which parts of the name are packages and which are containing classes. If you have the binary name, you don't know which $ were introduced as separators and which were part of some simple name. (The class file stores the binary name of the class itself and its enclosing class, which allows the runtime to make this distinction.)

  • Anonymous classes and local classes have no fully qualified names but still have a binary name. The same holds for classes nested inside such classes. Every class has a binary name.

  • Running javap -v -private on a/b/C.class shows that the bytecode refers to the type of d as La/b/C$D; and that of the array ds as [La/b/C$D;. These are called descriptors, and they are specified in JVMS section 4.3.

  • The class name a/b/C$D used in both of these descriptors is what you get by replacing . by / in the binary name. The JVM spec apparently calls this the internal form of the binary name. JVMS section 4.2.1 describes it, and states that the difference from the binary name were for historical reasons.

  • The file name of a class in one of the typical filename-based class loaders is what you get if you interpret the / in the internal form of the binary name as a directory separator, and append the file name extension .class to it. It's resolved relative to the class path used by the class loader in question.

How to specify font attributes for all elements on an html web page?

If you specify CSS attributes for your body element it should apply to anything within <body></body> so long as you don't override them later in the stylesheet.

How to check java bit version on Linux?

Why don't you examine System.getProperty("os.arch") value in your code?

JSONException: Value of type java.lang.String cannot be converted to JSONObject

This is simple way (thanks Gson)

JsonParser parser = new JsonParser();
String retVal = parser.parse(param).getAsString();

https://gist.github.com/MustafaFerhan/25906d2be6ca109f61ce#file-evaluatejavascript-string-problem

Is the MIME type 'image/jpg' the same as 'image/jpeg'?

The important thing to note here is that the mime type is not the same as the file extension. Sometimes, however, they have the same value.

https://www.iana.org/assignments/media-types/media-types.xhtml includes a list of registered Mime types, though there is nothing stopping you from making up your own, as long as you are at both the sending and the receiving end. Here is where Microsoft comes in to the picture.

Where there is a lot of confusion is the fact that operating systems have their own way of identifying file types by using the tail end of the file name, referred to as the extension. In modern operating systems, the whole name is one long string, but in more primitive operating systems, it is treated as a separate attribute.

The OS which caused the confusion is MSDOS, which had limited the extension to 3 characters. This limitation is inherited to this day in devices, such as SD cards, which still store data in the same way.

One side effect of this limitation is that some file extensions, such as .gif match their Mime Type, image/gif, while others are compromised. This includes image/jpeg whose extension is shortened to .jpg. Even in modern Windows, where the limitation is lifted, Microsoft never let the past go, and so the file extension is still the shortened version.

Given that that:

  1. File Extensions are not File Types
  2. Historically, some operating systems had serious file name limitations
  3. Some operating systems will just go ahead and make up their own rules

The short answer is:

  • Technically, there is no such thing as image/jpg, so the answer is that it is not the same as image/jpeg
  • That won’t stop some operating systems and software from treating it as if it is the same

While we’re at it …

Legacy versions of Internet Explorer took the liberty of uploading jpeg files with the Mime Type of image/pjpeg, which, of course, just means more work for everybody else. They also uploaded png files as image/x-png.

Violation Long running JavaScript task took xx ms

These are just warnings as everyone mentioned. However, if you're keen on resolving these (which you should), then you need to identify what is causing the warning first. There's no one reason due to which you can get force reflow warning. Someone has created a list for some possible options. You can follow the discussion for more information.
Here's the gist of the possible reasons:

What forces layout / reflow

All of the below properties or methods, when requested/called in JavaScript, will trigger the browser to synchronously calculate the style and layout*. This is also called reflow or layout thrashing, and is common performance bottleneck.

Element

Box metrics
  • elem.offsetLeft, elem.offsetTop, elem.offsetWidth, elem.offsetHeight, elem.offsetParent
  • elem.clientLeft, elem.clientTop, elem.clientWidth, elem.clientHeight
  • elem.getClientRects(), elem.getBoundingClientRect()
Scroll stuff
  • elem.scrollBy(), elem.scrollTo()
  • elem.scrollIntoView(), elem.scrollIntoViewIfNeeded()
  • elem.scrollWidth, elem.scrollHeight
  • elem.scrollLeft, elem.scrollTop also, setting them
Focus
  • elem.focus() can trigger a double forced layout (source)
Also…
  • elem.computedRole, elem.computedName
  • elem.innerText (source)

getComputedStyle

window.getComputedStyle() will typically force style recalc (source)

window.getComputedStyle() will force layout, as well, if any of the following is true:

  1. The element is in a shadow tree
  2. There are media queries (viewport-related ones). Specifically, one of the following: (source) * min-width, min-height, max-width, max-height, width, height * aspect-ratio, min-aspect-ratio, max-aspect-ratio
    • device-pixel-ratio, resolution, orientation
  3. The property requested is one of the following: (source)
    • height, width * top, right, bottom, left * margin [-top, -right, -bottom, -left, or shorthand] only if the margin is fixed. * padding [-top, -right, -bottom, -left, or shorthand] only if the padding is fixed. * transform, transform-origin, perspective-origin * translate, rotate, scale * webkit-filter, backdrop-filter * motion-path, motion-offset, motion-rotation * x, y, rx, ry

window

  • window.scrollX, window.scrollY
  • window.innerHeight, window.innerWidth
  • window.getMatchedCSSRules() only forces style

Forms

  • inputElem.focus()
  • inputElem.select(), textareaElem.select() (source)

Mouse events

  • mouseEvt.layerX, mouseEvt.layerY, mouseEvt.offsetX, mouseEvt.offsetY (source)

document

  • doc.scrollingElement only forces style

Range

  • range.getClientRects(), range.getBoundingClientRect()

SVG

contenteditable

  • Lots & lots of stuff, …including copying an image to clipboard (source)

Check more here.

Also, here's Chromium source code from the original issue and a discussion about a performance API for the warnings.


Edit: There's also an article on how to minimize layout reflow on PageSpeed Insight by Google. It explains what browser reflow is:

Reflow is the name of the web browser process for re-calculating the positions and geometries of elements in the document, for the purpose of re-rendering part or all of the document. Because reflow is a user-blocking operation in the browser, it is useful for developers to understand how to improve reflow time and also to understand the effects of various document properties (DOM depth, CSS rule efficiency, different types of style changes) on reflow time. Sometimes reflowing a single element in the document may require reflowing its parent elements and also any elements which follow it.

In addition, it explains how to minimize it:

  1. Reduce unnecessary DOM depth. Changes at one level in the DOM tree can cause changes at every level of the tree - all the way up to the root, and all the way down into the children of the modified node. This leads to more time being spent performing reflow.
  2. Minimize CSS rules, and remove unused CSS rules.
  3. If you make complex rendering changes such as animations, do so out of the flow. Use position-absolute or position-fixed to accomplish this.
  4. Avoid unnecessary complex CSS selectors - descendant selectors in particular - which require more CPU power to do selector matching.

Send a base64 image in HTML email

Support, unfortunately, is brutal at best. Here's a post on the topic:

https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/

And the post content: enter image description here

tSQL - Conversion from varchar to numeric works for all but integer

Try this

declare @v varchar(20)
set @v = 'Number'
select case when isnumeric(@v) = 1 then @v
else @v end

and

declare @v varchar(20)
set @v = '7082.7758172'
select case when isnumeric(@v) = 1 then @v
else convert(numeric(18,0),@v) end

How to install a plugin in Jenkins manually

If you use Docker, you should read this file: https://github.com/cloudbees/jenkins-ci.org-docker/blob/master/plugins.sh

Example of a parent Dockerfile:

FROM jenkins
COPY plugins.txt /plugins.txt
RUN /usr/local/bin/plugins.sh /plugins.txt

plugins.txt

<name>:<version>
<name2>:<version2>

ubuntu "No space left on device" but there is tons of space

It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.

Try unmounting the overflow partition:

umount /tmp

or

umount overflow

How to Install Windows Phone 8 SDK on Windows 7

Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator

And another link here

AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).

Best way to access a control on another form in Windows Forms?

Instead of making the control public, you can create a property that controls its visibility:

public bool ControlIsVisible
{
     get { return control.Visible; }
     set { control.Visible = value; }
}

This creates a proper accessor to that control that won't expose the control's whole set of properties.

How to read Data from Excel sheet in selenium webdriver

package com.test.utitlity;

import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class readExcel extends globalVariables {

    /**
     * @param args
     * @throws IOException 
     */
    public static void readExcel(int rowcounter) throws IOException{

        XSSFWorkbook srcBook = new XSSFWorkbook("./prop.xlsx");     
        XSSFSheet sourceSheet = srcBook.getSheetAt(0);
        int rownum=rowcounter;
        XSSFRow sourceRow = sourceSheet.getRow(rownum);
        XSSFCell cell1=sourceRow.getCell(0);
        XSSFCell cell2=sourceRow.getCell(1);
        XSSFCell cell3=sourceRow.getCell(2);
        System.out.println(cell1);
        System.out.println(cell2);
        System.out.println(cell3);



}

}

Android : How to read file in bytes?

Since the accepted BufferedInputStream#read isn't guaranteed to read everything, rather than keeping track of the buffer sizes myself, I used this approach:

    byte bytes[] = new byte[(int) file.length()];
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
    DataInputStream dis = new DataInputStream(bis);
    dis.readFully(bytes);

Blocks until a full read is complete, and doesn't require extra imports.

Heroku deployment error H10 (App crashed)

See if you get

bash: bin/rails: No such file or directory

in logs while running (heroku logs -t) command if yes then please Run

bundle exec rake rails:update

Don't overwrite your files, in the end this command will create

  create  bin
  create  bin/bundle
  create  bin/rails
  create  bin/rake

push these files to heroku and you are done.

How to trigger a file download when clicking an HTML button or JavaScript

HTML:

<button type="submit" onclick="window.open('file.doc')">Download!</button>

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

add this at the top of file,

header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");

What exactly is \r in C language?

' \r ' means carriage return.

The \r means nothing special as a consequence.For character-mode terminals (typically emulating even-older printing ones as above), in raw mode, \r and \n act similarly (except both in terms of the cursor, as there is no carriage or roller . Historically a \n was used to move the carriage down, while the \r was used to move the carriage back to the left side of the screen.

How do I use typedef and typedef enum in C?

typedef defines a new data type. So you can have:

typedef char* my_string;
typedef struct{
  int member1;
  int member2;
} my_struct;

So now you can declare variables with these new data types

my_string s;
my_struct x;

s = "welcome";
x.member1 = 10;

For enum, things are a bit different - consider the following examples:

enum Ranks {FIRST, SECOND};
int main()
{
   int data = 20;
   if (data == FIRST)
   {
      //do something
   }
}

using typedef enum creates an alias for a type:

typedef enum Ranks {FIRST, SECOND} Order;
int main()
{
   Order data = (Order)20;  // Must cast to defined type to prevent error

   if (data == FIRST)
   {
      //do something
   }
}

Printing the value of a variable in SQL Developer

select View-->DBMS Output in menu and

How can I parse a YAML file from a Linux shell script?

You can also consider using Grunt (The JavaScript Task Runner). Can be easily integrated with shell. It supports reading YAML (grunt.file.readYAML) and JSON (grunt.file.readJSON) files.

This can be achieved by creating a task in Gruntfile.js (or Gruntfile.coffee), e.g.:

module.exports = function (grunt) {

    grunt.registerTask('foo', ['load_yml']);

    grunt.registerTask('load_yml', function () {
        var data = grunt.file.readYAML('foo.yml');
        Object.keys(data).forEach(function (g) {
          // ... switch (g) { case 'my_key':
        });
    });

};

then from shell just simply run grunt foo (check grunt --help for available tasks).

Further more you can implement exec:foo tasks (grunt-exec) with input variables passed from your task (foo: { cmd: 'echo bar <%= foo %>' }) in order to print the output in whatever format you want, then pipe it into another command.


There is also similar tool to Grunt, it's called gulp with additional plugin gulp-yaml.

Install via: npm install --save-dev gulp-yaml

Sample usage:

var yaml = require('gulp-yaml');

gulp.src('./src/*.yml')
  .pipe(yaml())
  .pipe(gulp.dest('./dist/'))

gulp.src('./src/*.yml')
  .pipe(yaml({ space: 2 }))
  .pipe(gulp.dest('./dist/'))

gulp.src('./src/*.yml')
  .pipe(yaml({ safe: true }))
  .pipe(gulp.dest('./dist/'))

To more options to deal with YAML format, check YAML site for available projects, libraries and other resources which can help you to parse that format.


Other tools:

  • Jshon

    parses, reads and creates JSON

Split a python list into other "sublists" i.e smaller lists

I'd say

chunks = [data[x:x+100] for x in range(0, len(data), 100)]

If you are using python 2.x instead of 3.x, you can be more memory-efficient by using xrange(), changing the above code to:

chunks = [data[x:x+100] for x in xrange(0, len(data), 100)]

How to remove the arrow from a select element in Firefox

I know this question is a bit old, but since it turns up on google, and this is a "new" solution:

appearance: normal Seems to work fine in Firefox for me (version 5 now). but not in Opera and IE8/9

As a workaround for Opera and IE9, I used the :before pseudoselector to create a new white box and put that on top of the arrow.

Unfortunately, In IE8 this doesn't work. The box is rendered correctly, but the arrow just sticks out anyway... :-/

Using select:before works fine in Opera, but not in IE. If I look at the developer tools, I see it is reading the rules correctly, and then just ignores them (they're crossed out). So I use a <span class="selectwrap"> around the actual <select>.

select {
  -webkit-appearance: normal;
  -moz-appearance: normal;
  appearance: normal;
}
.selectwrap { position: relative; }
.selectwrap:before {
  content: "";
  height: 0;
  width: 0;
  border: .9em solid red;
  background-color: red;
  position: absolute;
  right: -.1em;
  z-index: 42;
}

You may need to tweak this a bit, but this works for me!

Disclaimer: I'm using this to get a good looking hardcopy of a webpage with forms so I don't need to create a second page. I'm not a 1337 haxx0r who wants red scrollbars, <marquee> tags, and whatnot :-) Please do not apply excessive styling to forms unless you have a very good reason.

Selecting a Linux I/O Scheduler

You can set this at boot by adding the "elevator" parameter to the kernel cmdline (such as in grub.cfg)

Example:

elevator=deadline

This will make "deadline" the default I/O scheduler for all block devices.

If you'd like to query or change the scheduler after the system has booted, or would like to use a different scheduler for a specific block device, I recommend installing and use the tool ioschedset to make this easy.

https://github.com/kata198/ioschedset

If you're on Archlinux it's available in aur:

https://aur.archlinux.org/packages/ioschedset

Some example usage:

# Get i/o scheduler for all block devices
[username@hostname ~]$ io-get-sched
sda:    bfq
sr0:    bfq

# Query available I/O schedulers
[username@hostname ~]$ io-set-sched --list
mq-deadline kyber bfq none

# Set sda to use "kyber"
[username@hostname ~]$ io-set-sched kyber /dev/sda
Must be root to set IO Scheduler. Rerunning under sudo...

[sudo] password for username:
+ Successfully set sda to 'kyber'!

# Get i/o scheduler for all block devices to assert change
[username@hostname ~]$ io-get-sched
sda:    kyber
sr0:    bfq

# Set all block devices to use 'deadline' i/o scheduler
[username@hostname ~]$ io-set-sched deadline
Must be root to set IO Scheduler. Rerunning under sudo...

+ Successfully set sda to 'deadline'!
+ Successfully set sr0 to 'deadline'!

# Get the current block scheduler just for sda
[username@hostname ~]$ io-get-sched sda
sda:    mq-deadline

Usage should be self-explanatory. The tools are standalone and only require bash.

Hope this helps!

EDIT: Disclaimer, these are scripts I wrote.

How to redirect on another page and pass parameter in url from table?

Bind the button, this is done with jQuery:

$("#my-table input[type='button']").click(function(){
    var parameter = $(this).val();
    window.location = "http://yoursite.com/page?variable=" + parameter;
});

Difference between scaling horizontally and vertically for databases

SQL databases like Oracle, db2 also support Horizontal scaling through Shared disk cluster. For example Oracle RAC, IBM DB2 purescale or Sybase ASE Cluster edition. New node can be added to Oracle RAC system or DB2 purescale system to achieve horizontal scaling.

But the approach is different from noSQL databases (like mongodb, CouchDB or IBM Cloudant) is that the data sharding is not part of Horizontal scaling. In noSQL databases data is shraded during horizontal scaling.

Sending mass email using PHP

You may consider using CRON for that kind of operation. Sending mass mail at once is certainly not good, it may be detected as spam, ddos, crash your server etc.

So CRON could be a great solution, send 100 mails at once, then wait a few minutes, next 100, etc.

In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?

yeah, this happens sometimes for no apparent reason. You can go to the "Problems"-Tab (right next to console output) and see the error message, so maybe you can narrow it down that way.

C# binary literals

Basically, I think the answer is NO, there is no easy way. Use decimal or hexadecimal constants - they are simple and clear. @RoyTinkers answer is also good - use a comment.

int someHexFlag = 0x010; // 000000010000
int someDecFlag = 8;     // 000000001000

The others answers here present several useful work-a rounds, but I think they aren't better then the simple answer. C# language designers probably considered a '0b' prefix unnecessary. HEX is easy to convert to binary, and most programmers are going to have to know the DEC equivalents of 0-8 anyways.

Also, when examining values in the debugger, they will be displayed has HEX or DEC.

Setting up a git remote origin

You can include the branch to track when setting up remotes, to keep things working as you might expect:

git remote add --track master origin [email protected]:group/project.git   # git
git remote add --track master origin [email protected]:group/project.git   # git w/IP
git remote add --track master origin http://github.com/group/project.git   # http
git remote add --track master origin http://172.16.1.100/group/project.git # http w/IP
git remote add --track master origin /Volumes/Git/group/project/           # local
git remote add --track master origin G:/group/project/                     # local, Win

This keeps you from having to manually edit your git config or specify branch tracking manually.

jQuery UI Dialog OnBeforeUnload

this works for me

$(window).bind('beforeunload', function() {
      return 'Do you really want to leave?' ;
});

Remove last specific character in a string c#

Try string.TrimEnd():

Something = Something.TrimEnd(',');

Sql connection-string for localhost server

You can also use Dot(.) for local key i.e;

Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True

If you have the default server instance i.e. MSSQLSERVER, then just use dot for Data Source.

Data Source=.;Initial Catalog=master;Integrated Security=True

How do I dynamically change the content in an iframe using jquery?

<html>
  <head>
    <script type="text/javascript" src="jquery.js"></script>
    <script>
      $(document).ready(function(){
        var locations = ["http://webPage1.com", "http://webPage2.com"];
        var len = locations.length;
        var iframe = $('#frame');
        var i = 0;
        setInterval(function () {
            iframe.attr('src', locations[++i % len]);
        }, 30000);
      });
    </script>
  </head>
  <body>
    <iframe id="frame"></iframe>
  </body>
</html>

How do I horizontally center a span element inside a div

I assume you want to center them on one line and not on two separate lines based on your fiddle. If that is the case, try the following css:

 div { background:red;
      overflow:hidden;
}
span { display:block;
       margin:0 auto;
       width:200px;
}
span a { padding:5px 10px;
         color:#fff;
         background:#222;
}

I removed the float since you want to center it, and then made the span surrounding the links centered by adding margin:0 auto to them. Finally, I added a static width to the span. This centers the links on one line within the red div.

Credit card expiration dates - Inclusive or exclusive?

In my experience, it has expired at the end of that month. That is based on the fact that I can use it during that month, and that month is when my bank sends a new one.

Can table columns with a Foreign Key be NULL?

I also stuck on this issue. But I solved simply by defining the foreign key as unsigned integer. Find the below example-

CREATE TABLE parent (
   id int(10) UNSIGNED NOT NULL,
    PRIMARY KEY (id)
) ENGINE=INNODB;

CREATE TABLE child (
    id int(10) UNSIGNED NOT NULL,
    parent_id int(10) UNSIGNED DEFAULT NULL,
    FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE
) ENGINE=INNODB;

What is the difference between a static and a non-static initialization code block

"final" guarantees that a variable must be initialized before end of object initializer code. Likewise "static final" guarantees that a variable will be initialized by the end of class initialization code. Omitting the "static" from your initialization code turns it into object initialization code; thus your variable no longer satisfies its guarantees.

Stripping everything but alphanumeric chars from a string in Python

sent = "".join(e for e in sent if e.isalpha())

How to show git log history (i.e., all the related commits) for a sub directory of a git repo?

The other answers only show the changed files.

git log -p DIR is very useful, if you need the full diff of all changed files in a specific subdirectory.

Example: Show all detailed changes in a specific version range

git log -p 8a5fb..HEAD -- A B

commit 62ad8c5d
Author: Scott Tiger
Date:   Mon Nov 27 14:25:29 2017 +0100

    My comment

...
@@ -216,6 +216,10 @@ public class MyClass {

+  Added
-  Deleted

What is the reason behind "non-static method cannot be referenced from a static context"?

A static method relates an action to a type of object, whereas the non static method relates an action to an instance of that type of object. Typically it is a method that does something with relation to the instance.

Ex:

class Car might have a wash method, which would indicate washing a particular car, whereas a static method would apply to the type car.

Best Way to Refresh Adapter/ListView on Android

adapter.notifyDataSetChanged();

changing default x range in histogram matplotlib

plt.hist(hmag, 30, range=[6.5, 12.5], facecolor='gray', align='mid')

What is the best way to calculate a checksum for a file that is on my machine?

Hashing is a standalone application that performs MD5, SHA-1 and SHA-2 family. Built upon OpenSSL.

Batch file script to zip files

This is link by Tomas has a well written script to zip contents of a folder.

To make it work just copy the script into a batch file and execute it by specifying the folder to be zipped(source).

No need to mention destination directory as it is defaulted in the script to Desktop ("%USERPROFILE%\Desktop")

Copying the script here, just incase the web-link is down:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

SET sourceDirPath=%1
IF [%2] EQU [] (
  SET destinationDirPath="%USERPROFILE%\Desktop"
) ELSE (
  SET destinationDirPath="%2"
)
IF [%3] EQU [] (
  SET destinationFileName="%~n1%.zip"
) ELSE (
  SET destinationFileName="%3"
)
SET tempFilePath=%TEMP%\FilesToZip.txt
TYPE NUL > %tempFilePath%

FOR /F "DELIMS=*" %%i IN ('DIR /B /S /A-D "%sourceDirPath%"') DO (
  SET filePath=%%i
  SET dirPath=%%~dpi
  SET dirPath=!dirPath:~0,-1!
  SET dirPath=!dirPath:%sourceDirPath%=!
  SET dirPath=!dirPath:%sourceDirPath%=!
  ECHO .SET DestinationDir=!dirPath! >> %tempFilePath%
  ECHO "!filePath!" >> %tempFilePath%
)

MAKECAB /D MaxDiskSize=0 /D CompressionType=MSZIP /D Cabinet=ON /D Compress=ON /D UniqueFiles=OFF /D DiskDirectoryTemplate=%destinationDirPath% /D CabinetNameTemplate=%destinationFileName%  /F %tempFilePath% > NUL 2>&1

DEL setup.inf > NUL 2>&1
DEL setup.rpt > NUL 2>&1
DEL %tempFilePath% > NUL 2>&1

How to get the MD5 hash of a file in C++?

For anyone redirected from "https://stackoverflow.com/questions/4393017/md5-implementation-in-c" because it's been incorrectly labelled a duplicate.

The example located here works:

http://www.zedwood.com/article/cpp-md5-function

If you are compiling in VC++2010 then you will need to change his main.cpp to this:

#include <iostream> //for std::cout
#include <string.h> //for std::string
#include "MD5.h"

using std::cout; using std::endl;

int main(int argc, char *argv[])
{
    std::string Temp =  md5("The quick brown fox jumps over the lazy dog");
    cout << Temp.c_str() << endl;

    return 0;
}

You will have to change the MD5 class slightly if you are to read in a char * array instead of a string to answer the question on this page here.

EDIT:

Apparently modifying the MD5 library isn't clear, well a Full VC++2010 solution is here for your convenience to include char *'s:

https://github.com/alm4096/MD5-Hash-Example-VS

A bit of an explanation is here:

#include <iostream> //for std::cout
#include <string.h> //for std::string
#include <fstream>
#include "MD5.h"

using std::cout; using std::endl;

int main(int argc, char *argv[])
{
    //Start opening your file
    ifstream inBigArrayfile;
    inBigArrayfile.open ("Data.dat", std::ios::binary | std::ios::in);

    //Find length of file
    inBigArrayfile.seekg (0, std::ios::end);
    long Length = inBigArrayfile.tellg();
    inBigArrayfile.seekg (0, std::ios::beg);    

    //read in the data from your file
    char * InFileData = new char[Length];
    inBigArrayfile.read(InFileData,Length);

    //Calculate MD5 hash
    std::string Temp =  md5(InFileData,Length);
    cout << Temp.c_str() << endl;

    //Clean up
    delete [] InFileData;

    return 0;
}

I have simply added the following into the MD5 library:

MD5.cpp:

MD5::MD5(char * Input, long length)
{
  init();
  update(Input, length);
  finalize();
}

MD5.h:

std::string md5(char * Input, long length);

How can I easily add storage to a VirtualBox machine with XP installed?

For windows users:

cd “C:\Program Files\Oracle\VirtualBox”
VBoxManage modifyhd “C:\Users\Chris\VirtualBox VMs\Windows 7\Windows 7.vdi” --resize 81920

http://www.howtogeek.com/124622/how-to-enlarge-a-virtual-machines-disk-in-virtualbox-or-vmware/

Yahoo Finance All Currencies quote API Documentation


| ATTENTION !!! |

| SERVICE SUSPENDED BY YAHOO, solution no longer valid. |

Get from Yahoo a JSON or XML that you can parse from a REST query.

You can exchange from any to any currency and even get the date and time of the query using the YQL (Yahoo Query Language).

https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fd%2Fquotes.csv%3Fe%3D.csv%26f%3Dnl1d1t1%26s%3Dusdeur%3DX%22%3B&format=json&callback=

This will bring an example like below:

{
 "query": {
  "count": 1,
  "created": "2016-02-12T07:07:30Z",
  "lang": "en-US",
  "results": {
   "row": {
    "col0": "USD/EUR",
    "col1": "0.8835",
    "col2": "2/12/2016",
    "col3": "7:07am"
   }
  }
 }
}

You can try the console

I think this does not break any Term of Service as it is a 100% yahoo solution.

PostgreSQL: export resulting data from SQL query to Excel/CSV

Example with Unix-style file name:

COPY (SELECT * FROM tbl) TO '/var/lib/postgres/myfile1.csv' format csv;

Read the manual about COPY (link to version 8.2).
You have to use an absolute path for the target file. Be sure to double quote file names with spaces. Example for MS Windows:

COPY (SELECT * FROM tbl)
TO E'"C:\\Documents and Settings\\Tech\Desktop\\myfile1.csv"' format csv;

In PostgreSQL 8.2, with standard_conforming_strings = off per default, you need to double backslashes, because \ is a special character and interpreted by PostgreSQL. Works in any version. It's all in the fine manual:

filename

 The absolute path name of the input or output file. Windows users might need to use an E'' string and double backslashes used as path separators.

Or the modern syntax with standard_conforming_strings = on (default since Postgres 9.1):

COPY tbl  -- short for (SELECT * FROM tbl)
TO '"C:\Documents and Settings\Tech\Desktop\myfile1.csv"' (format csv);

Or you can also use forward slashes for filenames under Windows.

An alternative is to use the meta-command \copy of the default terminal client psql.

You can also use a GUI like pgadmin and copy / paste from the result grid to Excel for small queries.

Closely related answer:

Similar solution for MySQL:

jQuery on window resize

can use it too

        function getWindowSize()
            {
                var fontSize = parseInt($("body").css("fontSize"), 10);
                var h = ($(window).height() / fontSize).toFixed(4);
                var w = ($(window).width() / fontSize).toFixed(4);              
                var size = {
                      "height": h
                     ,"width": w
                };
                return size;
            }
        function startResizeObserver()
            {
                //---------------------
                var colFunc = {
                     "f10" : function(){ alert(10); }
                    ,"f50" : function(){ alert(50); }
                    ,"f100" : function(){ alert(100); }
                    ,"f500" : function(){ alert(500); }
                    ,"f1000" : function(){ alert(1000);}
                };
                //---------------------
                $(window).resize(function() {
                    var sz = getWindowSize();
                    if(sz.width > 10){colFunc['f10']();}
                    if(sz.width > 50){colFunc['f50']();}
                    if(sz.width > 100){colFunc['f100']();}
                    if(sz.width > 500){colFunc['f500']();}
                    if(sz.width > 1000){colFunc['f1000']();}
                });
            }
        $(document).ready(function() 
            {
                startResizeObserver();
            });

How to convert Javascript datetime to C# datetime?

If you want to send dates to C# from JS that is actually quite simple - if sending UTC dates is acceptable.

var date = new Date("Tue Jul 12 2011 16:00:00 GMT-0700");
var dateStrToSendToServer = date.toISOString();

... send to C# side ...

var success = DateTimeOffset.TryParse(jsISOStr, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var result);

C# DateTime already understands ISO date formats and will parse it just fine.

To format from C# to JS just use DateTime.UtcNow.ToString("o").

Personally, I'm never comfortable relying on math and logic between different environments to get the milliseconds/ticks to show the EXACT same date and time a user may see on the client (especially where it matters). I would do the same when transferring currency as well (use strings instead to be safe, or separate dollars and cents between two different integers). Sending the date/time as separate values would be just a good (see accepted answer).

How do I convert NSInteger to NSString datatype?

The answer is given but think that for some situation this will be also interesting way to get string from NSInteger

NSInteger value = 12;
NSString * string = [NSString stringWithFormat:@"%0.0f", (float)value];

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

if you are interested in a ready solution then you may look at HumanizerCpp library (https://github.com/trodevel/HumanizerCpp) - it is a port of C# Humanizer library and it does exactly what you want.

It can even convert to ordinals and currently supports 3 languages: English, German and Russian.

Example:

const INumberToWordsConverter * e = Configurator::GetNumberToWordsConverter( "en" );

std::cout << e->Convert( 123 ) << std::endl;
std::cout << e->Convert( 1234 ) << std::endl;
std::cout << e->Convert( 12345 ) << std::endl;
std::cout << e->Convert( 123456 ) << std::endl;

std::cout << std::endl;
std::cout << e->ConvertToOrdinal( 1001 ) << std::endl;
std::cout << e->ConvertToOrdinal( 1021 ) << std::endl;


const INumberToWordsConverter * g = Configurator::GetNumberToWordsConverter( "de" );

std::cout << std::endl;
std::cout << g->Convert( 123456 ) << std::endl;

const INumberToWordsConverter * r = Configurator::GetNumberToWordsConverter( "ru" );

std::cout << r->ConvertToOrdinal( 1112 ) << std::endl;

Output:

one hundred and twenty-three
one thousand two hundred and thirty-four
twelve thousand three hundred and forty-five
one hundred and twenty-three thousand four hundred and fifty-six

thousand and first
thousand and twenty-first

einhundertdreiundzwanzigtausendvierhundertsechsundfünfzig
???? ?????? ??? ???????????

In any case you may take a look at the source code and reuse in your project or try to understand the logic. It is written in pure C++ without external libraries.

Regards, Serge

Use CSS to remove the space between images

I prefer do like this

img { float: left; }

to remove the space between images

Bash checking if string does not contain other string

Bash allow u to use =~ to test if the substring is contained. Ergo, the use of negate will allow to test the opposite.

fullstring="123asdf123"
substringA=asdf
substringB=gdsaf
# test for contains asdf, gdsaf and for NOT CONTAINS gdsaf 
[[ $fullstring =~ $substring ]] && echo "found substring $substring in $fullstring"
[[ $fullstring =~ $substringB ]] && echo "found substring $substringB in $fullstring" || echo "failed to find"
[[ ! $fullstring =~ $substringB ]] && echo "did not find substring $substringB in $fullstring"

Laravel Eloquent - distinct() and count() not working properly together

I came across the same problem.

If you install laravel debug bar you can see the queries and often see the problem

$ad->getcodes()->groupby('pid')->distinct()->count()

change to

$ad->getcodes()->distinct()->select('pid')->count()

You need to set the values to return as distinct. If you don't set the select fields it will return all the columns in the database and all will be unique. So set the query to distinct and only select the columns that make up your 'distinct' value you might want to add more. ->select('pid','date') to get all the unique values for a user in a day

JavaScript before leaving the page

This what I did to show the confirmation message just when I have unsaved data

window.onbeforeunload = function () {
            if (isDirty) {
                return "There are unsaved data.";
            }
            return undefined;
        }

returning "undefined" will disable the confirmation

Note: returning "null" will not work with IE

Also you can use "undefined" to disable the confirmation

window.onbeforeunload = undefined;

How can I hide/show a div when a button is clicked?

You can do this entirely with html and css and i have.


HTML First you give the div you wish to hide an ID to target like #view_element and a class to target like #hide_element. You can if you wish make both of these classes but i don't know if you can make them both IDs. Then have your Show button target your show id and your Hide button target your hide class. That is it for the html the hiding and showing is done in the CSS.

CSS The css to show and hide this should look something like this

#hide_element:target {
    display:none;
}

.show_element:target{
    display:block;
}

This should allow you to hide and show elements at will. This should work nicely on spans and divs.

How to check if any fields in a form are empty in php

your form is missing the method...

<form name="registrationform" action="register.php" method="post"> //here

anywyas to check the posted data u can use isset()..

Determine if a variable is set and is not NULL

if(!isset($firstname) || trim($firstname) == '')
{
   echo "You did not fill out the required fields.";
}

How to set background color of an Activity to white programmatically?

final View rootView = findViewById(android.R.id.content);
rootView.setBackgroundResource(...);

How do you set the title color for the new Toolbar?

If you can use appcompat-v7 app:titleTextColor="#fff">

<android.support.v7.widget.Toolbar  
        android:id="@+id/toolbar"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:background="@color/colorPrimary"   
        android:visibility="gone"   
        app:titleTextColor="#fff">   
    </android.support.v7.widget.Toolbar>   

How do I view the SQLite database on an Android device?

UPDATE 2020

Database Inspector (for Android Studio version 4.1). Read the Medium article

For older versions of Android Studio I recommend these 3 options:

  1. Facebook's open source [Stetho library] (http://facebook.github.io/stetho/). Taken from here

In build.gradle:

dependencies {
  // Stetho core
  compile 'com.facebook.stetho:stetho:1.5.1'        
  //If you want to add a network helper
  compile 'com.facebook.stetho:stetho-okhttp:1.5.1'
}

Initialize the library in the application object:

Stetho.initializeWithDefaults(this);

And you can view you database in Chrome from chrome://inspect

  1. Another option is this plugin (not free)
  2. And the last one is this free/open source library to see db contents in the browser https://github.com/amitshekhariitbhu/Android-Debug-Database

Check if a string contains a string in C++

From so many answers in this website I didn't find out a clear answer so in 5-10 minutes I figured it out the answer myself. But this can be done in two cases:

  1. Either you KNOW the position of the sub-string you search for in the string
  2. Either you don't know the position and search for it, char by char...

So, let's assume we search for the substring "cd" in the string "abcde", and we use the simplest substr built-in function in C++

for 1:

#include <iostream>
#include <string>

    using namespace std;
int i;

int main()
{
    string a = "abcde";
    string b = a.substr(2,2);    // 2 will be c. Why? because we start counting from 0 in a string, not from 1.

    cout << "substring of a is: " << b << endl;
    return 0;
}

for 2:

#include <iostream>
#include <string>

using namespace std;
int i;

int main()
{
    string a = "abcde";

    for (i=0;i<a.length(); i++)
    {
        if (a.substr(i,2) == "cd")
        {
        cout << "substring of a is: " << a.substr(i,2) << endl;    // i will iterate from 0 to 5 and will display the substring only when the condition is fullfilled 
        }
    }
    return 0;
}

URL encoding the space character: + or %20?

This confusion is because URLs are still 'broken' to this day.

Take "http://www.google.com" for instance. This is a URL. A URL is a Uniform Resource Locator and is really a pointer to a web page (in most cases). URLs actually have a very well-defined structure since the first specification in 1994.

We can extract detailed information about the "http://www.google.com" URL:

+---------------+-------------------+
|      Part     |      Data         |
+---------------+-------------------+
|  Scheme       | http              |
|  Host         | www.google.com    |
+---------------+-------------------+

If we look at a more complex URL such as:

"https://bob:[email protected]:8080/file;p=1?q=2#third"

we can extract the following information:

+-------------------+---------------------+
|        Part       |       Data          |
+-------------------+---------------------+
|  Scheme           | https               |
|  User             | bob                 |
|  Password         | bobby               |
|  Host             | www.lunatech.com    |
|  Port             | 8080                |
|  Path             | /file;p=1           |
|  Path parameter   | p=1                 |
|  Query            | q=2                 |
|  Fragment         | third               |
+-------------------+---------------------+

https://bob:[email protected]:8080/file;p=1?q=2#third
\___/   \_/ \___/ \______________/ \__/\_______/ \_/ \___/
  |      |    |          |          |      | \_/  |    |
Scheme User Password    Host       Port  Path |   | Fragment
        \_____________________________/       | Query
                       |               Path parameter
                   Authority

The reserved characters are different for each part.

For HTTP URLs, a space in a path fragment part has to be encoded to "%20" (not, absolutely not "+"), while the "+" character in the path fragment part can be left unencoded.

Now in the query part, spaces may be encoded to either "+" (for backwards compatibility: do not try to search for it in the URI standard) or "%20" while the "+" character (as a result of this ambiguity) has to be escaped to "%2B".

This means that the "blue+light blue" string has to be encoded differently in the path and query parts:

"http://example.com/blue+light%20blue?blue%2Blight+blue".

From there you can deduce that encoding a fully constructed URL is impossible without a syntactical awareness of the URL structure.

This boils down to:

You should have %20 before the ? and + after.

Source

What does the shrink-to-fit viewport meta attribute do?

As stats on iOS usage, indicating that iOS 9.0-9.2.x usage is currently at 0.17%. If these numbers are truly indicative of global use of these versions, then it’s even more likely to be safe to remove shrink-to-fit from your viewport meta tag.

After 9.2.x. IOS remove this tag check on its' browser.

You can check this page https://www.scottohara.me/blog/2018/12/11/shrink-to-fit.html

How to make an input type=button act like a hyperlink and redirect using a get request?

You can make <button> tag to do action like this:

<a href="http://www.google.com/">
   <button>Visit Google</button>
</a>

or:

<a href="http://www.google.com/">
   <input type="button" value="Visit Google" />
</a>

It's simple and no javascript required!


NOTE:

This approach is not valid from HTML structure. But, it works on many modern browser. See following reference :

Get and set position with jQuery .offset()

It's doable but you have to know that using offset() sets the position of the element relative to the document:

$('.layer1').offset( $('.layer2').offset() );

Disable F5 and browser refresh using JavaScript

for mac cmd+r, cmd+shift+r to need.

function disableF5(e) { if ((e.which || e.keyCode) == 116 || (e.which || e.keyCode) == 82) e.preventDefault(); };

$(document).ready(function(){
$(document).on("keydown", disableF5);
});

Spring Rest POST Json RequestBody Content type not supported

I met the same problem which i solved by deserializing myself the posted value :

@RequestMapping(value = "/arduinos/commands/{idArduino}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String sendCommandesJson(@PathVariable("idArduino") String idArduino, HttpServletRequest request) throws IOException {
    // getting the posted value
    String body = CharStreams.toString(request.getReader());
    List<ArduinoCommand> commandes = new ObjectMapper().readValue(body, new TypeReference<List<ArduinoCommand>>() {
    });

with theses gradle dependencies :

  compile('org.springframework.boot:spring-boot-starter-web')
  compile('com.google.guava:guava:16.0.1')

Selection with .loc in python

It's pandas label-based selection, as explained here: https://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-label

The boolean array is basically a selection method using a mask.

Convert the values in a column into row names in an existing data frame

You can execute this in 2 simple statements:

row.names(samp) <- samp$names
samp[1] <- NULL

Is there an exponent operator in C#?

For what it's worth I do miss the ^ operator when raising a power of 2 to define a binary constant. Can't use Math.Pow() there, but shifting an unsigned int of 1 to the left by the exponent's value works. When I needed to define a constant of (2^24)-1:

public static int Phase_count = 24;
public static uint PatternDecimal_Max = ((uint)1 << Phase_count) - 1;

Remember the types must be (uint) << (int).

MySql: is it possible to 'SUM IF' or to 'COUNT IF'?

You can use a CASE statement:

SELECT count(id), 
    SUM(hour) as totHour, 
    SUM(case when kind = 1 then 1 else 0 end) as countKindOne

Best way to compare 2 XML documents in Java

This will compare full string XMLs (reformatting them on the way). It makes it easy to work with your IDE (IntelliJ, Eclipse), cos you just click and visually see the difference in the XML files.

import org.apache.xml.security.c14n.CanonicalizationException;
import org.apache.xml.security.c14n.Canonicalizer;
import org.apache.xml.security.c14n.InvalidCanonicalizerException;
import org.w3c.dom.Element;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.io.StringReader;

import static org.apache.xml.security.Init.init;
import static org.junit.Assert.assertEquals;

public class XmlUtils {
    static {
        init();
    }

    public static String toCanonicalXml(String xml) throws InvalidCanonicalizerException, ParserConfigurationException, SAXException, CanonicalizationException, IOException {
        Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
        byte canonXmlBytes[] = canon.canonicalize(xml.getBytes());
        return new String(canonXmlBytes);
    }

    public static String prettyFormat(String input) throws TransformerException, ParserConfigurationException, IOException, SAXException, InstantiationException, IllegalAccessException, ClassNotFoundException {
        InputSource src = new InputSource(new StringReader(input));
        Element document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
        Boolean keepDeclaration = input.startsWith("<?xml");
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
        writer.getDomConfig().setParameter("xml-declaration", keepDeclaration);
        return writer.writeToString(document);
    }

    public static void assertXMLEqual(String expected, String actual) throws ParserConfigurationException, IOException, SAXException, CanonicalizationException, InvalidCanonicalizerException, TransformerException, IllegalAccessException, ClassNotFoundException, InstantiationException {
        String canonicalExpected = prettyFormat(toCanonicalXml(expected));
        String canonicalActual = prettyFormat(toCanonicalXml(actual));
        assertEquals(canonicalExpected, canonicalActual);
    }
}

I prefer this to XmlUnit because the client code (test code) is cleaner.

Install Chrome extension form outside the Chrome Web Store

For Windows, you can also whitelist your extension through Windows policies. The full steps are details in this answer, but there are quicker steps:

  1. Create the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist.
  2. For each extension you want to whitelist, add a string value whose name should be a sequence number (starting at 1) and value is the extension ID.

For instance, in order to whitelist 2 extensions with ID aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, create a string value with name 1 and value aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, and a second value with name 2 and value bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb. This can be sum up by this registry file:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome]

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist]
"1"="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"2"="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"

EDIT: actually, Chromium docs also indicate how to do it for other OS.

Lollipop : draw behind statusBar with its color set to transparent

There is good library StatusBarUtil from @laobie that help to easily draw image in the StatusBar.

Just add in your build.gradle:

compile 'com.jaeger.statusbarutil:library:1.4.0'

Then in the Activity set

StatusBarUtil.setTranslucentForImageView(Activity activity, int statusBarAlpha, View viewNeedOffset)

In the layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:orientation="vertical">

    <ImageView
        android:layout_alignParentTop="true"
        android:layout_width="match_parent"
        android:adjustViewBounds="true"
        android:layout_height="wrap_content"
        android:src="@drawable/toolbar_bg"/>

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/view_need_offset"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@android:color/transparent"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

        <!-- Your layout code -->
    </android.support.design.widget.CoordinatorLayout>
</RelativeLayout>

For more info download demo or clone from github page and play with all feature.

Note: Support KitKat and above.

Hope that helps somebody else!

How to find EOF through fscanf?

If you have integers in your file fscanf returns 1 until integer occurs. For example:

FILE *in = fopen("./task.in", "r");
int length = 0;
int counter;
int sequence;

for ( int i = 0; i < 10; i++ ) {
    counter = fscanf(in, "%d", &sequence);
    if ( counter == 1 ) {
        length += 1;
    }
}

To find out the end of the file with symbols you can use EOF. For example:

char symbol;
FILE *in = fopen("./task.in", "r");

for ( ; fscanf(in, "%c", &symbol) != EOF; ) {
    printf("%c", symbol); 
}

Inserting records into a MySQL table using Java

no that cannot work(not with real data):

String sql = "INSERT INTO course " +
        "VALUES (course_code, course_desc, course_chair)";
    stmt.executeUpdate(sql);

change it to:

String sql = "INSERT INTO course (course_code, course_desc, course_chair)" +
        "VALUES (?, ?, ?)";

Create a PreparedStatment with that sql and insert the values with index:

PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "Test2");
preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate(); 

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

Try to move:

apply plugin: 'com.google.gms.google-services'

just below:

apply plugin: 'com.android.application'

In your module Gradle file, then make sure all Google service's have the version 9.0.0.

Make sure that only this build tools is used:

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

Make sure in gradle-wrapper.properties:

distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip

After all above is correct, then make menu File -> Invalidate caches and restart.

how to detect search engine bots with php?

I'm using this to detect bots:

if (preg_match('/bot|crawl|curl|dataprovider|search|get|spider|find|java|majesticsEO|google|yahoo|teoma|contaxe|yandex|libwww-perl|facebookexternalhit/i', $_SERVER['HTTP_USER_AGENT'])) {
    // is bot
}

In addition I use a whitelist to block unwanted bots:

if (preg_match('/apple|baidu|bingbot|facebookexternalhit|googlebot|-google|ia_archiver|msnbot|naverbot|pingdom|seznambot|slurp|teoma|twitter|yandex|yeti/i', $_SERVER['HTTP_USER_AGENT'])) {
    // allowed bot
}

An unwanted bot (= false-positive user) is then able to solve a captcha to unblock himself for 24 hours. And as no one solves this captcha, I know it does not produce false-positives. So the bot detection seem to work perfectly.

Note: My whitelist is based on Facebooks robots.txt.

How does one create an InputStream from a String?

Here you go:

InputStream is = new ByteArrayInputStream( myString.getBytes() );

Update For multi-byte support use (thanks to Aaron Waibel's comment):

InputStream is = new ByteArrayInputStream(Charset.forName("UTF-16").encode(myString).array());

Please see ByteArrayInputStream manual.

It is safe to use a charset argument in String#getBytes(charset) method above.

After JDK 7+ you can use

java.nio.charset.StandardCharsets.UTF_16

instead of hardcoded encoding string:

InputStream is = new ByteArrayInputStream(StandardCharsets.UTF_16.encode(myString).array());

How to change a field name in JSON using Jackson

Be aware that there is org.codehaus.jackson.annotate.JsonProperty in Jackson 1.x and com.fasterxml.jackson.annotation.JsonProperty in Jackson 2.x. Check which ObjectMapper you are using (from which version), and make sure you use the proper annotation.

text flowing out of div

If it is just one instance that needs to be wrapped over 2 or 3 lines I would just use a few <wbr> in the string. It will treat those just like <br> but it wont insert the line break if it isn't necessary.

<div id="w74" class="dpinfo">
adsfadsadsads<wbr>fadsadsadsfadsadsa<wbr>dsfadsadsadsfadsadsads<wbr>fadsadsadsfadsadsadsfa<wbr>dsadsadsfadsadsadsfadsad<wbr>sadsfadsadsads<wbr>fadsadsadsfadsads adsfadsads
</div>

Here is a fiddle.

http://jsfiddle.net/gaby_de_wilde/UJ6zG/37/

retrieve data from db and display it in table in php .. see this code whats wrong with it?

Here is the solution total html with php and database connections

   <!doctype html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>database connections</title>
    </head>
    <body>
      <?php
      $username = "database-username";
      $password = "database-password";
      $host = "localhost";

      $connector = mysql_connect($host,$username,$password)
          or die("Unable to connect");
        echo "Connections are made successfully::";
      $selected = mysql_select_db("test_db", $connector)
        or die("Unable to connect");

      //execute the SQL query and return records
      $result = mysql_query("SELECT * FROM table_one ");
      ?>
      <table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;" >
      <thead>
        <tr>
          <th>Employee_id</th>
          <th>Employee_Name</th>
          <th>Employee_dob</th>
          <th>Employee_Adress</th>
          <th>Employee_dept</th>
          <td>Employee_salary</td>
        </tr>
      </thead>
      <tbody>
        <?php
          while( $row = mysql_fetch_assoc( $result ) ){
            echo
            "<tr>
              <td>{$row\['employee_id'\]}</td>
              <td>{$row\['employee_name'\]}</td>
              <td>{$row\['employee_dob'\]}</td>
              <td>{$row\['employee_addr'\]}</td>
              <td>{$row\['employee_dept'\]}</td>
              <td>{$row\['employee_sal'\]}</td> 
            </tr>\n";
          }
        ?>
      </tbody>
    </table>
     <?php mysql_close($connector); ?>
    </body>
    </html>

What is the difference between ArrayList.clear() and ArrayList.removeAll()?

They serve different purposes. clear() clears an instance of the class, removeAll() removes all the given objects and returns the state of the operation.

What is the difference between json.dumps and json.load?

dumps takes an object and produces a string:

>>> a = {'foo': 3}
>>> json.dumps(a)
'{"foo": 3}'

load would take a file-like object, read the data from that object, and use that string to create an object:

with open('file.json') as fh:
    a = json.load(fh)

Note that dump and load convert between files and objects, while dumps and loads convert between strings and objects. You can think of the s-less functions as wrappers around the s functions:

def dump(obj, fh):
    fh.write(dumps(obj))

def load(fh):
    return loads(fh.read())

Disabling swap files creation in vim

If you put set directory="" in your exrc file, you will turn off the swap file. However, doing so will disable recovery.

More info here.

Read binary file as string in Ruby

If you need binary mode, you'll need to do it the hard way:

s = File.open(filename, 'rb') { |f| f.read }

If not, shorter and sweeter is:

s = IO.read(filename)

How can I serve static html from spring boot?

You can quickly serve static content in JAVA Spring-boot App via thymeleaf (ref: source)

I assume you have already added Spring Boot plugin apply plugin: 'org.springframework.boot' and the necessary buildscript

Then go ahead and ADD thymeleaf to your build.gradle ==>

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    compile("org.springframework.boot:spring-boot-starter-thymeleaf")
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

Lets assume you have added home.html at src/main/resources To serve this file, you will need to create a controller.

package com.ajinkya.th.controller;

  import org.springframework.stereotype.Controller;
  import org.springframework.web.bind.annotation.RequestMapping;

  @Controller
  public class HomePageController {

      @RequestMapping("/")
      public String homePage() {
        return "home";
      }

  }

Thats it ! Now restart your gradle server. ./gradlew bootRun

How do I set/unset a cookie with jQuery?

A simple example of set cookie in your browser:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>jquery.cookie Test Suite</title>

        <script src="jquery-1.9.0.min.js"></script>
        <script src="jquery.cookie.js"></script>
        <script src="JSON-js-master/json.js"></script>
        <script src="JSON-js-master/json_parse.js"></script>
        <script>
            $(function() {

               if ($.cookie('cookieStore')) {
                    var data=JSON.parse($.cookie("cookieStore"));
                    $('#name').text(data[0]);
                    $('#address').text(data[1]);
              }

              $('#submit').on('click', function(){

                    var storeData = new Array();
                    storeData[0] = $('#inputName').val();
                    storeData[1] = $('#inputAddress').val();

                    $.cookie("cookieStore", JSON.stringify(storeData));
                    var data=JSON.parse($.cookie("cookieStore"));
                    $('#name').text(data[0]);
                    $('#address').text(data[1]);
              });
            });

       </script>
    </head>
    <body>
            <label for="inputName">Name</label>
            <br /> 
            <input type="text" id="inputName">
            <br />      
            <br /> 
            <label for="inputAddress">Address</label>
            <br /> 
            <input type="text" id="inputAddress">
            <br />      
            <br />   
            <input type="submit" id="submit" value="Submit" />
            <hr>    
            <p id="name"></p>
            <br />      
            <p id="address"></p>
            <br />
            <hr>  
     </body>
</html>

Simple just copy/paste and use this code for set your cookie.

How to update Git clone

If you want to fetch + merge, run

git pull

if you want simply to fetch :

git fetch

rsync: difference between --size-only and --ignore-times

On a Scientific Linux 6.7 system, the man page on rsync says:

--ignore-times          don't skip files that match size and time

I have two files with identical contents, but with different creation dates:

[root@windstorm ~]# ls -ls /tmp/master/usercron /tmp/new/usercron
4 -rwxrwx--- 1 root root 1595 Feb 15 03:45 /tmp/master/usercron
4 -rwxrwx--- 1 root root 1595 Feb 16 04:52 /tmp/new/usercron

[root@windstorm ~]# diff /tmp/master/usercron /tmp/new/usercron
[root@windstorm ~]# md5sum /tmp/master/usercron /tmp/new/usercron
368165347b09204ce25e2fa0f61f3bbd  /tmp/master/usercron
368165347b09204ce25e2fa0f61f3bbd  /tmp/new/usercron

With --size-only, the two files are regarded the same:

[root@windstorm ~]# rsync -v --size-only -n  /tmp/new/usercron /tmp/master/usercron

sent 29 bytes  received 12 bytes  82.00 bytes/sec
total size is 1595  speedup is 38.90 (DRY RUN)

With --ignore-times, the two files are regarded different:

[root@windstorm ~]# rsync -v --ignore-times -n  /tmp/new/usercron /tmp/master/usercron
usercron

sent 32 bytes  received 15 bytes  94.00 bytes/sec
total size is 1595  speedup is 33.94 (DRY RUN)

So it does not looks like --ignore-times has any effect at all.

How to Copy Contents of One Canvas to Another Canvas Locally

@robert-hurst has a cleaner approach.

However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.

    // select canvas elements
    var sourceCanvas = document.getElementById("some-unique-id");
    var destCanvas = document.getElementsByClassName("some-class-selector")[0];

    //copy canvas by DataUrl
    var sourceImageData = sourceCanvas.toDataURL("image/png");
    var destCanvasContext = destCanvas.getContext('2d');

    var destinationImage = new Image;
    destinationImage.onload = function(){
      destCanvasContext.drawImage(destinationImage,0,0);
    };
    destinationImage.src = sourceImageData;

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

You can use "export default" by calling an Arrow Function that returns its React.Component by passing it through the MaterialUI class object props, which in turn will be used within the Component render ().

class AllowanceClass extends Component{
    ...
    render() {
        const classes = this.props.classes;
        ...
    }
}

export default () => {
    const classes = useStyles();
    return (
        <AllowanceClass classes={classes} />
    )
}

Draw Circle using css alone

This will work in all browsers

#circle {
    background: #f00;
    width: 200px;
    height: 200px;
    border-radius: 50%;
    -moz-border-radius: 50%;
    -webkit-border-radius: 50%;
}

java.net.SocketException: Connection reset

Connection reset simply means that a TCP RST was received. This happens when your peer receives data that it can't process, and there can be various reasons for that.

The simplest is when you close the socket, and then write more data on the output stream. By closing the socket, you told your peer that you are done talking, and it can forget about your connection. When you send more data on that stream anyway, the peer rejects it with an RST to let you know it isn't listening.

In other cases, an intervening firewall or even the remote host itself might "forget" about your TCP connection. This could happen if you don't send any data for a long time (2 hours is a common time-out), or because the peer was rebooted and lost its information about active connections. Sending data on one of these defunct connections will cause a RST too.


Update in response to additional information:

Take a close look at your handling of the SocketTimeoutException. This exception is raised if the configured timeout is exceeded while blocked on a socket operation. The state of the socket itself is not changed when this exception is thrown, but if your exception handler closes the socket, and then tries to write to it, you'll be in a connection reset condition. setSoTimeout() is meant to give you a clean way to break out of a read() operation that might otherwise block forever, without doing dirty things like closing the socket from another thread.

Change value of input placeholder via model?

Since AngularJS does not have directive DOM manipulations as jQuery does, a proper way to modify attributes of one element will be using directive. Through link function of a directive, you have access to both element and its attributes.

Wrapping you whole input inside one directive, you can still introduce ng-model's methods through controller property.

This method will help to decouple the logic of ngmodel with placeholder from controller. If there is no logic between them, you can definitely go as Wagner Francisco said.

Change div height on button click

You have to set height as a string value when you use pixels.

document.getElementById('chartdiv').style.height = "200px"

Also try adding a DOCTYPE to your HTML for Internet Explorer.

<!DOCTYPE html>
<html> ...

docker entrypoint running bash script gets "permission denied"

An executable file needs to have permissions for execute set before you can execute it.

In your machine where you are building the docker image (not inside the docker image itself) try running:

ls -la path/to/directory

The first column of the output for your executable (in this case docker-entrypoint.sh) should have the executable bits set something like:

-rwxrwxr-x

If not then try:

chmod +x docker-entrypoint.sh

and then build your docker image again.

Docker uses it's own file system but it copies everything over (including permissions bits) from the source directories.

.htaccess file to allow access to images folder to view pictures?

Create a .htaccess file in the images folder and add this

<IfModule mod_rewrite.c>
RewriteEngine On
# directory browsing
Options All +Indexes
</IfModule>

you can put this Options All -Indexes in the project file .htaccess ,file to deny direct access to other folders.

This does what you want

How can I reset or revert a file to a specific revision?

In the case that you want to revert a file to a previous commit (and the file you want to revert already committed) you can use

git checkout HEAD^1 path/to/file

or

git checkout HEAD~1 path/to/file

Then just stage and commit the "new" version.

Armed with the knowledge that a commit can have two parents in the case of a merge, you should know that HEAD^1 is the first parent and HEAD~1 is the second parent.

Either will work if there is only one parent in the tree.

Compare if BigDecimal is greater than zero

It's as simple as:

if (value.compareTo(BigDecimal.ZERO) > 0)

The documentation for compareTo actually specifies that it will return -1, 0 or 1, but the more general Comparable<T>.compareTo method only guarantees less than zero, zero, or greater than zero for the appropriate three cases - so I typically just stick to that comparison.

Reorder HTML table rows using drag-and-drop

thanks to Jim Petkus that did gave me a wonderful answer . but i was trying to solve my own script not to changing it to another plugin . My main focus was not using an independent plugin and do what i wanted just by using the jquery core !

and guess what i did find the problem .

var title = $("em").attr("title");
$("div").text(title);

this is what i add to my script and the blew codes to my html part :

<td> <em title=\"$weight\">$weight</em></td>

and found each row $weight value

thanks again to Jim Petkus

Getting CheckBoxList Item values

Try to use this :

 private void button1_Click(object sender, EventArgs e)
    {

        for (int i = 0; i < chBoxListTables.Items.Count; i++)
            if (chBoxListTables.GetItemCheckState(i) == CheckState.Checked)
            {
               txtBx.text += chBoxListTables.Items[i].ToString() + " \n"; 

            }
    }

How to convert integers to characters in C?

Casting the integer to a char will do what you want.

char theChar=' ';
int theInt = 97;
theChar=(char) theInt;

cout<<theChar<<endl;

There is no difference between 'a' and 97 besides the way you interperet them.

Allow anonymous authentication for a single folder in web.config?

<location path="ForAll/Demo.aspx">
 <system.web>
  <authorization>
    <allow users="*" />
  </authorization>
 </system.web>
</location>

In Addition: If you want to write something on that folder through website , you have to give IIS_User permission to the folder

How to read data of an Excel file using C#?

Use OLEDB Connection to communicate with excel files. it gives better result

using System.Data.OleDb;



                string physicalPath = "Your Excel file physical path";
                OleDbCommand cmd = new OleDbCommand();
                OleDbDataAdapter da = new OleDbDataAdapter();
                DataSet ds = new DataSet();
                String strNewPath = physicalPath;
                String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                String query = "SELECT * FROM [Sheet1$]"; // You can use any different queries to get the data from the excel sheet
                OleDbConnection conn = new OleDbConnection(connString);
                if (conn.State == ConnectionState.Closed) conn.Open();
                try
                {
                    cmd = new OleDbCommand(query, conn);
                    da = new OleDbDataAdapter(cmd);
                    da.Fill(ds);

                }
                catch
                {
                    // Exception Msg 

                }
                finally
                {
                    da.Dispose();
                    conn.Close();
                }

The Output data will be stored in dataset, using the dataset object you can easily access the datas. Hope this may helpful

Show / hide div on click with CSS

You could do this with the CSS3 :target selector.

menu:hover block {
    visibility: visible;
}

block:target {
    visibility:hidden;
}

How do I compile with -Xlint:unchecked?

If you work with an IDE like NetBeans, you can specify the Xlint:unchecked compiler option in the propertys of your project.

Just go to projects window, right click in the project and then click in Properties.

In the window that appears search the Compiling category, and in the textbox labeled Additional Compiler Options set the Xlint:unchecked option.

Thus, the setting will remain set for every time you compile the project.

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

The documentation for Gerrit, in particular the "Push changes" section, explains that you push to the "magical refs/for/'branch' ref using any Git client tool".

The following image is taken from the Intro to Gerrit. When you push to Gerrit, you do git push gerrit HEAD:refs/for/<BRANCH>. This pushes your changes to the staging area (in the diagram, "Pending Changes"). Gerrit doesn't actually have a branch called <BRANCH>; it lies to the git client.

Internally, Gerrit has its own implementation for the Git and SSH stacks. This allows it to provide the "magical" refs/for/<BRANCH> refs.

When a push request is received to create a ref in one of these namespaces Gerrit performs its own logic to update the database, and then lies to the client about the result of the operation. A successful result causes the client to believe that Gerrit has created the ref, but in reality Gerrit hasn’t created the ref at all. [Link - Gerrit, "Gritty Details"].

The Gerrit workflow

After a successful patch (i.e, the patch has been pushed to Gerrit, [putting it into the "Pending Changes" staging area], reviewed, and the review has passed), Gerrit pushes the change from the "Pending Changes" into the "Authoritative Repository", calculating which branch to push it into based on the magic it did when you pushed to refs/for/<BRANCH>. This way, successfully reviewed patches can be pulled directly from the correct branches of the Authoritative Repository.

Importing modules from parent folder

I found the following way works for importing a package from the script's parent directory. In the example, I would like to import functions in env.py from app.db package.

.
+-- my_application
    +-- alembic
        +-- env.py
    +-- app
        +-- __init__.py
        +-- db
import os
import sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)

Enable vertical scrolling on textarea

Maybe a fixed height and overflow-y: scroll;

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

A pitfall some might step into that is covered by this question but isn't addressed in the answers as it is slightly different in the code structure but returns the exact same error.

This error occurs when using bindActionCreators and not passing the dispatch function

Error Code

import someComponent from './someComponent'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import { someAction } from '../../../actions/someAction'

const mapStatToProps = (state) => {
    const { someState } = state.someState

    return {
        someState
    }
};

const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({
        someAction
    });
};

export default connect(mapStatToProps, mapDispatchToProps)(someComponent)

Fixed Code

import someComponent from './someComponent'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import { someAction } from '../../../actions/someAction'

const mapStatToProps = (state) => {
    const { someState } = state.someState

    return {
        someState
    }
};

const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({
        someAction
    }, dispatch);
};

export default connect(mapStatToProps, mapDispatchToProps)(someComponent)

The function dispatch was missing in the Error code

How to git commit a single file/directory

Your arguments are in the wrong order. Try git commit -m 'my notes' path/to/my/file.ext, or if you want to be more explicit, git commit -m 'my notes' -- path/to/my/file.ext.

Incidentally, git v1.5.2.1 is 4.5 years old. You may want to update to a newer version (1.7.8.3 is the current release).

Which port(s) does XMPP use?

The ports required will be different for your XMPP Server and any XMPP Clients. Most "modern" XMPP Servers follow the defined IANA Ports for Server-to-Server 5269 and for Client-to-Server 5222. Any additional ports depends on what features you enable on the Server, i.e. if you offer BOSH then you may need to open port 80.

File Transfer is highly dependent on both the Clients you use and the Server as to what port it will use, but most of them also negotiate the connect via your existing XMPP Client-to-Server link so the required port opening will be client side (or proxied via port 80.)

How to split a delimited string into an array in awk?

echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'

should work.

Simplest way to display current month and year like "Aug 2016" in PHP?

Full version:

<? echo date('F Y'); ?>

Short version:

<? echo date('M Y'); ?>

Here is a good reference for the different date options.

update

To show the previous month we would have to introduce the mktime() function and make use of the optional timestamp parameter for the date() function. Like this:

echo date('F Y', mktime(0, 0, 0, date('m')-1, 1, date('Y')));

This will also work (it's typically used to get the last day of the previous month):

echo date('F Y', mktime(0, 0, 0, date('m'), 0, date('Y')));

Hope that helps.

Create a function with optional call variables

Not sure I understand the question correctly.

From what I gather, you want to be able to assign a value to Domain if it is null and also what to check if $args2 is supplied and according to the value, execute a certain code?

I changed the code to reassemble the assumptions made above.

Function DoStuff($computername, $arg2, $domain)
{
    if($domain -ne $null)
    {
        $domain = "Domain1"
    }

    if($arg2 -eq $null)
    {
    }
    else
    {
    }
}

DoStuff -computername "Test" -arg2 "" -domain "Domain2"
DoStuff -computername "Test" -arg2 "Test"  -domain ""
DoStuff -computername "Test" -domain "Domain2"
DoStuff -computername "Test" -arg2 "Domain2"

Did that help?

Javascript Cookie with no expiration date

All cookies expire as per the cookie specification, Maximum value you can set is

 2^31 - 1 = 2147483647 = 2038-01-19 04:14:07

So Maximum cookie life time is

$.cookie('subscripted_24', true, { expires: 2147483647 });

symfony 2 twig limit the length of the text and put three dots

I know this is a very old question, but from twig 1.6 you can use the slice filter;

{{ myentity.text|slice(0, 50) ~ '...' }}

The second part from the tilde is optional for if you want to add something for example the ellipsis.

Edit: My bad, I see the most up-voted answer do make use of the slice filter.

Append a Lists Contents to another List C#

if you want to get "terse" :)

List<string>GlobalStrings = new List<string>(); 

for(int x=1; x<10; x++) GlobalStrings.AddRange(new List<string> { "some value", "another value"});

getResourceAsStream returns null

What worked for me was to add the file under My Project/Java Resources/src and then use

this.getClass().getClassLoader().getResourceAsStream("myfile.txt");

I didn't need to explicitly add this file to the path (adding it to /src does that apparently)

Convert JSON string to array of JSON objects in Javascript

If your using jQuery, it's parseJSON function can be used and is preferable to JavaScript's native eval() function.

Elasticsearch : Root mapping definition has unsupported parameters index : not_analyzed

Check your Elastic version.

I had these problem because I was looking at the incorrect version's documentation.

enter image description here

Make a negative number positive

If you're interested in the mechanics of two's complement, here's the absolutely inefficient, but illustrative low-level way this is made:

private static int makeAbsolute(int number){
     if(number >=0){
        return number;
     } else{
        return (~number)+1;
     }
}

How to sort a list of objects based on an attribute of the objects?

from operator import attrgetter
ut.sort(key = attrgetter('count'), reverse = True)

How to specify legend position in matplotlib in graph coordinates

In addition to @ImportanceOfBeingErnest's post, I use the following line to add a legend at an absolute position in a plot.

plt.legend(bbox_to_anchor=(1.0,1.0),\
    bbox_transform=plt.gcf().transFigure)

For unknown reasons, bbox_transform=fig.transFigure does not work with me.

What is the significance of url-pattern in web.xml and how to configure servlet?

url-pattern is used in web.xml to map your servlet to specific URL. Please see below xml code, similar code you may find in your web.xml configuration file.

<servlet>
    <servlet-name>AddPhotoServlet</servlet-name>  //servlet name
    <servlet-class>upload.AddPhotoServlet</servlet-class>  //servlet class
</servlet>
 <servlet-mapping>
    <servlet-name>AddPhotoServlet</servlet-name>   //servlet name
    <url-pattern>/AddPhotoServlet</url-pattern>  //how it should appear
</servlet-mapping>

If you change url-pattern of AddPhotoServlet from /AddPhotoServlet to /MyUrl. Then, AddPhotoServlet servlet can be accessible by using /MyUrl. Good for the security reason, where you want to hide your actual page URL.

Java Servlet url-pattern Specification:

  1. A string beginning with a '/' character and ending with a '/*' suffix is used for path mapping.
  2. A string beginning with a '*.' prefix is used as an extension mapping.
  3. A string containing only the '/' character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
  4. All other strings are used for exact matches only.

Reference : Java Servlet Specification

You may also read this Basics of Java Servlet

First Heroku deploy failed `error code=H10`

in my case adding process.env.PORT || 3000 to my http server script, resolved. My heroku log reported 'H20' error and 503 http status.

Notification Icon with the new Firebase Cloud Messaging system

There is also one ugly but working way. Decompile FirebaseMessagingService.class and modify it's behavior. Then just put the class to the right package in yout app and dex use it instead of the class in the messaging lib itself. It is quite easy and working.

There is method:

private void zzo(Intent intent) {
    Bundle bundle = intent.getExtras();
    bundle.remove("android.support.content.wakelockid");
    if (zza.zzac(bundle)) {  // true if msg is notification sent from FirebaseConsole
        if (!zza.zzdc((Context)this)) { // true if app is on foreground
            zza.zzer((Context)this).zzas(bundle); // create notification
            return;
        }
        // parse notification data to allow use it in onMessageReceived whe app is on foreground
        if (FirebaseMessagingService.zzav(bundle)) {
            zzb.zzo((Context)this, intent);
        }
    }
    this.onMessageReceived(new RemoteMessage(bundle));
}

This code is from version 9.4.0, method will have different names in different version because of obfuscation.

Search for all occurrences of a string in a mysql database

If you can use a bash - here is a script: It needs a user dbread with pass dbread on the database.

#!/bin/bash
IFS='
'
DBUSER=dbread
DBPASS=dbread
echo -n "Which database do you want to search in (press 0 to see all databases): " 
read DB
echo -n "Which string do you want to search: " 
read SEARCHSTRING
for i in `mysql $DB -u$DBUSER -p$DBPASS -e "show tables" | grep -v \`mysql $DB -u$DBUSER -p$DBPASS -e "show tables" | head -1\``
do
for k in `mysql $DB -u$DBUSER -p$DBPASS -e "desc $i" | grep -v \`mysql $DB -u$DBUSER -p$DBPASS -e "desc $i" | head -1\` | grep -v int | awk '{print $1}'`
do
if [ `mysql $DB -u$DBUSER -p$DBPASS -e "Select * from $i where $k='$SEARCHSTRING'" | wc -l` -gt 1 ]
then
echo " Your searchstring was found in table $i, column $k"
fi
done
done

If anyone wants an explanation: http://infofreund.de/?p=1670

Find Number of CPUs and Cores per CPU using Command Prompt

If you want to find how many processors (or CPUs) a machine has the same way %NUMBER_OF_PROCESSORS% shows you the number of cores, save the following script in a batch file, for example, GetNumberOfCores.cmd:

@echo off
for /f "tokens=*" %%f in ('wmic cpu get NumberOfCores /value ^| find "="') do set %%f

And then execute like this:

GetNumberOfCores.cmd

echo %NumberOfCores%

The script will set a environment variable named %NumberOfCores% and it will contain the number of processors.

redistributable offline .NET Framework 3.5 installer for Windows 8

Try this command:

Dism.exe /online /enable-feature /featurename:NetFX3 /Source:I:\Sources\sxs /LimitAccess

I: partition of your Windows DVD.

Return sql rows where field contains ONLY non-alphanumeric characters

If you have short strings you should be able to create a few LIKE patterns ('[^a-zA-Z0-9]', '[^a-zA-Z0-9][^a-zA-Z0-9]', ...) to match strings of different length. Otherwise you should use CLR user defined function and a proper regular expression - Regular Expressions Make Pattern Matching And Data Extraction Easier.

How to embed a Facebook page's feed into my website

If you are looking for a custom code instead of plugin, then this might help you. Facebook graph has under gone some changes since it has evolved. These steps are for the latest Graph API which I tried recently and worked well.

There are two main steps involved - 1. Getting Facebook Access Token, 2. Calling the Graph API passing the access token.

1. Getting the access token - Here is the step by step process to get the access token for your Facebook page. - Embed Facebook page feed on my website. As per this you need to create an app in Facebook developers page which would give you an App Id and an App Secret. Use these two and get the Access Token.

2. Calling the Graph API - This would be pretty simple once you get the access token. You just need to form a URL to Graph API with all the fields/properties you want to retrieve and make a GET request to this URL. Here is one example on how to do it in asp.net MVC. Embedding facebook feeds using asp.net mvc. This should be pretty similar in any other technology as it would be just a HTTP GET request.

Sample FQL Query: https://graph.facebook.com/FBPageName/posts?fields=full_picture,picture,link,message,created_time&limit=5&access_token=YOUR_ACCESS_TOKEN_HERE

Where to get "UTF-8" string literal in Java?

In Java 1.7+

Do not use "UTF-8" string, instead use Charset type parameter:

import java.nio.charset.StandardCharsets

...

new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);

How to convert this var string to URL in Swift

To Convert file path in String to NSURL, observe the following code

var filePathUrl = NSURL.fileURLWithPath(path)

How do I write to a Python subprocess' stdin?

To clarify some points:

As jro has mentioned, the right way is to use subprocess.communicate.

Yet, when feeding the stdin using subprocess.communicate with input, you need to initiate the subprocess with stdin=subprocess.PIPE according to the docs.

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

Also qed has mentioned in the comments that for Python 3.4 you need to encode the string, meaning you need to pass Bytes to the input rather than a string. This is not entirely true. According to the docs, if the streams were opened in text mode, the input should be a string (source is the same page).

If streams were opened in text mode, input must be a string. Otherwise, it must be bytes.

So, if the streams were not opened explicitly in text mode, then something like below should work:

import subprocess
command = ['myapp', '--arg1', 'value_for_arg1']
p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.communicate(input='some data'.encode())[0]

I've left the stderr value above deliberately as STDOUT as an example.

That being said, sometimes you might want the output of another process rather than building it up from scratch. Let's say you want to run the equivalent of echo -n 'CATCH\nme' | grep -i catch | wc -m. This should normally return the number characters in 'CATCH' plus a newline character, which results in 6. The point of the echo here is to feed the CATCH\nme data to grep. So we can feed the data to grep with stdin in the Python subprocess chain as a variable, and then pass the stdout as a PIPE to the wc process' stdin (in the meantime, get rid of the extra newline character):

import subprocess

what_to_catch = 'catch'
what_to_feed = 'CATCH\nme'

# We create the first subprocess, note that we need stdin=PIPE and stdout=PIPE
p1 = subprocess.Popen(['grep', '-i', what_to_catch], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

# We immediately run the first subprocess and get the result
# Note that we encode the data, otherwise we'd get a TypeError
p1_out = p1.communicate(input=what_to_feed.encode())[0]

# Well the result includes an '\n' at the end, 
# if we want to get rid of it in a VERY hacky way
p1_out = p1_out.decode().strip().encode()

# We create the second subprocess, note that we need stdin=PIPE
p2 = subprocess.Popen(['wc', '-m'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

# We run the second subprocess feeding it with the first subprocess' output.
# We decode the output to convert to a string
# We still have a '\n', so we strip that out
output = p2.communicate(input=p1_out)[0].decode().strip()

This is somewhat different than the response here, where you pipe two processes directly without adding data directly in Python.

Hope that helps someone out.

Cannot catch toolbar home button click event

The easiest approach we could do is change the home icon to a known icon and compare drawables (because android.R.id.home icon can differ to different api versions

so set a toolbar as actionbar SetSupportActionBar(_toolbar);

_toolbar.NavigationIcon = your_known_drawable_here;

   for (int i = 0; i < _toolbar.ChildCount; i++)
            {
                View v = _toolbar.GetChildAt(i);
                if (v is ImageButton)
                {
                    ImageButton imageButton = v as ImageButton;

                    if (imageButton.Drawable.GetConstantState().Equals(_bookMarkIcon.GetConstantState()))
                    {
                       //here v is the widget that contains the home  icon you can add your click events here 
                    }
                }
            }

Printing reverse of any String without using any predefined function?

You can do it either recursively or iteratively (looping).

Iteratively:

 static String reverseMe(String s) {
   StringBuilder sb = new StringBuilder();
   for(int i = s.length() - 1; i >= 0; --i)
     sb.append(s.charAt(i));
   return sb.toString();
 }

Recursively:

 static String reverseMe(String s) {
   if(s.length() == 0)
     return "";
   return s.charAt(s.length() - 1) + reverseMe(s.substring(0,s.length()-1));
 }

How do I set the background color of my main screen in Flutter?

I still cannot make this work. Any other ideas?

Django values_list vs values

The values() method returns a QuerySet containing dictionaries:

<QuerySet [{'comment_id': 1}, {'comment_id': 2}]>

The values_list() method returns a QuerySet containing tuples:

<QuerySet [(1,), (2,)]>

If you are using values_list() with a single field, you can use flat=True to return a QuerySet of single values instead of 1-tuples:

<QuerySet [1, 2]>

Number of days between two dates in Joda-Time

DateTime  dt  = new DateTime(laterDate);        

DateTime newDate = dt.minus( new  DateTime ( previousDate ).getMillis());

System.out.println("No of days : " + newDate.getDayOfYear() - 1 );    

Define a struct inside a class in C++

#include<iostream>
using namespace std;

class A
{
    public:
        struct Assign
        {
            public:
                int a=10;
                float b=20.5;
            private:
                double c=30.0;
                long int d=40;
         };
         struct Assign ALT;
};

class B: public A
{
public:
    int x = 10;
private:
    float y = 20.8;
};

int main()
{
   B myobj;
   A obj;
   //cout<<myobj.a<<endl;
   //cout<<myobj.b<<endl;
   //cout<<obj.a<<endl;
   //cout<<obj.b<<endl;
   cout<<myobj.ALT.a<<endl;

    return 0;
}

    enter code here

How can I give an imageview click effect like a button on Android?

You can do that by adding this attr

 android:background="?android:attr/selectableItemBackground"/

into your

submit a form in a new tab

<form target="_blank" [....]

will submit the form in a new tab... I am not sure if is this what you are looking for, please explain better...

Working copy XXX locked and cleanup failed in SVN

Today I have experienced above issue saying

svn: run 'svn cleanup' to remove locks (type 'svn help cleanup' for details)

And here is my solution, got working

  1. Closed Xcode IDE, from where I was trying to commit changes.
  2. On Mac --> Go to Terminal --> type below command

svn cleanup <Dir path of my SVN project code>

exmaple:

svn cleanup /Users/Ramdhan/SVN_Repo/ProjectName

  1. Hit enter and wait for cleanup done.
  2. Go To XCode IDE and Clean and Build project
  3. Now I can commit my all changes and take update as well.

Hope this will help.

How can I create persistent cookies in ASP.NET?

Here's how you can do that.

Writing the persistent cookie.

//create a cookie
HttpCookie myCookie = new HttpCookie("myCookie");

//Add key-values in the cookie
myCookie.Values.Add("userid", objUser.id.ToString());

//set cookie expiry date-time. Made it to last for next 12 hours.
myCookie.Expires = DateTime.Now.AddHours(12);

//Most important, write the cookie to client.
Response.Cookies.Add(myCookie);

Reading the persistent cookie.

//Assuming user comes back after several hours. several < 12.
//Read the cookie from Request.
HttpCookie myCookie = Request.Cookies["myCookie"];
if (myCookie == null)
{
    //No cookie found or cookie expired.
    //Handle the situation here, Redirect the user or simply return;
}

//ok - cookie is found.
//Gracefully check if the cookie has the key-value as expected.
if (!string.IsNullOrEmpty(myCookie.Values["userid"]))
{
    string userId = myCookie.Values["userid"].ToString();
    //Yes userId is found. Mission accomplished.
}

Another Repeated column in mapping for entity error

If you are stuck with a legacy database where someone already placed JPA annotations on but did NOT define the relationships and you are now trying to define them for use in your code, then you might NOT be able to delete the customerId @Column since other code may directly reference it already. In that case, define the relationships as follows:

@ManyToOne(optional=false)
@JoinColumn(name="productId",referencedColumnName="id_product", insertable=false, updatable=false)
private Product product;

@ManyToOne(optional=false)
@JoinColumn(name="customerId",referencedColumnName="id_customer", insertable=false, updatable=false)
private Customer customer;

This allows you to access the relationships. However, to add/update to the relationships you will have to manipulate the foreign keys directly via their defined @Column values. It's not an ideal situation, but if you are handed this sort of situation, at least you can define the relationships so that you can use JPQL successfully.

How do I remove an array item in TypeScript?

If array is type of objects, then the simplest way is

let foo_object // Item to remove
this.foo_objects = this.foo_objects.filter(obj => obj !== foo_object);

Cmake is not able to find Python-libraries

I was facing this problem while trying to compile OpenCV 3 on a Xubuntu 14.04 Thrusty Tahr system. With all the dev packages of Python installed, the configuration process was always returning the message:

Could NOT found PythonInterp: /usr/bin/python2.7 (found suitable version "2.7.6", minimum required is "2.7")
Could NOT find PythonLibs (missing: PYTHON_INCLUDE_DIRS) (found suitable exact version "2.7.6")
Found PythonInterp: /usr/bin/python3.4 (found suitable version "3.4", minimum required is "3.4")
Could NOT find PythonLibs (missing: PYTHON_LIBRARIES) (Required is exact version "3.4.0")

The CMake version available on Thrusty Tahr repositories is 2.8. Some posts inspired me to upgrade CMake. I've added a PPA CMake repository which installs CMake version 3.2.

After the upgrade everything ran smoothly and the compilation was successful.

XMLHttpRequest cannot load an URL with jQuery

Found a possible workaround that I don't believe was mentioned.

Here is a good description of the problem: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Basically as long as you use forms/url-encoded/plain text content types you are fine.

$.ajax({
    type: "POST",
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'text/plain'
    },
    dataType: "json",
    url: "http://localhost/endpoint",
    data: JSON.stringify({'DataToPost': 123}),
    success: function (data) {
        alert(JSON.stringify(data));
    }
});     

I use it with ASP.NET WebAPI2. So on the other end:

public static void RegisterWebApi(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();

    config.Formatters.Clear();
    config.Formatters.Add(new JsonMediaTypeFormatter());

    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
}

This way Json formatter gets used when parsing plain text content type.

And don't forget in Web.config:

<system.webServer>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET, POST" />
  </customHeaders>
</httpProtocol>    

Hope this helps.

Using R to download zipped data file, extract, and import data

Zip archives are actually more a 'filesystem' with content metadata etc. See help(unzip) for details. So to do what you sketch out above you need to

  1. Create a temp. file name (eg tempfile())
  2. Use download.file() to fetch the file into the temp. file
  3. Use unz() to extract the target file from temp. file
  4. Remove the temp file via unlink()

which in code (thanks for basic example, but this is simpler) looks like

temp <- tempfile()
download.file("http://www.newcl.org/data/zipfiles/a1.zip",temp)
data <- read.table(unz(temp, "a1.dat"))
unlink(temp)

Compressed (.z) or gzipped (.gz) or bzip2ed (.bz2) files are just the file and those you can read directly from a connection. So get the data provider to use that instead :)