Programs & Examples On #Keypad

"A namespace cannot directly contain members such as fields or methods"

The snippet you're showing doesn't seem to be directly responsible for the error.

This is how you can CAUSE the error:

namespace MyNameSpace
{
   int i; <-- THIS NEEDS TO BE INSIDE THE CLASS

   class MyClass
   {
      ...
   }
}

If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

IntelliJ how to zoom in / out

Double click Shift to open the quick actions. Then search for "Decrease Font Size" or "Increase Font Size" and hit Enter. To repeat the action you can doubleclick Shift and Enter

I prefer that way because it works even when you're using not your own Computer without opening settings. Also works without leaving fullscreen, which is useful if you are live coding.

keyCode values for numeric keypad?

You can simply run

$(document).keyup(function(e) {
    console.log(e.keyCode);
});

to see the codes of pressed keys in the browser console.

Or you can find key codes here: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode#Numpad_keys

How to disable keypad popup when on edittext?

Use This to enable and disable EditText....

InputMethodManager imm;

imm = (InputMethodManager)
getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);

if (isETEnable == true) {

    imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
    ivWalllet.setImageResource(R.drawable.checkbox_yes);
    etWalletAmount.setEnabled(true);
    etWalletAmount.requestFocus();
    isETEnable = false;
    } 
else {

    imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,0);
    ivWalllet.setImageResource(R.drawable.checkbox_unchecked);
    etWalletAmount.setEnabled(false);
    isETEnable = true;
    }

Android: How to set password property in an edit text?

My search for a similar solution for Visual Studio 2015/Xamarin lead me to this thread. While setting the EditText.InputType to Android.Text.InputTypes.TextVariationVisiblePassword properly hid the password during user entry, it did not 'hide' the password if it was visible before the EditText Layout was rendered (before the user submitted their password entry). In order to hide a visible password after the user submits their password and the EditText Layout is rendered, I used EditText.TransformationMethod = PasswordTransformationMethod.Instance as suggested by LuxuryMode.

What is a Sticky Broadcast?

A normal broadcast Intent is not available anymore after is was send and processed by the system. If you use the sendStickyBroadcast(Intent) method, the Intent is sticky, meaning the Intent you are sending stays around after the broadcast is complete.

you refer to my blog:enter link description here

dropping a global temporary table

yes - the engine will throw different exceptions for different conditions.

you will change this part to catch the exception and do something different

  EXCEPTION
      WHEN OTHERS THEN

here is a reference

http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96624/07_errs.htm

Return HTML from ASP.NET Web API

ASP.NET Core. Approach 1

If your Controller extends ControllerBase or Controller you can use Content(...) method:

[HttpGet]
public ContentResult Index() 
{
    return base.Content("<div>Hello</div>", "text/html");
}

ASP.NET Core. Approach 2

If you choose not to extend from Controller classes, you can create new ContentResult:

[HttpGet]
public ContentResult Index() 
{
    return new ContentResult 
    {
        ContentType = "text/html",
        Content = "<div>Hello World</div>"
    };
}

Legacy ASP.NET MVC Web API

Return string content with media type text/html:

public HttpResponseMessage Get()
{
    var response = new HttpResponseMessage();
    response.Content = new StringContent("<div>Hello World</div>");
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
}

Javascript, viewing [object HTMLInputElement]

<input type="text" />
<script>
$("input:text").change(function() {
    var value=$("input:text").val();
    alert(value);
});
</script>

use .val() to get value of the element (jquery method), $("input:text") this selector to select your input, .change() to bind an event handler to the "change" JavaScript event.

How to read from input until newline is found using scanf()?

//increase char array size if u want take more no. of characters.

#include <stdio.h>
int main()
{
    char s[10],s1[10];
    scanf("\n");//imp for below statement to work
    scanf("%[^\n]%c",s);//to take input till the you click enter
    scanf("%s",s1);//to take input till a space
    printf("%s",s);
    printf("%s",s1);
    return 0;
}

How to split a string content into an array of strings in PowerShell?

[string[]]$recipients = $address.Split('; ',[System.StringSplitOptions]::RemoveEmptyEntries)

How do I create a WPF Rounded Corner container?

You don't need a custom control, just put your container in a border element:

<Border BorderBrush="#FF000000" BorderThickness="1" CornerRadius="8">
   <Grid/>
</Border>

You can replace the <Grid/> with any of the layout containers...

What's the difference between integer class and numeric class in R

To my understanding - we do not declare a variable with a data type so by default R has set any number without L to be a numeric. If you wrote:

> x <- c(4L, 5L, 6L, 6L)
> class(x)
>"integer" #it would be correct

Example of Integer:

> x<- 2L
> print(x)

Example of Numeric (kind of like double/float from other programming languages)

> x<-3.4
> print(x)

Order a MySQL table by two columns

This maybe help somebody who is looking for the way to sort table by two columns, but in paralel way. This means to combine two sorts using aggregate sorting function. It's very useful when for example retrieving articles using fulltext search and also concerning the article publish date.

This is only example, but if you catch the idea you can find a lot of aggregate functions to use. You can even weight the columns to prefer one over second. The function of mine takes extremes from both sorts, thus the most valued rows are on the top.

Sorry if there exists simplier solutions to do this job, but I haven't found any.

SELECT
 `id`,
 `text`,
 `date`
 FROM
   (
   SELECT
     k.`id`,
     k.`text`,
     k.`date`,
     k.`match_order_id`,
     @row := @row + 1 as `date_order_id`
     FROM
     (
       SELECT
         t.`id`,
         t.`text`,
         t.`date`,
         @row := @row + 1 as `match_order_id`
         FROM
         (
           SELECT
             `art_id` AS `id`,
             `text`   AS `text`,
             `date`   AS `date`,
             MATCH (`text`) AGAINST (:string) AS `match`
             FROM int_art_fulltext
             WHERE MATCH (`text`) AGAINST (:string IN BOOLEAN MODE)
             LIMIT 0,101
         ) t,
         (
           SELECT @row := 0
         ) r
         ORDER BY `match` DESC
     ) k,
     (
       SELECT @row := 0
     ) l
     ORDER BY k.`date` DESC
   ) s
 ORDER BY (1/`match_order_id`+1/`date_order_id`) DESC

What is key=lambda

In Python, lambda is a keyword used to define anonymous functions(functions with no name) and that's why they are known as lambda functions.

Basically it is used for defining anonymous functions that can/can't take argument(s) and returns value of data/expression. Let's see an example.

>>> # Defining a lambda function that takes 2 parameters(as integer) and returns their sum
... 
>>> lambda num1, num2: num1 + num2 
<function <lambda> at 0x1004b5de8>
>>> 
>>> # Let's store the returned value in variable & call it(1st way to call)
... 
>>> addition = lambda num1, num2: num1 + num2
>>> addition(62, 5)
67
>>> addition(1700, 29)
1729
>>> 
>>> # Let's call it in other way(2nd way to call, one line call )
... 
>>> (lambda num1, num2: num1 + num2)(120, 1)
121
>>> (lambda num1, num2: num1 + num2)(-68, 2)
-66
>>> (lambda num1, num2: num1 + num2)(-68, 2**3)
-60
>>> 

Now let me give an answer of your 2nd question. The 1st answer is also great. This is my own way to explain with another example.

Suppose we have a list of items(integers and strings with numeric contents) as follows,

nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]

and I want to sort it using sorted() function, lets see what happens.

>>> nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]
>>> sorted(nums)
[1, 3, 4, '-1', '-10', '2', '5', '8']
>>>

It didn't give me what I expected as I wanted like below,

['-10', '-1', 1, '2', 3, 4, '5', '8']

It means we need some strategy(so that sorted could treat our string items as an ints) to achieve this. This is why the key keyword argument is used. Please look at the below one.

>>> nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]
>>> sorted(nums, key=int)
['-10', '-1', 1, '2', 3, 4, '5', '8']
>>> 

Lets use lambda function as a value of key

>>> names = ["Rishikesh", "aman", "Ajay", "Hemkesh", "sandeep", "Darshan", "Virendra", "Shwetabh"]
>>> names2 = sorted(names)
>>> names2
['Ajay', 'Darshan', 'Hemkesh', 'Rishikesh', 'Shwetabh', 'Virendra', 'aman', 'sandeep']
>>> # But I don't want this o/p(here our intention is to treat 'a' same as 'A')
...
>>> names3 = sorted(names, key=lambda name:name.lower())
>>> names3
['Ajay', 'aman', 'Darshan', 'Hemkesh', 'Rishikesh', 'sandeep', 'Shwetabh', 'Virendra']
>>>

You can define your own function(callable) and provide it as value of key.

Dear programers, I have written the below code for you, just try to understand it and comment your explanation. I would be glad to see your explanation(it's simple).

>>> def validator(item):
...     try:
...         return int(item)
...     except:
...         return 0
... 
>>> sorted(['gurmit', "0", 5, 2, 1, "front", -2, "great"], key=validator)
[-2, 'gurmit', '0', 'front', 'great', 1, 2, 5]
>>>

I hope it would be useful.

Rename column SQL Server 2008

Use sp_rename

EXEC sp_RENAME 'TableName.OldColumnName' , 'NewColumnName', 'COLUMN'

See: SQL SERVER – How to Rename a Column Name or Table Name

Documentation: sp_rename (Transact-SQL)

For your case it would be:

EXEC sp_RENAME 'table_name.old_name', 'new_name', 'COLUMN'

Remember to use single quotes to enclose your values.

How do I set the proxy to be used by the JVM

As is pointed out in other answers, if you need to use Authenticated proxies, there's no reliable way to do this purely using command-line variables - which is annoying if you're using someone else's application and don't want to mess with the source code.

Will Iverson makes the helpful suggestion over at Using HttpProxy to connect to a host with preemtive authentication to use a Proxy-management tool such as Proxifier ( http://www.proxifier.com/ for Mac OS X and Windows) to handle this.

For example with Proxifier you can set it up to only intercept java commands to be managed and redirected through its (authenticated) proxy. You're going to want to set the proxyHost and proxyPort values to blank in this case though, e.g. pass in -Dhttp.proxyHost= -Dhttp.proxyPort= to your java commands.

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Until I get a better option, this is the most "bootstrappy" answer I can work out:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/6cbrjrt5/

I have switched to using LESS and including the Bootstrap Source NuGet package to ensure compatibility (by giving me access to the bootstrap variables.less file:

in _layout.cshtml master page

  • Move footer outside the body-content container
  • Use boostrap's navbar-fixed-bottom on the footer
  • Drop the <hr/> before the footer (as now redundant)

Relevant page HTML:

<div class="container-fluid body-content">
    @RenderBody()
</div>
<footer class="navbar-fixed-bottom">
    <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
</footer>

In Site.less

  • Set HTML and BODY heights to 100%
  • Set BODY overflow to hidden
  • Set body-content div position to absolute
  • Set body-content div top to @navbar-height instead of hard-wiring value
  • Set body-content div bottom to 30px.
  • Set body-content div left and right to 0
  • Set body-content div overflow-y to auto

Site.less

html {
    height: 100%;

    body {
        height: 100%;
        overflow: hidden;

        .container-fluid.body-content {
            position: absolute;
            top: @navbar-height;
            bottom: 30px;
            right: 0;
            left: 0;
            overflow-y: auto;
        }
    }
}

The remaining problem is there seems to be no defining variable for the footer height in bootstrap. If someone call tell me if there is a magic 30px variable defined in Bootstrap I would appreciate it.

How do I download a file using VBA (without Internet Explorer)

I was struggling for hours on this until I figured out it can be done in one line of powershell:

invoke-webrequest -Uri "http://myserver/Reports/Pages/ReportViewer.aspx?%2fClients%2ftest&rs:Format=PDF&rs:ClearSession=true&CaseCode=12345678" -OutFile "C:\Temp\test.pdf" -UseDefaultCredentials

I looked into doing it purely in VBA but it runs to several pages, so I just call my powershell script from VBA every time I want to download a file.

Simple.

Setting the height of a SELECT in IE

select{
  *zoom: 1.6;
  *font-size: 9px;
}

If you change properties, size of select will change also in IE7.

Javascript Uncaught TypeError: Cannot read property '0' of undefined

There is no error when I use your code,

but I am calling the hasLetter method like this:

hasLetter("a",words);

How can I use mySQL replace() to replace strings in multiple records?

This will help you.

UPDATE play_school_data SET title= REPLACE(title, "&#39;", "'") WHERE title = "Elmer&#39;s Parade";

Result:

title = Elmer's Parade

Getting number of days in a month

You want DateTime.DaysInMonth:

int days = DateTime.DaysInMonth(year, month);

Obviously it varies by year, as sometimes February has 28 days and sometimes 29. You could always pick a particular year (leap or not) if you want to "fix" it to one value or other.

Multiple arguments to function called by pthread_create()?

Use:

struct arg_struct *args = malloc(sizeof(struct arg_struct));

And pass this arguments like this:

pthread_create(&tr, NULL, print_the_arguments, (void *)args);

Don't forget free args! ;)

How to change the session timeout in PHP?

Just a notice for a sharing hosting server or added on domains =

For your settings to work you must have a different save session dir for added domain by using php_value session.save_path folderA/sessionsA.

So create a folder to your root server, not into the public_html and not to be publicity accessed from outside. For my cpanel/server worked fine the folder permissions 0700. Give a try...

# Session timeout, 2628000 sec = 1 month, 604800 = 1 week, 57600 = 16 hours, 86400 = 1 day
ini_set('session.save_path', '/home/server/.folderA_sessionsA');
ini_set('session.gc_maxlifetime', 57600); 
ini_set('session.cookie_lifetime', 57600);
# session.cache_expire is in minutes unlike the other settings above         
ini_set('session.cache_expire', 960);
ini_set('session.name', 'MyDomainA');

before session_start();

or put this in your .htaccess file.

php_value session.save_path /home/server/.folderA_sessionsA
php_value session.gc_maxlifetime 57600
php_value session.cookie_lifetime 57600
php_value session.cache_expire 57600
php_value session.name MyDomainA

After many researching and testing this worked fine for shared cpanel/php7 server. Many thanks to: NoiS

Check if string contains a value in array

Here is a mini-function that search all values from an array in a given string. I use this in my site to check for visitor IP is in my permitted list on certain pages.

function array_in_string($str, array $arr) {
    foreach($arr as $arr_value) { //start looping the array
        if (stripos($str,$arr_value) !== false) return true; //if $arr_value is found in $str return true
    }
    return false; //else return false
}

how to use

$owned_urls = array('website1.com', 'website2.com', 'website3.com');

//this example should return FOUND
$string = 'my domain name is website3.com';
if (array_in_string($string, $owned_urls)) {
    echo "first: Match found<br>"; 
}
else {
    echo "first: Match not found<br>";
}

//this example should return NOT FOUND
$string = 'my domain name is website4.com';
if (array_in_string($string, $owned_urls)) {
    echo "second: Match found<br>"; 
}
else {
    echo "second: Match not found<br>";
}

DEMO: http://phpfiddle.org/lite/code/qf7j-8m09

How to convert a string to an integer in JavaScript?

To convert a String into Integer, I recommend using parseFloat and NOT parseInt. Here's why:

Using parseFloat:

parseFloat('2.34cms')  //Output: 2.34
parseFloat('12.5')     //Output: 12.5
parseFloat('012.3')    //Output: 12.3

Using parseInt:

parseInt('2.34cms')  //Output: 2
parseInt('12.5')     //Output: 12
parseInt('012.3')    //Output: 12

So if you have noticed parseInt discards the values after the decimals, whereas parseFloat lets you work with floating point numbers and hence more suitable if you want to retain the values after decimals. Use parseInt if and only if you are sure that you want the integer value.

Loop through a Map with JSTL

You can loop through a hash map like this

<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);                            
%>

  <c:forEach items="${itemList}" var="itemrow">
   <input  type="text"  value="<c:out value='${itemrow.test}'/>"/>
  </c:forEach>               

For more JSTL functionality look here

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

POST request with JSON body

I think cURL would be a good solution. This is not tested, but you can try something like this:

$body = '{
  "kind": "blogger#post",
  "blog": {
    "id": "8070105920543249955"
  },
  "title": "A new post",
  "content": "With <b>exciting</b> content..."
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/blogger/v3/blogs/8070105920543249955/posts/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: OAuth 2.0 token here"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$result = curl_exec($ch);

How can I make an svg scale with its parent container?

changing the SVG file was not a fair solution for me so instead, I used relative CSS units.

vh, vw, % are very handy. I used a CSS like height: 2.4vh; to set a dynamic size to my SVG images.

How to capitalize the first character of each word in a string

With this simple code:

String example="hello";

example=example.substring(0,1).toUpperCase()+example.substring(1, example.length());

System.out.println(example);

Result: Hello

MessageBox with YesNoCancel - No & Cancel triggers same event

Closing conformation alert:

Private Sub cmd_exit_click()

    ' By clicking on the button the MsgBox will appear
    If MsgBox("Are you sure want to exit now?", MsgBoxStyle.YesNo, "closing warning") = MsgBoxResult.Yes Then ' If you select yes in the MsgBox then it will close the window
               Me.Close() ' Close the window
    Else
        ' Will not close the application
    End If
End Sub

How do I monitor the computer's CPU, memory, and disk usage in Java?

Make a batch file "Pc.bat" as, typeperf -sc 1 "\mukit\processor(_Total)\%% Processor Time"

You can use the class MProcess,

/*
 *Md. Mukit Hasan
 *CSE-JU,35
 **/
import java.io.*;

public class MProcessor {

public MProcessor() { String s; try { Process ps = Runtime.getRuntime().exec("Pc.bat"); BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream())); while((s = br.readLine()) != null) { System.out.println(s); } } catch( Exception ex ) { System.out.println(ex.toString()); } }

}

Then after some string manipulation, you get the CPU use. You can use the same process for other tasks.

--Mukit Hasan

HTML5 Pre-resize images before uploading

I tackled this problem a few years ago and uploaded my solution to github as https://github.com/rossturner/HTML5-ImageUploader

robertc's answer uses the solution proposed in the Mozilla Hacks blog post, however I found this gave really poor image quality when resizing to a scale that was not 2:1 (or a multiple thereof). I started experimenting with different image resizing algorithms, although most ended up being quite slow or else were not great in quality either.

Finally I came up with a solution which I believe executes quickly and has pretty good performance too - as the Mozilla solution of copying from 1 canvas to another works quickly and without loss of image quality at a 2:1 ratio, given a target of x pixels wide and y pixels tall, I use this canvas resizing method until the image is between x and 2 x, and y and 2 y. At this point I then turn to algorithmic image resizing for the final "step" of resizing down to the target size. After trying several different algorithms I settled on bilinear interpolation taken from a blog which is not online anymore but accessible via the Internet Archive, which gives good results, here's the applicable code:

ImageUploader.prototype.scaleImage = function(img, completionCallback) {
    var canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);

    while (canvas.width >= (2 * this.config.maxWidth)) {
        canvas = this.getHalfScaleCanvas(canvas);
    }

    if (canvas.width > this.config.maxWidth) {
        canvas = this.scaleCanvasWithAlgorithm(canvas);
    }

    var imageData = canvas.toDataURL('image/jpeg', this.config.quality);
    this.performUpload(imageData, completionCallback);
};

ImageUploader.prototype.scaleCanvasWithAlgorithm = function(canvas) {
    var scaledCanvas = document.createElement('canvas');

    var scale = this.config.maxWidth / canvas.width;

    scaledCanvas.width = canvas.width * scale;
    scaledCanvas.height = canvas.height * scale;

    var srcImgData = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
    var destImgData = scaledCanvas.getContext('2d').createImageData(scaledCanvas.width, scaledCanvas.height);

    this.applyBilinearInterpolation(srcImgData, destImgData, scale);

    scaledCanvas.getContext('2d').putImageData(destImgData, 0, 0);

    return scaledCanvas;
};

ImageUploader.prototype.getHalfScaleCanvas = function(canvas) {
    var halfCanvas = document.createElement('canvas');
    halfCanvas.width = canvas.width / 2;
    halfCanvas.height = canvas.height / 2;

    halfCanvas.getContext('2d').drawImage(canvas, 0, 0, halfCanvas.width, halfCanvas.height);

    return halfCanvas;
};

ImageUploader.prototype.applyBilinearInterpolation = function(srcCanvasData, destCanvasData, scale) {
    function inner(f00, f10, f01, f11, x, y) {
        var un_x = 1.0 - x;
        var un_y = 1.0 - y;
        return (f00 * un_x * un_y + f10 * x * un_y + f01 * un_x * y + f11 * x * y);
    }
    var i, j;
    var iyv, iy0, iy1, ixv, ix0, ix1;
    var idxD, idxS00, idxS10, idxS01, idxS11;
    var dx, dy;
    var r, g, b, a;
    for (i = 0; i < destCanvasData.height; ++i) {
        iyv = i / scale;
        iy0 = Math.floor(iyv);
        // Math.ceil can go over bounds
        iy1 = (Math.ceil(iyv) > (srcCanvasData.height - 1) ? (srcCanvasData.height - 1) : Math.ceil(iyv));
        for (j = 0; j < destCanvasData.width; ++j) {
            ixv = j / scale;
            ix0 = Math.floor(ixv);
            // Math.ceil can go over bounds
            ix1 = (Math.ceil(ixv) > (srcCanvasData.width - 1) ? (srcCanvasData.width - 1) : Math.ceil(ixv));
            idxD = (j + destCanvasData.width * i) * 4;
            // matrix to vector indices
            idxS00 = (ix0 + srcCanvasData.width * iy0) * 4;
            idxS10 = (ix1 + srcCanvasData.width * iy0) * 4;
            idxS01 = (ix0 + srcCanvasData.width * iy1) * 4;
            idxS11 = (ix1 + srcCanvasData.width * iy1) * 4;
            // overall coordinates to unit square
            dx = ixv - ix0;
            dy = iyv - iy0;
            // I let the r, g, b, a on purpose for debugging
            r = inner(srcCanvasData.data[idxS00], srcCanvasData.data[idxS10], srcCanvasData.data[idxS01], srcCanvasData.data[idxS11], dx, dy);
            destCanvasData.data[idxD] = r;

            g = inner(srcCanvasData.data[idxS00 + 1], srcCanvasData.data[idxS10 + 1], srcCanvasData.data[idxS01 + 1], srcCanvasData.data[idxS11 + 1], dx, dy);
            destCanvasData.data[idxD + 1] = g;

            b = inner(srcCanvasData.data[idxS00 + 2], srcCanvasData.data[idxS10 + 2], srcCanvasData.data[idxS01 + 2], srcCanvasData.data[idxS11 + 2], dx, dy);
            destCanvasData.data[idxD + 2] = b;

            a = inner(srcCanvasData.data[idxS00 + 3], srcCanvasData.data[idxS10 + 3], srcCanvasData.data[idxS01 + 3], srcCanvasData.data[idxS11 + 3], dx, dy);
            destCanvasData.data[idxD + 3] = a;
        }
    }
};

This scales an image down to a width of config.maxWidth, maintaining the original aspect ratio. At the time of development this worked on iPad/iPhone Safari in addition to major desktop browsers (IE9+, Firefox, Chrome) so I expect it will still be compatible given the broader uptake of HTML5 today. Note that the canvas.toDataURL() call takes a mime type and image quality which will allow you to control the quality and output file format (potentially different to input if you wish).

The only point this doesn't cover is maintaining the orientation information, without knowledge of this metadata the image is resized and saved as-is, losing any metadata within the image for orientation meaning that images taken on a tablet device "upside down" were rendered as such, although they would have been flipped in the device's camera viewfinder. If this is a concern, this blog post has a good guide and code examples on how to accomplish this, which I'm sure could be integrated to the above code.

How can I load webpage content into a div on page load?

You can't inject content from another site (domain) using AJAX. The reason an iFrame is suited for these kinds of things is that you can specify the source to be from another domain.

Recursively counting files in a Linux directory

To determine how many files there are in the current directory, put in ls -1 | wc -l. This uses wc to do a count of the number of lines (-l) in the output of ls -1. It doesn't count dotfiles. Please note that ls -l (that's an "L" rather than a "1" as in the previous examples) which I used in previous versions of this HOWTO will actually give you a file count one greater than the actual count. Thanks to Kam Nejad for this point.

If you want to count only files and NOT include symbolic links (just an example of what else you could do), you could use ls -l | grep -v ^l | wc -l (that's an "L" not a "1" this time, we want a "long" listing here). grep checks for any line beginning with "l" (indicating a link), and discards that line (-v).

Relative speed: "ls -1 /usr/bin/ | wc -l" takes about 1.03 seconds on an unloaded 486SX25 (/usr/bin/ on this machine has 355 files). "ls -l /usr/bin/ | grep -v ^l | wc -l" takes about 1.19 seconds.

Source: http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x700.html

How many values can be represented with n bits?

What you're missing: Zero is a value

H2 database error: Database may be already in use: "Locked by another process"

I ran into similar problems running with ORMLite from a web application. I initially got stuck on the syntax to use server mode in the url. The answers above helped with that. Then I had the similar user/password error which was easier to figure out. I did not have to shut anything down or erase any files. The following code worked:

protected ConnectionSource getConnectionSource() throws SQLException {
    String databaseUrl = "jdbc:h2:tcp://localhost/~/test";
    return new JdbcConnectionSource(databaseUrl,"sa","sa");
}

To use H2 in server mode on wildfly, I Modifed connection-url in standalone.xml

<datasource jndi-name="java:jboss/datasources/ExampleDS" pool- name="ExampleDS" enabled="true" use-java-context="true">
     <connection-url>jdbc:h2:tcp://localhost/~/test</connection-url>
               …
</datasource>

Multiple types were found that match the controller named 'Home'

Right click the project and select clean the project. Or else completely empty the bin directory and then re-build again. This should clear of any left over assemblies from previous builds

How to call a parent method from child class in javascript?

Here's a nice way for child objects to have access to parent properties and methods using JavaScript's prototype chain, and it's compatible with Internet Explorer. JavaScript searches the prototype chain for methods and we want the child’s prototype chain to looks like this:

Child instance -> Child’s prototype (with Child methods) -> Parent’s prototype (with Parent methods) -> Object prototype -> null

The child methods can also call shadowed parent methods, as shown at the three asterisks *** below.

Here’s how:

_x000D_
_x000D_
//Parent constructor_x000D_
function ParentConstructor(firstName){_x000D_
    //add parent properties:_x000D_
    this.parentProperty = firstName;_x000D_
}_x000D_
_x000D_
//add 2 Parent methods:_x000D_
ParentConstructor.prototype.parentMethod = function(argument){_x000D_
    console.log(_x000D_
            "Parent says: argument=" + argument +_x000D_
            ", parentProperty=" + this.parentProperty +_x000D_
            ", childProperty=" + this.childProperty_x000D_
    );_x000D_
};_x000D_
_x000D_
ParentConstructor.prototype.commonMethod = function(argument){_x000D_
    console.log("Hello from Parent! argument=" + argument);_x000D_
};_x000D_
_x000D_
//Child constructor    _x000D_
function ChildConstructor(firstName, lastName){_x000D_
    //first add parent's properties_x000D_
    ParentConstructor.call(this, firstName);_x000D_
_x000D_
    //now add child's properties:_x000D_
    this.childProperty = lastName;_x000D_
}_x000D_
_x000D_
//insert Parent's methods into Child's prototype chain_x000D_
var rCopyParentProto = Object.create(ParentConstructor.prototype);_x000D_
rCopyParentProto.constructor = ChildConstructor;_x000D_
ChildConstructor.prototype = rCopyParentProto;_x000D_
_x000D_
//add 2 Child methods:_x000D_
ChildConstructor.prototype.childMethod = function(argument){_x000D_
    console.log(_x000D_
            "Child says: argument=" + argument +_x000D_
            ", parentProperty=" + this.parentProperty +_x000D_
            ", childProperty=" + this.childProperty_x000D_
    );_x000D_
};_x000D_
_x000D_
ChildConstructor.prototype.commonMethod = function(argument){_x000D_
    console.log("Hello from Child! argument=" + argument);_x000D_
_x000D_
    // *** call Parent's version of common method_x000D_
    ParentConstructor.prototype.commonMethod(argument);_x000D_
};_x000D_
_x000D_
//create an instance of Child_x000D_
var child_1 = new ChildConstructor('Albert', 'Einstein');_x000D_
_x000D_
//call Child method_x000D_
child_1.childMethod('do child method');_x000D_
_x000D_
//call Parent method_x000D_
child_1.parentMethod('do parent method');_x000D_
_x000D_
//call common method_x000D_
child_1.commonMethod('do common method');
_x000D_
_x000D_
_x000D_

Split comma-separated values

Lamba expression aren't included in c# 2.0

maybe you could refert to this post here on SO

More elegant way of declaring multiple variables at the same time

In your case, I would use YAML .

That is an elegant and professional standard for dealing with multiple parameters. The values are loaded from a separate file. You can see some info in this link:

https://keleshev.com/yaml-quick-introduction

But it is easier to Google it, as it is a standard, there are hundreds of info about it, you can find what best fits to your understanding. ;)

Best regards.

postgresql sequence nextval in schema

SELECT last_value, increment_by from "other_schema".id_seq;

for adding a seq to a column where the schema is not public try this.

nextval('"other_schema".id_seq'::regclass)

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

You are using str methods on an open file object.

You can read the file as a list of lines by simply calling list() on the file object:

with open('goodlines.txt') as f:
    mylist = list(f)

This does include the newline characters. You can strip those in a list comprehension:

with open('goodlines.txt') as f:
    mylist = [line.rstrip('\n') for line in f]

EF 5 Enable-Migrations : No context type was found in the assembly

I have been getting this same problem. I have even tried above enable migrations even though I have already done. But it keeps giving same error. Then I had to use the force switch to get overcome this problem. I am sure this will help in someone else's case as well as its a possible work around.

After enabling migration with force, you should update your database (Make sure default project is set correctly). Otherwise you will get another problem like explicit migrations are pending.

Then just execute your add-migrations or any other commands, it should work.

Enable-Migrations -ProjectName <PROJECT_NAME> -ContextTypeName <FULL_CONTEXT_NAMESPACE.YOUR_CONTEXT_NAME> -force

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

What are the ascii values of up down left right?

You can utilzed the special function for activating the navigation for your programming purpose. Below is the sample code for it.

   void Specialkey(int key, int x, int y)
    {
    switch(key)
    {
    case GLUT_KEY_UP: 
/*Do whatever you want*/        
         break; 
    case GLUT_KEY_DOWN: 
/*Do whatever you want*/
                 break;
    case GLUT_KEY_LEFT:
/*Do whatever you want*/
                 break;
    case GLUT_KEY_RIGHT:
/*Do whatever you want*/
                 break;
    }

    glutPostRedisplay();
    }

Add this to your main function

glutSpecialFunc(Specialkey);

Hope this will to solve the problem!

Why does the JFrame setSize() method not set the size correctly?

JFrame SetSize() contains the the Area + Border.

I think you have to set the size of ContentPane of that

jFrame.getContentPane().setSize(800,400);

So I would advise you to use JPanel embedded in a JFrame and you draw on that JPanel. This would minimize your problem.

JFrame jf = new JFrame();
JPanel jp = new JPanel();
jp.setPreferredSize(new Dimension(400,800));// changed it to preferredSize, Thanks!
jf.getContentPane().add( jp );// adding to content pane will work here. Please read the comment bellow.
jf.pack();

I am reading this from Javadoc

The JFrame class is slightly incompatible with Frame. Like all other JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame. This is different from the AWT Frame case. For example, to add a child to an AWT frame you'd write:

frame.add(child);

However using JFrame you need to add the child to the JFrame's content pane instead:

frame.getContentPane().add(child);

Http Servlet request lose params from POST body after read it once

Just overwriting of getInputStream() did not work in my case. My server implementation seems to parse parameters without calling this method. I did not find any other way, but re-implement the all four getParameter* methods as well. Here is the code of getParameterMap (Apache Http Client and Google Guava library used):

@Override
public Map<String, String[]> getParameterMap() {
    Iterable<NameValuePair> params = URLEncodedUtils.parse(getQueryString(), NullUtils.UTF8);

    try {
        String cts = getContentType();
        if (cts != null) {
            ContentType ct = ContentType.parse(cts);
            if (ct.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
                List<NameValuePair> postParams = URLEncodedUtils.parse(IOUtils.toString(getReader()), NullUtils.UTF8);
                params = Iterables.concat(params, postParams);
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    Map<String, String[]> result = toMap(params);
    return result;
}

public static Map<String, String[]> toMap(Iterable<NameValuePair> body) {
    Map<String, String[]> result = new LinkedHashMap<>();
    for (NameValuePair e : body) {
        String key = e.getName();
        String value = e.getValue();
        if (result.containsKey(key)) {
            String[] newValue = ObjectArrays.concat(result.get(key), value);
            result.remove(key);
            result.put(key, newValue);
        } else {
            result.put(key, new String[] {value});
        }
    }
    return result;
}

How to read file with async/await properly?

You can easily wrap the readFile command with a promise like so:

async function readFile(path) {
    return new Promise((resolve, reject) => {
      fs.readFile(path, 'utf8', function (err, data) {
        if (err) {
          reject(err);
        }
        resolve(data);
      });
    });
  }

then use:

await readFile("path/to/file");

How do I save and restore multiple variables in python?

If you need to save multiple objects, you can simply put them in a single list, or tuple, for instance:

import pickle

# obj0, obj1, obj2 are created here...

# Saving the objects:
with open('objs.pkl', 'w') as f:  # Python 3: open(..., 'wb')
    pickle.dump([obj0, obj1, obj2], f)

# Getting back the objects:
with open('objs.pkl') as f:  # Python 3: open(..., 'rb')
    obj0, obj1, obj2 = pickle.load(f)

If you have a lot of data, you can reduce the file size by passing protocol=-1 to dump(); pickle will then use the best available protocol instead of the default historical (and more backward-compatible) protocol. In this case, the file must be opened in binary mode (wb and rb, respectively).

The binary mode should also be used with Python 3, as its default protocol produces binary (i.e. non-text) data (writing mode 'wb' and reading mode 'rb').

Python concatenate text files

I don't know about elegance, but this works:

    import glob
    import os
    for f in glob.glob("file*.txt"):
         os.system("cat "+f+" >> OutFile.txt")

Search text in stored procedure in SQL Server

Have you tried using some of the third party tools to do the search? There are several available out there that are free and that saved me a ton of time in the past.

Below are two SSMS Addins I used with good success.

ApexSQL Search – Searches both schema and data in databases and has additional features such as dependency tracking and more…

SSMS Tools pack – Has same search functionality as previous one and several other cool features. Not free for SQL Server 2012 but still very affordable.

I know this answer is not 100% related to the questions (which was more specific) but hopefully others will find this useful.

How many files can I put in a directory?

Keep in mind that on Linux if you have a directory with too many files, the shell may not be able to expand wildcards. I have this issue with a photo album hosted on Linux. It stores all the resized images in a single directory. While the file system can handle many files, the shell can't. Example:

-shell-3.00$ ls A*
-shell: /bin/ls: Argument list too long

or

-shell-3.00$ chmod 644 *jpg
-shell: /bin/chmod: Argument list too long

Parsing JSON Array within JSON Object

private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

 String jsonText = readAll(inputofyourjsonstream);
 JSONObject json = new JSONObject(jsonText);
 JSONArray arr = json.getJSONArray("sources");

Your arr would looks like: [ { "id":1001, "name":"jhon" }, { "id":1002, "name":"jhon" } ] You can use:

arr.getJSONObject(index)

to get the objects inside of the array.

MySQL "between" clause not inclusive?

Is the field you are referencing in your query a Date type or a DateTime type?

A common cause of the behavior you describe is when you use a DateTime type where you really should be using a Date type. That is, unless you really need to know what time someone was born, just use the Date type.

The reason the final day is not being included in your results is the way that the query is assuming the time portion of the dates that you did not specify in your query.

That is: Your query is being interpreted as up to Midnight between 2011-01-30 and 2011-01-31, but the data may have a value sometime later in the day on 2011-01-31.

Suggestion: Change the field to the Date type if it is a DateTime type.

AngularJs event to call after content is loaded

you can call javascript version of onload event in angular js. this ng-load event can be applied to any dom element like div, span, body, iframe, img etc. following is the link to add ng-load in your existing project.

download ng-load for angular js

Following is example for iframe, once it is loaded testCallbackFunction will be called in controller

EXAMPLE

JS

    // include the `ngLoad` module
    var app = angular.module('myApp', ['ngLoad']);
    app.controller('myCtrl', function($scope) {
        $scope.testCallbackFunction = function() {
          //TODO : Things to do once Element is loaded
        };

    });  

HTML

  <div ng-app='myApp' ng-controller='myCtrl'> 
      <iframe src="test.html" ng-load callback="testCallbackFunction()">  
  </div>

Flutter Countdown Timer

Here is an example using Timer.periodic :

Countdown starts from 10 to 0 on button click :

import 'dart:async';

[...]

Timer _timer;
int _start = 10;

void startTimer() {
  const oneSec = const Duration(seconds: 1);
  _timer = new Timer.periodic(
    oneSec,
    (Timer timer) {
      if (_start == 0) {
        setState(() {
          timer.cancel();
        });
      } else {
        setState(() {
          _start--;
        });
      }
    },
  );
}

@override
void dispose() {
  _timer.cancel();
  super.dispose();
}

Widget build(BuildContext context) {
  return new Scaffold(
    appBar: AppBar(title: Text("Timer test")),
    body: Column(
      children: <Widget>[
        RaisedButton(
          onPressed: () {
            startTimer();
          },
          child: Text("start"),
        ),
        Text("$_start")
      ],
    ),
  );
}

Result :

Flutter countdown timer example

You can also use the CountdownTimer class from the quiver.async library, usage is even simpler :

import 'package:quiver/async.dart';

[...]

int _start = 10;
int _current = 10;

void startTimer() {
  CountdownTimer countDownTimer = new CountdownTimer(
    new Duration(seconds: _start),
    new Duration(seconds: 1),
  );

  var sub = countDownTimer.listen(null);
  sub.onData((duration) {
    setState(() { _current = _start - duration.elapsed.inSeconds; });
  });

  sub.onDone(() {
    print("Done");
    sub.cancel();
  });
}

Widget build(BuildContext context) {
  return new Scaffold(
    appBar: AppBar(title: Text("Timer test")),
    body: Column(
      children: <Widget>[
        RaisedButton(
          onPressed: () {
            startTimer();
          },
          child: Text("start"),
        ),
        Text("$_current")
      ],
    ),
  );
}

EDIT : For the question in comments about button click behavior

With the above code which uses Timer.periodic, a new timer will indeed be started on each button click, and all these timers will update the same _start variable, resulting in a faster decreasing counter.

There are multiple solutions to change this behavior, depending on what you want to achieve :

  • disable the button once clicked so that the user could not disturb the countdown anymore (maybe enable it back once timer is cancelled)
  • wrap the Timer.periodic creation with a non null condition so that clicking the button multiple times has no effect
if (_timer != null) {
  _timer = new Timer.periodic(...);
}
  • cancel the timer and reset the countdown if you want to restart the timer on each click :
if (_timer != null) {
  _timer.cancel();
  _start = 10;
}
_timer = new Timer.periodic(...);
  • if you want the button to act like a play/pause button :
if (_timer != null) {
  _timer.cancel();
  _timer = null;
} else {
  _timer = new Timer.periodic(...);
}

You could also use this official async package which provides a RestartableTimer class which extends from Timer and adds the reset method.

So just call _timer.reset(); on each button click.

Finally, Codepen now supports Flutter ! So here is a live example so that everyone can play with it : https://codepen.io/Yann39/pen/oNjrVOb

JQuery to load Javascript file dynamically

Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.

You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:

$('#add_comment').click(function() {
    if(typeof TinyMCE == "undefined") {
        $.getScript('tinymce.js', function() {
            TinyMCE.init();
        });
    }
});

Assuming you only have to call init on it once, that is. If not, you can figure it out from here :)

C# Iterating through an enum? (Indexing a System.Array)

Array has a GetValue(Int32) method which you can use to retrieve the value at a specified index.

Array.GetValue

Directory-tree listing in Python

This is a way to traverse every file and directory in a directory tree:

import os

for dirname, dirnames, filenames in os.walk('.'):
    # print path to all subdirectories first.
    for subdirname in dirnames:
        print(os.path.join(dirname, subdirname))

    # print path to all filenames.
    for filename in filenames:
        print(os.path.join(dirname, filename))

    # Advanced usage:
    # editing the 'dirnames' list will stop os.walk() from recursing into there.
    if '.git' in dirnames:
        # don't go into any .git directories.
        dirnames.remove('.git')

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

Another simple solution (not very elegant, but not too ugly also) is to place a inner div / span then get his height ($(this).find('span).height()).

Here is an example of using this strategy:

_x000D_
_x000D_
$(".more").click(function(){_x000D_
if($(this).parent().find('.showMore').length) {_x000D_
$(this).parent().find('.showMore').removeClass('showMore').css('max-height','90px');_x000D_
$(this).parent().find('.more').removeClass('less').text('More');_x000D_
} else {_x000D_
$(this).parent().find('.text').addClass('showMore').css('max-height',$(this).parent().find('span').height());_x000D_
$(this).parent().find('.more').addClass('less').text('Less');_x000D_
}_x000D_
});
_x000D_
* {transition: all 0.5s;}_x000D_
.text {position:relative;width:400px;max-height:90px;overflow:hidden;}_x000D_
.showMore {}_x000D_
.text::after {_x000D_
  content: "";_x000D_
    position: absolute; bottom: 0; left: 0;_x000D_
        box-shadow: inset 0 -26px 22px -17px #fff;_x000D_
    height: 39px;_x000D_
  z-index:99999;_x000D_
  width:100%;_x000D_
  opacity:1;_x000D_
}_x000D_
.showMore::after {opacity:0;}_x000D_
.more {border-top:1px solid gray;width:400px;color:blue;cursor:pointer;}_x000D_
.more.less {border-color:#fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<div class="text">_x000D_
<span>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</span></div>_x000D_
<div class="more">More</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

(This specific example is using this trick to animate the max-height and avoiding animation delay when collapsing (when using high number for the max-height property).

Flattening a shallow list in Python

Off the top of my head, you can eliminate the lambda:

reduce(list.__add__, map(list, [mi.image_set.all() for mi in list_of_menuitems]))

Or even eliminate the map, since you've already got a list-comp:

reduce(list.__add__, [list(mi.image_set.all()) for mi in list_of_menuitems])

You can also just express this as a sum of lists:

sum([list(mi.image_set.all()) for mi in list_of_menuitems], [])

How to check if a file exists from inside a batch file

C:\>help if

Performs conditional processing in batch programs.

IF [NOT] ERRORLEVEL number command

IF [NOT] string1==string2 command

IF [NOT] EXIST filename command

Correct way to handle conditional styling in React

 <div style={{ visibility: this.state.driverDetails.firstName != undefined? 'visible': 'hidden'}}></div>

Checkout the above code. That will do the trick.

Correct way to delete cookies server-side

Use Max-Age=-1 rather than "Expires". It is shorter, less picky about the syntax, and Max-Age takes precedence over Expires anyway.

Find difference between timestamps in seconds in PostgreSQL

select age(timestamp_A, timestamp_B)

Answering to Igor's comment:

select age('2013-02-28 11:01:28'::timestamp, '2011-12-31 11:00'::timestamp);
              age              
-------------------------------
 1 year 1 mon 28 days 00:01:28

How can I send JSON response in symfony2 controller

If your data is already serialized:

a) send a JSON response

public function someAction()
{
    $response = new Response();
    $response->setContent(file_get_contents('path/to/file'));
    $response->headers->set('Content-Type', 'application/json');
    return $response;
}

b) send a JSONP response (with callback)

public function someAction()
{
    $response = new Response();
    $response->setContent('/**/FUNCTION_CALLBACK_NAME(' . file_get_contents('path/to/file') . ');');
    $response->headers->set('Content-Type', 'text/javascript');
    return $response;
}

If your data needs be serialized:

c) send a JSON response

public function someAction()
{
    $response = new JsonResponse();
    $response->setData([some array]);
    return $response;
}

d) send a JSONP response (with callback)

public function someAction()
{
    $response = new JsonResponse();
    $response->setData([some array]);
    $response->setCallback('FUNCTION_CALLBACK_NAME');
    return $response;
}

e) use groups in Symfony 3.x.x

Create groups inside your Entities

<?php

namespace Mindlahus;

use Symfony\Component\Serializer\Annotation\Groups;

/**
 * Some Super Class Name
 *
 * @ORM    able("table_name")
 * @ORM\Entity(repositoryClass="SomeSuperClassNameRepository")
 * @UniqueEntity(
 *  fields={"foo", "boo"},
 *  ignoreNull=false
 * )
 */
class SomeSuperClassName
{
    /**
     * @Groups({"group1", "group2"})
     */
    public $foo;
    /**
     * @Groups({"group1"})
     */
    public $date;

    /**
     * @Groups({"group3"})
     */
    public function getBar() // is* methods are also supported
    {
        return $this->bar;
    }

    // ...
}

Normalize your Doctrine Object inside the logic of your application

<?php

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
// For annotations
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;

...

$repository = $this->getDoctrine()->getRepository('Mindlahus:SomeSuperClassName');
$SomeSuperObject = $repository->findOneById($id);

$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer($classMetadataFactory);
$callback = function ($dateTime) {
    return $dateTime instanceof \DateTime
        ? $dateTime->format('m-d-Y')
        : '';
};
$normalizer->setCallbacks(array('date' => $callback));
$serializer = new Serializer(array($normalizer), array($encoder));
$data = $serializer->normalize($SomeSuperObject, null, array('groups' => array('group1')));

$response = new Response();
$response->setContent($serializer->serialize($data, 'json'));
$response->headers->set('Content-Type', 'application/json');
return $response;

Is it possible to preview stash contents in git?

The following command can be used to extract diff of stashed change againest any other stash or commit or branch or HEAD.

git stash show
git show
git diff
git difftool

Let’s see, how we can use each of the above mentioned commands.

  1. git stash show

The simple command git stash show gives very brief summary of changes of file, but will not show the diff of changes against current HEAD.

  1. git show

The command git-show is used to see various types of objects.

The command git-show is not only used to visualize stash changes, but also used to see one or more objects like blobs, trees, tags and commits.

  1. git diff

The command git-diff is also one of common command which is used to show changes between commits, commit and working tree, etc.

By default, git diff will show the diff of selected stash against(modified files) current state of repository unless other stash reference or commit is specified.

To get difference between top most stash stash@{0} and master branch:

$ git diff stash@{0} master

Only display the names of file not diff of changes:

$ git diff --name-only stash@{0} master

See the diff between selected stashes for a selected file:

$ git diff stash@{0}^1 stash@{0} --

  1. git difftool

The command git-difftool can also be used to find diff between selected stash and selected commit or branch or stash

See the difference between latest two stashes:

$ git difftool stash@{0} stash@{0}^1

git difftool --dir-diff stash@{0} stash@{0}^1

Summary:

Commands which are useful to extract the diff from selected stash git stash show, git show, git diff, git difftool .

See difference using command git stash show,

git stash show -p stash@{0}

See the changes in the stash using command git show,

git show stash@{1}

See the difference between latest stash and selected commit using command git diff,

git diff stash@{0}

References:

https://howto.lintel.in/how-to-see-stashed-changes-using-git-stash/

https://git-scm.com/docs/git-show

https://git-scm.com/docs/git-stash

Check if element at position [x] exists in the list

if(list.ElementAtOrDefault(2) != null)
{
   // logic
}

ElementAtOrDefault() is part of the System.Linq namespace.

Although you have a List, so you can use list.Count > 2.

Maven package/install without test (skip tests)

The best and the easiest way to do it, in IntelliJ Idea in the window “Maven Project”, and just don’t click on the test button. I hope, I helped you. Have a good day :)

How do I reference a cell within excel named range?

I've been willing to use something like this in a sheet where all lines are identical and usually refer to other cells in the same line - but as the formulas get complex, the references to other columns get hard to read. I tried the trick given in other answers, with for example column A named as "Sales" I can refers to it as INDEX(Sales;row()) but I found it a bit too long for my tastes.

However, in this particular case, I found that using Sales alone works just as well - Excel (2010 here) just gets the corresponding row automatically.

It appears to work with other ranges too; for example let's say I have values in A2:A11 which I name Sales, I can just use =Sales*0.21 in B2:11 and it will use the same row value, giving out ten different results.


I also found a nice trick on this page: named ranges can also be relative. Going back to your original question, if your value "Age" is in column A and assuming you're using that value in formulas in the same line, you can define Age as being $A2 instead of $A$2, so that when used in B5 or C5 for example, it will actually refer to $A5. (The Name Manager always show the reference relative to the cell currently selected)

erlative named range

Calling dynamic function with dynamic number of parameters

Here's what you need:

function mainfunc (){
    window[Array.prototype.shift.call(arguments)].apply(null, arguments);
}

The first argument is used as the function name and all of the remaining ones are used as arguments to the called function...

We're able to use the shift method to return and then delete the first value from the arguments array. Note that we've called it from the Array prototype since, strictly speaking, 'arguments' is not a real array and so doesn't inherit the shift method like a regular array would.


You can also call the shift method like this:

[].shift.call(arguments);

How to know if other threads have finished?

Do you want to wait for them to finish? If so, use the Join method.

There is also the isAlive property if you just want to check it.

How do I call a SQL Server stored procedure from PowerShell?

This answer was pulled from http://www.databasejournal.com/features/mssql/article.php/3683181

This same example can be used for any adhoc queries. Let us execute the stored procedure “sp_helpdb” as shown below.

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=HOME\SQLEXPRESS;Database=master;Integrated Security=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "sp_helpdb"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]

What is the proper REST response code for a valid request but an empty data?

TL;DR:

  • If no user is found at /users/9, you should return a 404.
  • If no user is found at /users?id=9, you should return a 204.

Long Version:

After reviewing my own usage of these status codes and the examples on this post, I would have to say that 404 is the appropriate response if User #9 was Not Found at the url of /users/9.

In my system today, our Application Insights logs are filled with hundreds of logged 404 errors that muddy up our logs all because we decided to return 404's when /users/9 had no correlating data. However, this does not mean our approach was incorrect when setting up our responses, rather, I would propose that it means our approach was incorrect when setting up our routing.

If you're expecting an endpoint to get a lot of traffic and are concerned about logging too many 404 errors, you should change your routing to fall in line with the status code you want, not force a status code to be inappropriately used.

We've since decided to make 2 changes to our code:

  1. Change our route to work by expecting /users?id=9
  2. Change our error code to 204 so that the 404's don't fill our AI logs.

At the end of the day, the architect of the API needs to understand how their API will be used and what kind of routing will be appropriate for that use case.

I believe that in the case of /users/9, the resource you are requesting is the user itself, User #9; you are asking the server to respond with an object identified as "9" that happens to exist in a path that has the word 'user' in it. If that object was not found, you should get a 404.

However, if you call /users?id=9, I feel that the resource you are requesting is the Users controller while also providing a bit more specificity so that it doesn't return a full list of all users. You are asking the server to respond with a specific user who can be identified by an ID number defined in the query string. Thusly, if no data was found, it makes sense to me that a 204 would be applicable because even if no data was found, the controller was.

The query string approach also accomplishes something that I think helps not only the API developers but also the client developers (especially junior developers or future developers who inherit this code, or code that makes calls to it):

It becomes immediately clear to anyone involved that 9 is an ID, not some arbitrary number. This point may seem moot in such a basic example, but consider a system that uses GUIDs as row ID's or allows you to get data by a person's name, or even a system that is returning info for specific ZIP/postal codes instead of row ID's. It would be useful for all developers involved if, at a glance, they knew whether that identifying parameter was a first, last, full name, or a ZIP/postal code instead of an ID.

MySQL integer field is returned as string in PHP

When you select data from a MySQL database using PHP the datatype will always be converted to a string. You can convert it back to an integer using the following code:

$id = (int) $row['userid'];

Or by using the function intval():

$id = intval($row['userid']);

How to add two edit text fields in an alert dialog

 LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.text_entry, null);
//text_entry is an Layout XML file containing two text field to display in alert dialog
final EditText input1 = (EditText) textEntryView.findViewById(R.id.EditText1);
final EditText input2 = (EditText) textEntryView.findViewById(R.id.EditText2);             
input1.setText("DefaultValue", TextView.BufferType.EDITABLE);
input2.setText("DefaultValue", TextView.BufferType.EDITABLE);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);

alert.setIcon(R.drawable.icon)
     .setTitle("Enter the Text:")
     .setView(textEntryView)
     .setPositiveButton("Save", 
         new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int whichButton) {
                    Log.i("AlertDialog","TextEntry 1 Entered "+input1.getText().toString());
                    Log.i("AlertDialog","TextEntry 2 Entered "+input2.getText().toString());
                    /* User clicked OK so do some stuff */
             }
         })
     .setNegativeButton("Cancel",
         new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog,
                    int whichButton) {
             }
         });
alert.show();

Common sources of unterminated string literal

Scan the code that comes before the line# mentioned by error message. Whatever is unterminated has resulted in something downstream, (the blamed line#), to be flagged.

ASP.NET Core Web API exception handling

Use built-in Exception Handling Middleware

Step 1. In your startup, register your exception handling route:

// It should be one of your very first registrations
app.UseExceptionHandler("/error"); // Add this
app.UseEndpoints(endpoints => endpoints.MapControllers());

Step 2. Create controller that will handle all exceptions and produce error response:

[ApiExplorerSettings(IgnoreApi = true)]
public class ErrorsController : ControllerBase
{
    [Route("error")]
    public MyErrorResponse Error()
    {
        var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
        var exception = context.Error; // Your exception
        var code = 500; // Internal Server Error by default

        if      (exception is MyNotFoundException) code = 404; // Not Found
        else if (exception is MyUnauthException)   code = 401; // Unauthorized
        else if (exception is MyException)         code = 400; // Bad Request

        Response.StatusCode = code; // You can use HttpStatusCode enum instead

        return new MyErrorResponse(exception); // Your error model
    }
}

A few important notes and observations:

  • [ApiExplorerSettings(IgnoreApi = true)] is needed. Otherwise, it may break your Swashbuckle swagger
  • Again, app.UseExceptionHandler("/error"); has to be one of the very top registrations in your Startup Configure(...) method. It's probably safe to place it at the top of the method.
  • The path in app.UseExceptionHandler("/error") and in controller [Route("error")] should be the same, to allow the controller handle exceptions redirected from exception handler middleware.

Microsoft documentation for this subject is not that great but has some interesting ideas. I'll just leave the link here.

Response models and custom exceptions

Implement your own response model and exceptions. This example is just a good starting point. Every service would need to handle exceptions in its own way. But with this code, you have full flexibility and control over handling exceptions and returning a proper result to the caller.

An example of error response model (just to give you some ideas):

public class MyErrorResponse
{
    public string Type { get; set; }
    public string Message { get; set; }
    public string StackTrace { get; set; }

    public MyErrorResponse(Exception ex)
    {
        Type = ex.GetType().Name;
        Message = ex.Message;
        StackTrace = ex.ToString();
    }
}

For simpler services, you might want to implement http status code exception that would look like this:

public class HttpStatusException : Exception
{
    public HttpStatusCode Status { get; private set; }

    public HttpStatusException(HttpStatusCode status, string msg) : base(msg)
    {
        Status = status;
    }
}

This can be thrown like that:

throw new HttpStatusCodeException(HttpStatusCode.NotFound, "User not found");

Then your handling code could be simplified to:

if (exception is HttpStatusException httpException)
{
    code = (int) httpException.Status;
}

Why so un-obvious HttpContext.Features.Get<IExceptionHandlerFeature>()?

ASP.NET Core developers embraced the concept of middlewares where different aspects of functionality such as Auth, Mvc, Swagger etc. are separated and executed sequentially by processing the request and returning the response or passing the execution to the next middleware. With this architecture, MVC itself, for instance, would not be able to handle errors happening in Auth. So, they came up with exception handling middleware that catches all the exceptions happening in middlewares registered down in the pipeline, pushes exception data into HttpContext.Features, and re-runs the pipeline for specified route (/error), allowing any middleware to handle this exception, and the best way to handle it is by our Controllers to maintain proper content negotiation.

SOAP client in .NET - references or examples?

Take a look at "using WCF Services with PHP". It explains the basics of what you need.

As a theory summary:

WCF or Windows Communication Foundation is a technology that allow to define services abstracted from the way - the underlying communication method - they'll be invoked.

The idea is that you define a contract about what the service does and what the service offers and also define another contract about which communication method is used to actually consume the service, be it TCP, HTTP or SOAP.

You have the first part of the article here, explaining how to create a very basic WCF Service.

More resources:

Using WCF with PHP5.

Aslo take a look to NuSOAP. If you now NuSphere this is a toolkit to let you connect from PHP to an WCF service.

How to scroll page in flutter

You can use this one and it's best practice.

SingleChildScrollView(
  child: Column(
    children: <Widget>[
      //Your Widgets
      //Your Widgets,
      //Your Widgets
    ],
  ),
);

Logger slf4j advantages of formatting with {} instead of string concatenation

Another alternative is String.format(). We are using it in jcabi-log (static utility wrapper around slf4j).

Logger.debug(this, "some variable = %s", value);

It's much more maintainable and extendable. Besides, it's easy to translate.

How do you create a read-only user in PostgreSQL?

I read trough all the possible solutions, which are all fine, if you remember to connect to the database before you grant the things ;) Thanks anyway to all other solutions!!!

user@server:~$ sudo su - postgres

create psql user:

postgres@server:~$ createuser --interactive 
Enter name of role to add: readonly
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) n
Shall the new role be allowed to create more new roles? (y/n) n

start psql cli and set a password for the created user:

postgres@server:~$ psql
psql (10.6 (Ubuntu 10.6-0ubuntu0.18.04.1), server 9.5.14)
Type "help" for help.

postgres=# alter user readonly with password 'readonly';
ALTER ROLE

connect to the target database:

postgres=# \c target_database 
psql (10.6 (Ubuntu 10.6-0ubuntu0.18.04.1), server 9.5.14)
You are now connected to database "target_database" as user "postgres".

grant all the needed privileges:

target_database=# GRANT CONNECT ON DATABASE target_database TO readonly;
GRANT

target_database=# GRANT USAGE ON SCHEMA public TO readonly ;
GRANT

target_database=# GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly ;
GRANT

alter default privileges for targets db public shema:

target_database=# ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;
ALTER DEFAULT PRIVILEGES

How to Allow Remote Access to PostgreSQL database

After set listen_addresses = '*' in postgresql.conf

Edit the pg_hba.conf file and add the following entry at the very end of file:

host    all             all              0.0.0.0/0                       md5
host    all             all              ::/0                            md5

For finding the config files this link might help you.

Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (plus shared security)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  http://www.springframework.org/schema/cache 
        http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

        <mvc:annotation-driven/>
        <context:component-scan base-package="com.testpoc.controller"/>

        <bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="ViewClass" value="org.springframework.web.servlet.view.JstlView"></property>
            <property name="prefix">
                <value>/WEB-INF/pages/</value>
            </property>
            <property name="suffix">
                <value>.jsp</value>
            </property>
        </bean>

</beans>

Loop through array of values with Arrow Function

One statement can be written as such:

someValues.forEach(x => console.log(x));

or multiple statements can be enclosed in {} like this:

someValues.forEach(x => { let a = 2 + x; console.log(a); });

How to include another XHTML in XHTML using JSF 2.0 Facelets?

Included page:

<!-- opening and closing tags of included page -->
<ui:composition ...>
</ui:composition>

Including page:

<!--the inclusion line in the including page with the content-->
<ui:include src="yourFile.xhtml"/>
  • You start your included xhtml file with ui:composition as shown above.
  • You include that file with ui:include in the including xhtml file as also shown above.

Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

In VB.Net. Do NOT use "IsNot Nothing" when you can use ".HasValue". I just solved an "Operation could destabilize the runtime" Medium trust error by replacing "IsNot Nothing" with ".HasValue" In one spot. I don't really understand why, but something is happening differently in the compiler. I would assume that "!= null" in C# may have the same issue.

Passing variable number of arguments around

There's no way of calling (eg) printf without knowing how many arguments you're passing to it, unless you want to get into naughty and non-portable tricks.

The generally used solution is to always provide an alternate form of vararg functions, so printf has vprintf which takes a va_list in place of the .... The ... versions are just wrappers around the va_list versions.

jquery: animate scrollLeft

First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate

$('.swipeRight').click(function()
{

    $('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});

$('.swipeLeft').click(function()
{
    $('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});

The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.

Find OpenCV Version Installed on Ubuntu

1) Direct Answer: Try this:

   sudo updatedb
   locate OpenCVConfig.cmake

For me, I get:

   /home/pkarasev3/source/opencv/build/OpenCVConfig.cmake

To see the version, you can try:

   cat /home/pkarasev3/source/opencv/build/OpenCVConfig.cmake

giving

    ....
   SET(OpenCV_VERSION 2.3.1)
    ....

2) Better Answer:

"sudo make install" is your enemy, don't do that when you need to compile/update the library often and possibly debug step through it's internal functions. Notice how my config file is in a local build directory, not in /usr/something. You will avoid this confusion in the future, and can maintain several different versions even (debug and release, for example).

Edit: the reason this questions seems to arise often for OpenCV as opposed to other libraries is that it changes rather dramatically and fast between versions, and many of the operations are not so well-defined / well-constrained so you can't just rely on it to be a black-box like you do for something like libpng or libjpeg. Thus, better to not install it at all really, but just compile and link to the build folder.

SoapFault exception: Could not connect to host

In my case, disabled SELINUX allow PHP to call my WebService. I run PHP in FPM with Apache2

SELinux status :

# sestatus

Disable SELinux :

setenforce 0

Enable SELinux :

# setenforce 1

Permanent disable :

edit this file /etc/selinux/config

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

[Solved for me]

Eclipse project properties->Java build path->Order and export

Uncheck Android private libraries.

An error occurred while collecting items to be installed (Access is denied)

None of the above worked for me.

Instead, I tried installing the plugins I needed via the Eclipse Market Place, and that worked without issue.

  1. Click "Help" Menu.
  2. Click "Eclipse Marketplace..." menu item.
  3. Enter the name of the plugin you want.
  4. Click "Install" when the plugin appears in the Marketplace List.
  5. Restart Eclipse.

Is it possible to set the stacking order of pseudo-elements below their parent element?

Speaking with regard to the spec (http://www.w3.org/TR/CSS2/zindex.html), since a.someSelector is positioned it creates a new stacking context that its children can't break out of. Leave a.someSelector unpositioned and then child a.someSelector:after may be positioned in the same context as a.someSelector.

"The system cannot find the file specified"

Considering that a LocalDb instance only intended for use in development. LocalDb is not available for production servers When you deploy the final result.

I think your connection string is pointing to a LocalDb instance and you need to take certain steps to turn it into the SQL Server database. It's not just a matter of copying an mdf file either. It will possibly differ from one hosting company to another, but typically, you need to create a backup of your existing database (a .bak file) and then restore that to the hosting company's SQL Server. You should ask them where you can find instructions on deploying your database into production.

Windows command prompt log to a file

First method

For Windows 7 and above users, Windows PowerShell give you this option. Users with windows version less than 7 can download PowerShell online and install it.

Steps:

  1. type PowerShell in search area and click on "Windows PowerShell"

  2. If you have a .bat (batch) file go to step 3 OR copy your commands to a file and save it with .bat extension (e.g. file.bat)

  3. run the .bat file with following command

    PS (location)> <path to bat file>/file.bat | Tee-Object -file log.txt

This will generate a log.txt file with all command prompt output in it. Advantage is that you can also the output on command prompt.

Second method

You can use file redirection (>, >>) as suggest by Bali C above.

I will recommend first method if you have lots of commands to run or a script to run. I will recommend last method if there is only few commands to run.

What is the size limit of a post request?

You can post large amount of data by setting php.ini variable: max_input_vars Default size of this variable is 1000 but if you want to sent large amount of data you have to increase the size accordingly. If you can't set the size from ini_set you have to do it through htaccess or by doing changes into php.ini file directly.

max_input_vars  2500
memory_limit    256M

Get WooCommerce product categories from WordPress

You could also use wp_list_categories();

wp_list_categories( array('taxonomy' => 'product_cat', 'title_li'  => '') );

Runtime vs. Compile time

It's not a good question for S.O. (it's not a specific programming question), but it's not a bad question in general.

If you think it's trivial: what about read-time vs compile-time, and when is this a useful distinction to make? What about languages where the compiler is available at runtime? Guy Steele (no dummy, he) wrote 7 pages in CLTL2 about EVAL-WHEN, which CL programmers can use to control this. 2 sentences are barely enough for a definition, which itself is far short of an explanation.

In general, it's a tough problem that language designers have seemed to try to avoid. They often just say "here's a compiler, it does compile-time things; everything after that is run-time, have fun". C is designed to be simple to implement, not the most flexible environment for computation. When you don't have the compiler available at runtime, or the ability to easily control when an expression is evaluated, you tend to end up with hacks in the language to fake common uses of macros, or users come up with Design Patterns to simulate having more powerful constructs. A simple-to-implement language can definitely be a worthwhile goal, but that doesn't mean it's the end-all-be-all of programming language design. (I don't use EVAL-WHEN much, but I can't imagine life without it.)

And the problemspace around compile-time and run-time is huge and still largely unexplored. That's not to say S.O. is the right place to have the discussion, but I encourage people to explore this territory further, especially those who have no preconceived notions of what it should be. The question is neither simple nor silly, and we could at least point the inquisitor in the right direction.

Unfortunately, I don't know any good references on this. CLTL2 talks about it a bit, but it's not great for learning about it.

CSS: Background image and padding

The only option to actuall have this made pixel perfect is to create some transparent padding within the GIF itself. That way you can actually align it to the right of the LI and still have the background padding you are looking for.

How to get resources directory path programmatically

I'm assuming the contents of src/main/resources/ is copied to WEB-INF/classes/ inside your .war at build time. If that is the case you can just do (substituting real values for the classname and the path being loaded).

URL sqlScriptUrl = MyServletContextListener.class
                       .getClassLoader().getResource("sql/script.sql");

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

Execute docker build -t getting-started . in your project directory and make sure Dockerfile is present and having no .txt extension. If you are on Windows, check the 'file name extension' in the under the view tab in the File Explorer to show whether .txt is there or not and remove it if the former is true. Good Luck.

How to hide the title bar for an Activity in XML with existing custom theme

You just need to change AppTheme style in Style.xml if you replace the definition from DarkActionBar

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

to NoActionBar

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

the AppTheme defined in AndroidManifast.xml

php delete a single file in directory

http://php.net/manual/en/function.unlink.php

Unlink can safely remove a single file; just make sure the file you are removing it actually a file and not a directory ('.' or '..')

if (is_file($filepath))
  {
    unlink($filepath);
  }

Loading state button in Bootstrap 3

You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.

$("button").click(function() {
    var $btn = $(this);
    $btn.button('loading');
    // simulating a timeout
    setTimeout(function () {
        $btn.button('reset');
    }, 1000);
});

Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.

JSFIDDLE

Official Documentation

java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty on Linux, or why is the default truststore empty

Not the answer to the original question but when trying to resolve a similar issue, I found that the Mac OS X update to Maverics screwed up the java install (the cacert actually). Remove sudo rm -rf /Library/Java/JavaVirtualMachines/*.jdk and reinstall from http://www.oracle.com/technetwork/java/javase/downloads/index.html

how to convert a string date to date format in oracle10g

You need to use the TO_DATE function.

SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;

Dynamically load JS inside JS

Necromancing.

I use this to load dependant scripts;
it works with IE8+ without adding any dependency on another library like jQuery !

var cScriptLoader = (function ()
{
    function cScriptLoader(files)
    {
        var _this = this;
        this.log = function (t)
        {
            console.log("ScriptLoader: " + t);
        };
        this.withNoCache = function (filename)
        {
            if (filename.indexOf("?") === -1)
                filename += "?no_cache=" + new Date().getTime();
            else
                filename += "&no_cache=" + new Date().getTime();
            return filename;
        };
        this.loadStyle = function (filename)
        {
            // HTMLLinkElement
            var link = document.createElement("link");
            link.rel = "stylesheet";
            link.type = "text/css";
            link.href = _this.withNoCache(filename);
            _this.log('Loading style ' + filename);
            link.onload = function ()
            {
                _this.log('Loaded style "' + filename + '".');
            };
            link.onerror = function ()
            {
                _this.log('Error loading style "' + filename + '".');
            };
            _this.m_head.appendChild(link);
        };
        this.loadScript = function (i)
        {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = _this.withNoCache(_this.m_js_files[i]);
            var loadNextScript = function ()
            {
                if (i + 1 < _this.m_js_files.length)
                {
                    _this.loadScript(i + 1);
                }
            };
            script.onload = function ()
            {
                _this.log('Loaded script "' + _this.m_js_files[i] + '".');
                loadNextScript();
            };
            script.onerror = function ()
            {
                _this.log('Error loading script "' + _this.m_js_files[i] + '".');
                loadNextScript();
            };
            _this.log('Loading script "' + _this.m_js_files[i] + '".');
            _this.m_head.appendChild(script);
        };
        this.loadFiles = function ()
        {
            // this.log(this.m_css_files);
            // this.log(this.m_js_files);
            for (var i = 0; i < _this.m_css_files.length; ++i)
                _this.loadStyle(_this.m_css_files[i]);
            _this.loadScript(0);
        };
        this.m_js_files = [];
        this.m_css_files = [];
        this.m_head = document.getElementsByTagName("head")[0];
        // this.m_head = document.head; // IE9+ only
        function endsWith(str, suffix)
        {
            if (str === null || suffix === null)
                return false;
            return str.indexOf(suffix, str.length - suffix.length) !== -1;
        }
        for (var i = 0; i < files.length; ++i)
        {
            if (endsWith(files[i], ".css"))
            {
                this.m_css_files.push(files[i]);
            }
            else if (endsWith(files[i], ".js"))
            {
                this.m_js_files.push(files[i]);
            }
            else
                this.log('Error unknown filetype "' + files[i] + '".');
        }
    }
    return cScriptLoader;
})();
var ScriptLoader = new cScriptLoader(["foo.css", "Scripts/Script4.js", "foobar.css", "Scripts/Script1.js", "Scripts/Script2.js", "Scripts/Script3.js"]);
ScriptLoader.loadFiles();

If you are interested in the typescript-version used to create this:

class cScriptLoader {
    private m_js_files: string[];
    private m_css_files: string[];
    private m_head:HTMLHeadElement;
    
    private log = (t:any) =>
    {
        console.log("ScriptLoader: " + t);
    }
    
    
    constructor(files: string[]) {
        this.m_js_files = [];
        this.m_css_files = [];
        this.m_head = document.getElementsByTagName("head")[0];
        // this.m_head = document.head; // IE9+ only
        
        
        function endsWith(str:string, suffix:string):boolean 
        {
            if(str === null || suffix === null)
                return false;
                
            return str.indexOf(suffix, str.length - suffix.length) !== -1;
        }
        
        
        for(let i:number = 0; i < files.length; ++i) 
        {
            if(endsWith(files[i], ".css"))
            {
                this.m_css_files.push(files[i]);
            }
            else if(endsWith(files[i], ".js"))
            {
                this.m_js_files.push(files[i]);
            }
            else
                this.log('Error unknown filetype "' + files[i] +'".');
        }
        
    }
    
    
    public withNoCache = (filename:string):string =>
    {
        if(filename.indexOf("?") === -1)
            filename += "?no_cache=" + new Date().getTime();
        else
            filename += "&no_cache=" + new Date().getTime();
            
        return filename;    
    }
    

    public loadStyle = (filename:string) =>
    {
        // HTMLLinkElement
        let link = document.createElement("link");
        link.rel = "stylesheet";
        link.type = "text/css";
        link.href = this.withNoCache(filename);
        
        this.log('Loading style ' + filename);
        link.onload = () =>
        {
            this.log('Loaded style "' + filename + '".');
            
        };
        
        link.onerror = () =>
        {
            this.log('Error loading style "' + filename + '".');
        };
        
        this.m_head.appendChild(link);
    }
    
    
    public loadScript = (i:number) => 
    {
        let script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = this.withNoCache(this.m_js_files[i]);
        
        var loadNextScript = () => 
        {
            if (i + 1 < this.m_js_files.length)
            {
                this.loadScript(i + 1);
            }
        }
        
        script.onload = () =>
        {
            this.log('Loaded script "' + this.m_js_files[i] + '".');
            loadNextScript();
        };
        
        
        script.onerror = () =>
        {
            this.log('Error loading script "' + this.m_js_files[i] + '".');
            loadNextScript();
        };
        
        
        this.log('Loading script "' + this.m_js_files[i] + '".');
        this.m_head.appendChild(script);
    }
    
    public loadFiles = () => 
    {
        // this.log(this.m_css_files);
        // this.log(this.m_js_files);
        
        for(let i:number = 0; i < this.m_css_files.length; ++i)
            this.loadStyle(this.m_css_files[i])
        
        this.loadScript(0);
    }
    
}


var ScriptLoader = new cScriptLoader(["foo.css", "Scripts/Script4.js", "foobar.css", "Scripts/Script1.js", "Scripts/Script2.js", "Scripts/Script3.js"]);
ScriptLoader.loadFiles();

If it's to load a dynamic list of scripts, write the scripts into an attribute, such as data-main, e.g. <script src="scriptloader.js" data-main="file1.js,file2.js,file3.js,etc." ></script>
and do a element.getAttribute("data-main").split(',')

such as

var target = document.currentScript || (function() {
  var scripts = document.getElementsByTagName('script');
  // Note: this is for IE as IE doesn't support currentScript
  // this does not work if you have deferred loading with async
  // e.g. <script src="..." async="async" ></script>
  // https://web.archive.org/web/20180618155601/https://www.w3schools.com/TAgs/att_script_async.asp
  return scripts[scripts.length - 1];
})();

target.getAttribute("data-main").split(',')

to obtain the list.

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

I believe this is the simplest example:

header := w.Header()
header.Add("Access-Control-Allow-Origin", "*")
header.Add("Access-Control-Allow-Methods", "DELETE, POST, GET, OPTIONS")
header.Add("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")

You can also add a header for Access-Control-Max-Age and of course you can allow any headers and methods that you wish.

Finally you want to respond to the initial request:

if r.Method == "OPTIONS" {
    w.WriteHeader(http.StatusOK)
    return
}

Edit (June 2019): We now use gorilla for this. Their stuff is more actively maintained and they have been doing this for a really long time. Leaving the link to the old one, just in case.

Old Middleware Recommendation below: Of course it would probably be easier to just use middleware for this. I don't think I've used it, but this one seems to come highly recommended.

Python: BeautifulSoup - get an attribute value based on the name attribute

The following works:

from bs4 import BeautifulSoup

soup = BeautifulSoup('<META NAME="City" content="Austin">', 'html.parser')

metas = soup.find_all("meta")

for meta in metas:
    print meta.attrs['content'], meta.attrs['name']

Strip HTML from strings in Python

Here's a solution similar to the currently accepted answer (https://stackoverflow.com/a/925630/95989), except that it uses the internal HTMLParser class directly (i.e. no subclassing), thereby making it significantly more terse:

def strip_html(text):
    parts = []                                                                      
    parser = HTMLParser()                                                           
    parser.handle_data = parts.append                                               
    parser.feed(text)                                                               
    return ''.join(parts)

Recommendations of Python REST (web services) framework?

In 2010, the Pylons and repoze.bfg communities "joined forces" to create Pyramid, a web framework based most heavily on repoze.bfg. It retains the philosophies of its parent frameworks, and can be used for RESTful services. It's worth a look.

What is href="#" and why is it used?

The problem with using href="#" for an empty link is that it will take you to the top of the page which may not be the desired action. To avoid this, for older browsers or non-HTML5 doctypes, use

<a href="javascript:void(0)">Goes Nowhere</a>

How to clean project cache in Intellij idea like Eclipse's clean?

If you are using Maven, run this command in your project directory

mvn clean package

Android Facebook integration with invalid key hash

try {
    PackageInfo info = getPackageManager().getPackageInfo(
                           "www.icognix.infomedia",
                           PackageManager.GET_SIGNATURES);
    for (Signature signature : info.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        Log.d("YourKeyHash: ", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        Log.d("YourKeyHash: ", Base64.encodeToString(md.digest(), Base64.DEFAULT));
    }
}
catch (PackageManager.NameNotFoundException e) {
}
catch (NoSuchAlgorithmException e) {
}

Close pre-existing figures in matplotlib when running from eclipse

Nothing works in my case using the scripts above but I was able to close these figures from eclipse console bar by clicking on Terminate ALL (two red nested squares icon).

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

If you need performance, then you must test on your environment. No other way.

Here example code:

int tmp = 0;
String s = new String(new byte[64*1024]);
{
    long st = System.nanoTime();
    for(int i = 0, n = s.length(); i < n; i++) {
        tmp += s.charAt(i);
    }
    st = System.nanoTime() - st;
    System.out.println("1 " + st);
}

{
    long st = System.nanoTime();
    char[] ch = s.toCharArray();
    for(int i = 0, n = ch.length; i < n; i++) {
        tmp += ch[i];
    }
    st = System.nanoTime() - st;
    System.out.println("2 " + st);
}
{
    long st = System.nanoTime();
    for(char c : s.toCharArray()) {
        tmp += c;
    }
    st = System.nanoTime() - st;
    System.out.println("3 " + st);
}
System.out.println("" + tmp);

On Java online I get:

1 10349420
2 526130
3 484200
0

On Android x86 API 17 I get:

1 9122107
2 13486911
3 12700778
0

jQuery - Check if DOM element already exists

Just to confirm that you are selecting the element in the right way. Try this one

if ($('#some_element').length == 0) {
    //Add it to the dom
}

How can I store and retrieve images from a MySQL database using PHP?

Beware that serving images from DB is usually much, much much slower than serving them from disk.

You'll be starting a PHP process, opening a DB connection, having the DB read image data from the same disk and RAM for cache as filesystem would, transferring it over few sockets and buffers and then pushing out via PHP, which by default makes it non-cacheable and adds overhead of chunked HTTP encoding.

OTOH modern web servers can serve images with just few optimized kernel calls (memory-mapped file and that memory area passed to TCP stack), so that they don't even copy memory around and there's almost no overhead.

That's a difference between being able to serve 20 or 2000 images in parallel on one machine.

So don't do it unless you absolutely need transactional integrity (and actually even that can be done with just image metadata in DB and filesystem cleanup routines) and know how to improve PHP's handling of HTTP to be suitable for images.

While variable is not defined - wait

I prefer something simple like this:

function waitFor(variable, callback) {
  var interval = setInterval(function() {
    if (window[variable]) {
      clearInterval(interval);
      callback();
    }
  }, 200);
}

And then to use it with your example variable of someVariable:

waitFor('someVariable', function() {
  // do something here now that someVariable is defined
});

Note that there are various tweaks you can do. In the above setInterval call, I've passed 200 as how often the interval function should run. There is also an inherent delay of that amount of time (~200ms) before the variable is checked for -- in some cases, it's nice to check for it right away so there is no delay.

Deleting a local branch with Git

This worked for me...
I have removed the folders there in .git/worktrees folder and then tried "git delete -D branch-name".

CSS horizontal scroll

Use this code to generate horizontal scrolling blocks contents. I got this from here http://www.htmlexplorer.com/2014/02/horizontal-scrolling-webpage-content.html

<html>
<title>HTMLExplorer Demo: Horizontal Scrolling Content</title>
<head>
<style type="text/css">
#outer_wrapper {  
    overflow: scroll;  
    width:100%;
}
#outer_wrapper #inner_wrapper {
    width:6000px; /* If you have more elements, increase the width accordingly */
}
#outer_wrapper #inner_wrapper div.box { /* Define the properties of inner block */
    width: 250px;
    height:300px;
    float: left;
    margin: 0 4px 0 0;
    border:1px grey solid;
}
</style>
</head>
<body>

<div id="outer_wrapper">
    <div id="inner_wrapper">
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
             <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
             <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <!-- more boxes here -->
    </div>
</div>
</body>
</html>

JQuery html() vs. innerHTML

Here is some code to get you started. You can modify the behavior of .innerHTML -- you could even create your own complete .innerHTML shim. (P.S.: redefining .innerHTML will also work in Firefox, but not Chrome -- they're working on it.)

if (/(msie|trident)/i.test(navigator.userAgent)) {
 var innerhtml_get = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").get
 var innerhtml_set = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").set
 Object.defineProperty(HTMLElement.prototype, "innerHTML", {
  get: function () {return innerhtml_get.call (this)},
  set: function(new_html) {
   var childNodes = this.childNodes
   for (var curlen = childNodes.length, i = curlen; i > 0; i--) {
    this.removeChild (childNodes[0])
   }
   innerhtml_set.call (this, new_html)
  }
 })
}

var mydiv = document.createElement ('div')
mydiv.innerHTML = "test"
document.body.appendChild (mydiv)

document.body.innerHTML = ""
console.log (mydiv.innerHTML)

http://jsfiddle.net/DLLbc/9/

How to POST request using RestSharp

it is better to use json after post your resuest like below

  var clien = new RestClient("https://smple.com/");
  var request = new RestRequest("index", Method.POST);
  request.AddHeader("Sign", signinstance);    
  request.AddJsonBody(JsonConvert.SerializeObject(yourclass));
  var response = client.Execute<YourReturnclassSample>(request);
  if (response.StatusCode == System.Net.HttpStatusCode.Created)
   {
       return Ok(response.Content);
   }

Excel VBA function to print an array to the workbook

A more elegant way is to assign the whole array at once:

Sub PrintArray(Data, SheetName, StartRow, StartCol)

    Dim Rng As Range

    With Sheets(SheetName)
        Set Rng = .Range(.Cells(StartRow, StartCol), _
            .Cells(UBound(Data, 1) - LBound(Data, 1) + StartRow, _
            UBound(Data, 2) - LBound(Data, 2) + StartCol))
    End With
    Rng.Value2 = Data

End Sub

But watch out: it only works up to a size of about 8,000 cells. Then Excel throws a strange error. The maximum size isn't fixed and differs very much from Excel installation to Excel installation.

Default interface methods are only supported starting with Android N

You can resolve this issue by downgrading Source Compatibility and Target Compatibility Java Version to 1.8 in Latest Android Studio Version 3.4.1

  1. Open Module Settings (Project Structure) Winodw by right clicking on app folder or Command + Down Arrow on Mac enter image description here

  2. Go to Modules -> Properties enter image description here

  3. Change Source Compatibility and Target Compatibility Version to 1.8 enter image description here

  4. Click on Apply or OK Thats it. It will solve your issue.

Also you can manually add in build.gradle (Module: app)

android {
...

compileOptions {
        sourceCompatibility = '1.8'
        targetCompatibility = '1.8'
    }

...
}

How to add extension methods to Enums

A Simple workaround.

public static class EnumExtensions
{
    public static int ToInt(this Enum payLoad) {

        return ( int ) ( IConvertible ) payLoad;

    }
}

int num = YourEnum.AItem.ToInt();
Console.WriteLine("num : ", num);

How to change background color in android app

You need to use the android:background property , eg

android:background="@color/white"

Also you need to add a value for white in the strings.xml

<color name="white">#FFFFFF</color>

Edit : 18th Nov 2012

The first two letters of an 8 letter color code provide the alpha value, if you are using the html 6 letter color notation the color is opaque.

Eg :

enter image description here

How do I use a PriorityQueue?

Java 8 solution

We can use lambda expression or method reference introduced in Java 8. In case we have some String values stored in the Priority Queue (having capacity 5) we can provide inline comparator (based on length of String) :

Using lambda expression

PriorityQueue<String> pq=
                    new PriorityQueue<String>(5,(a,b) -> a.length() - b.length());

Using Method reference

PriorityQueue<String> pq=
                new PriorityQueue<String>(5, Comparator.comparing(String::length));

Then we can use any of them as:

public static void main(String[] args) {
        PriorityQueue<String> pq=
                new PriorityQueue<String>(5, (a,b) -> a.length() - b.length());
       // or pq = new PriorityQueue<String>(5, Comparator.comparing(String::length));
        pq.add("Apple");
        pq.add("PineApple");
        pq.add("Custard Apple");
        while (pq.size() != 0)
        {
            System.out.println(pq.remove());
        }
    }

This will print:

Apple
PineApple
Custard Apple

To reverse the order (to change it to max-priority queue) simply change the order in inline comparator or use reversed as:

PriorityQueue<String> pq = new PriorityQueue<String>(5, 
                             Comparator.comparing(String::length).reversed());

We can also use Collections.reverseOrder:

PriorityQueue<Integer> pqInt = new PriorityQueue<>(10, Collections.reverseOrder());
PriorityQueue<String> pq = new PriorityQueue<String>(5, 
                Collections.reverseOrder(Comparator.comparing(String::length))

So we can see that Collections.reverseOrder is overloaded to take comparator which can be useful for custom objects. The reversed actually uses Collections.reverseOrder:

default Comparator<T> reversed() {
    return Collections.reverseOrder(this);
}

offer() vs add()

As per the doc

The offer method inserts an element if possible, otherwise returning false. This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues.

When using a capacity-restricted queue, offer() is generally preferable to add(), which can fail to insert an element only by throwing an exception. And PriorityQueue is an unbounded priority queue based on a priority heap.

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

This is due to the mismatch of the data type of your java Entity and the database table column. Please review if all the column is exact same data type as your entity. This mismatch happens when we update our model attribute's data-type.

How do I read CSV data into a record array in NumPy?

I timed the

from numpy import genfromtxt
genfromtxt(fname = dest_file, dtype = (<whatever options>))

versus

import csv
import numpy as np
with open(dest_file,'r') as dest_f:
    data_iter = csv.reader(dest_f,
                           delimiter = delimiter,
                           quotechar = '"')
    data = [data for data in data_iter]
data_array = np.asarray(data, dtype = <whatever options>)

on 4.6 million rows with about 70 columns and found that the NumPy path took 2 min 16 secs and the csv-list comprehension method took 13 seconds.

I would recommend the csv-list comprehension method as it is most likely relies on pre-compiled libraries and not the interpreter as much as NumPy. I suspect the pandas method would have similar interpreter overhead.

Showing line numbers in IPython/Jupyter Notebooks

In Jupyter Lab 2.1.5, it is View -> Show Line Numbers.

enter image description here

How to replace NaN value with zero in a huge data frame?

In fact, in R, this operation is very easy:

If the matrix 'a' contains some NaN, you just need to use the following code to replace it by 0:

a <- matrix(c(1, NaN, 2, NaN), ncol=2, nrow=2)
a[is.nan(a)] <- 0
a

If the data frame 'b' contains some NaN, you just need to use the following code to replace it by 0:

#for a data.frame: 
b <- data.frame(c1=c(1, NaN, 2), c2=c(NaN, 2, 7))
b[is.na(b)] <- 0
b

Note the difference is.nan when it's a matrix vs. is.na when it's a data frame.

Doing

#...
b[is.nan(b)] <- 0
#...

yields: Error in is.nan(b) : default method not implemented for type 'list' because b is a data frame.

Note: Edited for small but confusing typos

Show/Hide the console window of a C# console application

Why do you need a console application if you want to hide console itself? =)

I recommend setting Project Output type to Windows Application instead of Console application. It will not show you console window, but execute all actions, like Console application do.

How do I POST with multipart form data using fetch?

I was recently working with IPFS and worked this out. A curl example for IPFS to upload a file looks like this:

curl -i -H "Content-Type: multipart/form-data; boundary=CUSTOM" -d $'--CUSTOM\r\nContent-Type: multipart/octet-stream\r\nContent-Disposition: file; filename="test"\r\n\r\nHello World!\n--CUSTOM--' "http://localhost:5001/api/v0/add"

The basic idea is that each part (split by string in boundary with --) has it's own headers (Content-Type in the second part, for example.) The FormData object manages all this for you, so it's a better way to accomplish our goals.

This translates to fetch API like this:

const formData = new FormData()
formData.append('blob', new Blob(['Hello World!\n']), 'test')

fetch('http://localhost:5001/api/v0/add', {
  method: 'POST',
  body: formData
})
.then(r => r.json())
.then(data => {
  console.log(data)
})

MySQL Orderby a number, Nulls last

MySQL has an undocumented syntax to sort nulls last. Place a minus sign (-) before the column name and switch the ASC to DESC:

SELECT * FROM tablename WHERE visible=1 ORDER BY -position DESC, id DESC

It is essentially the inverse of position DESC placing the NULL values last but otherwise the same as position ASC.

A good reference is here http://troels.arvin.dk/db/rdbms#select-order_by

How to move columns in a MySQL table?

If empName is a VARCHAR(50) column:

ALTER TABLE Employees MODIFY COLUMN empName VARCHAR(50) AFTER department;

EDIT

Per the comments, you can also do this:

ALTER TABLE Employees CHANGE COLUMN empName empName VARCHAR(50) AFTER department;

Note that the repetition of empName is deliberate. You have to tell MySQL that you want to keep the same column name.

You should be aware that both syntax versions are specific to MySQL. They won't work, for example, in PostgreSQL or many other DBMSs.

Another edit: As pointed out by @Luis Rossi in a comment, you need to completely specify the altered column definition just before the AFTER modifier. The above examples just have VARCHAR(50), but if you need other characteristics (such as NOT NULL or a default value) you need to include those as well. Consult the docs on ALTER TABLE for more info.

How do you remove Subversion control for a folder?

Without subshells in Linux to delete .svn folders:

find . -name .svn -exec rm -r -f {} +

rm = remove
-r = recursive (folders)
-f = force, avoids a lot of "a your sure you want to delete file XY".

Finding modified date of a file/folder

You can try dirTimesJS.bat and fileTimesJS.bat

example:

C:\>dirTimesJS.bat %windir%

directory timestamps for C:\Windows :

Modified : 2020-11-22 22:12:55
Modified - milliseconds passed : 1604607175000
Modified day of the week : 4

Created : 2019-12-11 11:03:44
Created - milliseconds passed : 1575709424000
Created day of the week : 6

Accessed : 2020-11-16 16:39:22
Accessed - milliseconds passed : 1605019162000
Accessed day of the week : 2

C:\>fileTimesJS.bat %windir%\notepad.exe

file timestamps for C:\Windows\notepad.exe :

Modified : 2020-09-08 08:33:31
Modified - milliseconds passed : 1599629611000
Modified day of the week : 3

Created : 2020-09-08 08:33:31
Created - milliseconds passed : 1599629611000
Created day of the week : 3

Accessed : 2020-11-23 23:59:22
Accessed - milliseconds passed : 1604613562000
Accessed day of the week : 4

JavaScript string newline character?

I've just tested a few browsers using this silly bit of JavaScript:

_x000D_
_x000D_
function log_newline(msg, test_value) {_x000D_
  if (!test_value) { _x000D_
    test_value = document.getElementById('test').value;_x000D_
  }_x000D_
  console.log(msg + ': ' + (test_value.match(/\r/) ? 'CR' : '')_x000D_
              + ' ' + (test_value.match(/\n/) ? 'LF' : ''));_x000D_
}_x000D_
_x000D_
log_newline('HTML source');_x000D_
log_newline('JS string', "foo\nbar");_x000D_
log_newline('JS template literal', `bar_x000D_
baz`);
_x000D_
<textarea id="test" name="test">_x000D_
_x000D_
</textarea>
_x000D_
_x000D_
_x000D_

IE8 and Opera 9 on Windows use \r\n. All the other browsers I tested (Safari 4 and Firefox 3.5 on Windows, and Firefox 3.0 on Linux) use \n. They can all handle \n just fine when setting the value, though IE and Opera will convert that back to \r\n again internally. There's a SitePoint article with some more details called Line endings in Javascript.

Note also that this is independent of the actual line endings in the HTML file itself (both \n and \r\n give the same results).

When submitting a form, all browsers canonicalize newlines to %0D%0A in URL encoding. To see that, load e.g. data:text/html,<form><textarea name="foo">foo%0abar</textarea><input type="submit"></form> and press the submit button. (Some browsers block the load of the submitted page, but you can see the URL-encoded form values in the console.)

I don't think you really need to do much of any determining, though. If you just want to split the text on newlines, you could do something like this:

lines = foo.value.split(/\r\n|\r|\n/g);

What is android:ems attribute in Edit Text?

Taken from: http://www.w3.org/Style/Examples/007/units:

The em is simply the font size. In an element with a 2in font, 1em thus means 2in. Expressing sizes, such as margins and paddings, in em means they are related to the font size, and if the user has a big font (e.g., on a big screen) or a small font (e.g., on a handheld device), the sizes will be in proportion. Declarations such as 'text-indent: 1.5em' and 'margin: 1em' are extremely common in CSS.

em is basically CSS property for font sizes.

Getting file size in Python?

You may use os.stat() function, which is a wrapper of system call stat():

import os

def getSize(filename):
    st = os.stat(filename)
    return st.st_size

Is it possible to put a ConstraintLayout inside a ScrollView?

Set ScrollView layout_height as a wrap_content then it will work fine. Below are example which may help someone. I have used compile 'com.android.support.constraint:constraint-layout:1.0.2' for constraint layout.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    android:orientation="vertical"
    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:id="@+id/activity_main"
    tools:context=".ScrollViewActivity">

    <ScrollView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        >

        <android.support.constraint.ConstraintLayout 
            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="wrap_content"
            android:orientation="vertical"
            android:paddingLeft="8dp"
            android:paddingRight="8dp"
            android:scrollbars="vertical">

            <TextView
                android:id="@+id/tvCommonSurname"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="surname"
                android:textAppearance="?android:attr/textAppearanceLarge"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                tools:layout_constraintLeft_creator="1"
                tools:layout_constraintTop_creator="1" />

            <EditText
                android:id="@+id/editText3"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:ems="10"
                android:inputType="text"
                android:maxLines="1"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/tvCommonSurname"
                tools:layout_constraintLeft_creator="1"
                tools:layout_constraintRight_creator="1"
                tools:layout_constraintTop_creator="1" />

            <TextView
                android:id="@+id/tvCommonName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:text="firstName"
                android:textAppearance="?android:attr/textAppearanceLarge"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/editText3"
                tools:layout_constraintLeft_creator="1"
                tools:layout_constraintTop_creator="1" />

            <EditText
                android:id="@+id/editText"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:ems="10"
                android:inputType="text"
                android:maxLines="1"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/tvCommonName"
                tools:layout_constraintLeft_creator="1"
                tools:layout_constraintRight_creator="1"
                tools:layout_constraintTop_creator="1" />

            <TextView
                android:id="@+id/tvCommonLastName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:text="middleName"
                android:textAppearance="?android:attr/textAppearanceLarge"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/editText"
                tools:layout_constraintLeft_creator="1"
                tools:layout_constraintTop_creator="1" />

            <EditText
                android:id="@+id/editText2"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:ems="10"
                android:inputType="text"
                android:maxLines="1"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/tvCommonLastName"
                tools:layout_constraintLeft_creator="1"
                tools:layout_constraintRight_creator="1"
                tools:layout_constraintTop_creator="1" />

            <TextView
                android:id="@+id/tvCommonPhone"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:text="Phone number"
                android:textAppearance="?android:attr/textAppearanceLarge"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/editText2"
                tools:layout_constraintLeft_creator="1"
                tools:layout_constraintTop_creator="1" />

            <EditText
                android:id="@+id/editText4"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:digits="0123456789"
                android:ems="10"
                android:inputType="phone"
                android:maxLength="10"
                android:maxLines="1"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/tvCommonPhone"
                tools:layout_constraintLeft_creator="1"
                tools:layout_constraintRight_creator="1"
                tools:layout_constraintTop_creator="1" />

            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:text="sex"
                android:textAppearance="?android:attr/textAppearanceLarge"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/editText4"
                tools:layout_constraintLeft_creator="1"
                tools:layout_constraintTop_creator="1" />

            <RadioGroup 
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/radiogroup"
                android:layout_width="0dp"
                android:layout_height="48dp"
                android:layout_marginTop="8dp"
                android:orientation="horizontal"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView3"
                tools:layout_constraintLeft_creator="1"
                tools:layout_constraintTop_creator="1">

                <RadioButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="pirates" />

                <RadioButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="ninjas" />
            </RadioGroup>

            <TextView
                android:id="@+id/tvCommonDOB"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:text="dob"
                android:textAppearance="?android:attr/textAppearanceLarge"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/radiogroup"
                tools:layout_constraintLeft_creator="1"
                tools:layout_constraintTop_creator="1" />

            <EditText
                android:id="@+id/editText5"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:ems="10"
                android:inputType="date"
                android:maxLines="1"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/tvCommonDOB"
                tools:layout_constraintLeft_creator="1"
                tools:layout_constraintRight_creator="1"
                tools:layout_constraintTop_creator="1" />

            <TextView
                android:id="@+id/tvCommonLivingCity"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:text="livingCity"
                android:textAppearance="?android:attr/textAppearanceLarge"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/editText5"
                tools:layout_constraintLeft_creator="1"
                tools:layout_constraintTop_creator="1" />

            <EditText
                android:id="@+id/editText34"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:ems="10"
                android:inputType="text"
                android:maxLines="1"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/tvCommonLivingCity"
                tools:layout_constraintLeft_creator="1"
                tools:layout_constraintRight_creator="1"
                tools:layout_constraintTop_creator="1" />

            <TextView
                android:id="@+id/tvCommonPlaceOfBithday"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:text="placeOfBirth"
                android:textAppearance="?android:attr/textAppearanceLarge"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/editText34"
                tools:layout_constraintLeft_creator="1"
                tools:layout_constraintTop_creator="1" />

            <EditText
                android:id="@+id/editText6"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:ems="10"
                android:inputType="text"
                android:maxLines="1"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/tvCommonPlaceOfBithday"
                tools:layout_constraintLeft_creator="1"
                tools:layout_constraintRight_creator="1"
                tools:layout_constraintTop_creator="1" />

            <TextView
                android:id="@+id/textView4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:text="education"
                android:textAppearance="?android:attr/textAppearanceLarge"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/editText6"
                tools:layout_constraintLeft_creator="1"
                tools:layout_constraintTop_creator="1" />

            <Spinner
                android:id="@+id/spinner_id"
                android:layout_width="0dp"
                android:layout_height="48dp"
                android:layout_marginTop="8dp"
                android:spinnerMode="dialog"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView4"
                tools:layout_constraintLeft_creator="1"
                tools:layout_constraintRight_creator="1"
                tools:layout_constraintTop_creator="1" />

        </android.support.constraint.ConstraintLayout>
    </ScrollView>


</android.support.constraint.ConstraintLayout>

No server in windows>preferences

You did not install the correct Eclipse distribution. Try install the one labeled "Eclipse IDE for Java EE Developers".

How to convert string date to Timestamp in java?

Use capital HH to get hour of day format, instead of am/pm hours

How do I stretch a background image to cover the entire HTML element?

The following code I use mostly for achieving the asked effect:

body {
    background-image: url('../images/bg.jpg');
    background-repeat: no-repeat;
    background-size: 100%;
}

How do I declare and assign a variable on a single line in SQL

You've nearly got it:

DECLARE @myVariable nvarchar(max) = 'hello world';

See here for the docs

For the quotes, SQL Server uses apostrophes, not quotes:

DECLARE @myVariable nvarchar(max) = 'John said to Emily "Hey there Emily"';

Use double apostrophes if you need them in a string:

DECLARE @myVariable nvarchar(max) = 'John said to Emily ''Hey there Emily''';

jquery .html() vs .append()

.html() will replace everything.

.append() will just append at the end.

Can we install Android OS on any Windows Phone and vice versa, and same with iPhone and vice versa?

Ok, For installing Android on Windows phone, I think you can..(But your window phone has required configuration to run Android) (For other I don't know If I will then surely post here)

Just go through these links,

Run Android on Your Windows Mobile Phone

full tutorial on how to put android on windows mobile touch pro 2

How to install Android on most Windows Mobile phones

Update:

For Windows 7 to Android device, this also possible, (You need to do some hack for this)

Just go through these links,

Install Windows Phone 7 Mango on HTC HD2 [How-To Guide]

HTC HD2: How To Install WP7 (Windows Phone 7) & MAGLDR 1.13 To NAND

Install windows phone 7 on android and iphones | Tips and Tricks

How to install Windows Phone 7 on HTC HD2? (Video)


To Install Android on your iOS Devices (This also possible...)

Look at How To Install Android on your iOS Devices

Android 2.2 Froyo running on Iphone

What is the difference between an interface and abstract class?

An Interface contains only the definition / signature of functionality, and if we have some common functionality as well as common signatures, then we need to use an abstract class. By using an abstract class, we can provide behavior as well as functionality both in the same time. Another developer inheriting abstract class can use this functionality easily, as they would only need to fill in the blanks.

enter image description here Taken from:

http://www.dotnetbull.com/2011/11/difference-between-abstract-class-and.html

http://www.dotnetbull.com/2011/11/what-is-abstract-class-in-c-net.html http://www.dotnetbull.com/2011/11/what-is-interface-in-c-net.html

Sheet.getRange(1,1,1,12) what does the numbers in bracket specify?

Found these docu on the google docu pages:

  • row --- int --- top row of the range
  • column --- int--- leftmost column of the range
  • optNumRows --- int --- number of rows in the range.
  • optNumColumns --- int --- number of columns in the range

In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns

edit

Using the example on the docu:

// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);

The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G

So you come to the range: C2:G8

Parsing domain from a URL

This will generally work very well if the input URL is not total junk. It removes the subdomain.

$host = parse_url( $Row->url, PHP_URL_HOST );
$parts = explode( '.', $host );
$parts = array_reverse( $parts );
$domain = $parts[1].'.'.$parts[0];

Example

Input: http://www2.website.com:8080/some/file/structure?some=parameters

Output: website.com

Why and how to fix? IIS Express "The specified port is in use"

For me netstat did the trick to show me that I had Fiddler running which was keeping the port open.

PHP Composer update "cannot allocate memory" error (using Laravel 4)

Make a swap and run composer command again. I hope it'll work for you.

 $ dd if=/dev/zero of=/swapfile bs=1024 count=512k
 $ mkswap /swapfile
 $ swapon /swapfile
 $ echo "/swapfile       none    swap    sw      0       0 " >> /etc/fstab
 $ echo 0 > /proc/sys/vm/swappiness
 $ chown root:root /swapfile
 $ chmod 0600 /swapfile

Do I cast the result of malloc?

People used to GCC and Clang are spoiled. It's not all that good out there.

I have been pretty horrified over the years by the staggeringly aged compilers I've been required to use. Often companies and managers adopt an ultra-conservative approach to changing compilers and will not even test if a new compiler ( with better standards compliance and code optimization ) will work in their system. The practical reality for working developers is that when you're coding you need to cover your bases and, unfortunately, casting mallocs is a good habit if you cannot control what compiler may be applied to your code.

I would also suggest that many organizations apply a coding standard of their own and that that should be the method people follow if it is defined. In the absence of explicit guidance I tend to go for most likely to compile everywhere, rather than slavish adherence to a standard.

The argument that it's not necessary under current standards is quite valid. But that argument omits the practicalities of the real world. We do not code in a world ruled exclusively by the standard of the day, but by the practicalities of what I like to call "local management's reality field". And that's bent and twisted more than space time ever was. :-)

YMMV.

I tend to think of casting malloc as a defensive operation. Not pretty, not perfect, but generally safe. ( Honestly, if you've not included stdlib.h then you've way more problems than casting malloc ! ).

Get AVG ignoring Null or Zero values

In Case of not considering '0' or 'NULL' in average function. Simply use

AVG(NULLIF(your_column_name,0))

how to split the ng-repeat data with three columns using bootstrap

This example produces a nested repeater where the outer data includes an inner array which I wanted to list in two column. The concept would hold true for three or more columns.

In the inner column I repeat the "row" until the limit is reached. The limit is determined by dividing the length of the array of items by the number of columns desired, in this case by two. The division method sits on the controller and is passed the current array length as a parameter. The JavaScript slice(0, array.length / columnCount) function then applied the limit to the repeater.

The second column repeater is then invoked and repeats slice( array.length / columnCount, array.length) which produces the second half of the array in column two.

<div class="row" ng-repeat="GroupAccess in UsersController.SelectedUser.Access" ng-class="{even: $even, odd: $odd}">
    <div class="col-md-12 col-xs-12" style=" padding-left:15px;">
        <label style="margin-bottom:2px;"><input type="checkbox" ng-model="GroupAccess.isset" />{{GroupAccess.groupname}}</label>
    </div>
    <div class="row" style=" padding-left:15px;">
        <div class="col-md-1 col-xs-0"></div>
        <div class="col-md-3 col-xs-2">
            <div style="line-height:11px; margin-left:2px; margin-bottom:2px;" ng-repeat="Feature in GroupAccess.features.slice(0, state.DivideBy2(GroupAccess.features.length))">
                <span class="GrpFeature">{{Feature.featurename}}</span>
            </div>
        </div>
        <div class="col-md-3 col-xs-2">
            <div style="line-height:11px; margin-left:2px; margin-bottom:2px;" ng-repeat="Feature in GroupAccess.features.slice( state.DivideBy2(GroupAccess.features.length), GroupAccess.features.length )">
                <span class="GrpFeature">{{Feature.featurename}}</span>
            </div>
        </div>
        <div class="col-md-5 col-xs-8">
        </div>
    </div>
</div>


// called to format two columns
state.DivideBy2 = function(nValue) {
    return Math.ceil(nValue /2);
};

Hope this helps to look at the solution in yet another way. (PS this is my first post here! :-))

How do I use the Simple HTTP client in Android?

You can use like this:

public static String executeHttpPost1(String url,
            HashMap<String, String> postParameters) throws UnsupportedEncodingException {
        // TODO Auto-generated method stub

        HttpClient client = getNewHttpClient();

        try{
        request = new HttpPost(url);

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


        if(postParameters!=null && postParameters.isEmpty()==false){

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(postParameters.size());
            String k, v;
            Iterator<String> itKeys = postParameters.keySet().iterator();
            while (itKeys.hasNext()) 
            {
                k = itKeys.next();
                v = postParameters.get(k);
                nameValuePairs.add(new BasicNameValuePair(k, v));
            }     

            UrlEncodedFormEntity urlEntity  = new  UrlEncodedFormEntity(nameValuePairs);
            request.setEntity(urlEntity);

        }
        try {


            Response = client.execute(request,localContext);
            HttpEntity entity = Response.getEntity();
            int statusCode = Response.getStatusLine().getStatusCode();
            Log.i(TAG, ""+statusCode);


            Log.i(TAG, "------------------------------------------------");





                try{
                    InputStream in = (InputStream) entity.getContent(); 
                    //Header contentEncoding = Response.getFirstHeader("Content-Encoding");
                    /*if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                        in = new GZIPInputStream(in);
                    }*/
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder str = new StringBuilder();
                    String line = null;
                    while((line = reader.readLine()) != null){
                        str.append(line + "\n");
                    }
                    in.close();
                    response = str.toString();
                    Log.i(TAG, "response"+response);
                }
                catch(IllegalStateException exc){

                    exc.printStackTrace();
                }


        } catch(Exception e){

            Log.e("log_tag", "Error in http connection "+response);         

        }
        finally {

        }

        return response;
    }

Setting width to wrap_content for TextView through code

There is another way to achieve same result. In case you need to set only one parameter, for example 'height':

TextView textView = (TextView)findViewById(R.id.text_view);
ViewGroup.LayoutParams params = textView.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(params);

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

I didn't get System.Web.Mvc in VS 2012 but I got it in VS 2013. Using AddReference Dialog, enter image description here

Or, You can find this in your project path,

YourProjectName\packages\Microsoft.AspNet.Mvc.5.0.0\lib\net45\System.Web.Mvc.dll

could not extract ResultSet in hibernate

I faced the same problem after migrating a database from online server to localhost. The schema changed so I had to define the schema manually for each table:

@Entity
@Table(name = "ESBCORE_DOMAIN", schema = "SYS")

Bootstrap 3 - jumbotron background image effect

Example: http://bootply.com/103783

One way to achieve this is using a position:fixed container for the background image and place it outside of the .jumbotron. Make the bg container the same height as the .jumbotron and center the background image:

background: url('/assets/example/...jpg') no-repeat center center;

CSS

.bg {
  background: url('/assets/example/bg_blueplane.jpg') no-repeat center center;
  position: fixed;
  width: 100%;
  height: 350px; /*same height as jumbotron */
  top:0;
  left:0;
  z-index: -1;
}

.jumbotron {
  margin-bottom: 0px;
  height: 350px;
  color: white;
  text-shadow: black 0.3em 0.3em 0.3em;
  background:transparent;
}

Then use jQuery to decrease the height of the .jumbtron as the window scrolls. Since the background image is centered in the DIV it will adjust accordingly -- creating a parallax affect.

JavaScript

var jumboHeight = $('.jumbotron').outerHeight();
function parallax(){
    var scrolled = $(window).scrollTop();
    $('.bg').css('height', (jumboHeight-scrolled) + 'px');
}

$(window).scroll(function(e){
    parallax();
});

Demo

http://bootply.com/103783

Using curl to upload POST data with files

The issue that lead me here turned out to be a basic user error - I wasn't including the @ sign in the path of the file and so curl was posting the path/name of the file rather than the contents. The Content-Length value was therefore 8 rather than the 479 I expected to see given the legnth of my test file.

The Content-Length header will be automatically calculated when curl reads and posts the file.

curl -i -H "Content-Type: application/xml" --data "@test.xml" -v -X POST https://<url>/<uri/

... < Content-Length: 479 ...

Posting this here to assist other newbies in future.

Get the Highlighted/Selected text

Getting the text the user has selected is relatively simple. There's no benefit to be gained by involving jQuery since you need nothing other than the window and document objects.

function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}

If you're interested in an implementation that will also deal with selections in <textarea> and texty <input> elements, you could use the following. Since it's now 2016 I'm omitting the code required for IE <= 8 support but I've posted stuff for that in many places on SO.

_x000D_
_x000D_
function getSelectionText() {_x000D_
    var text = "";_x000D_
    var activeEl = document.activeElement;_x000D_
    var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;_x000D_
    if (_x000D_
      (activeElTagName == "textarea") || (activeElTagName == "input" &&_x000D_
      /^(?:text|search|password|tel|url)$/i.test(activeEl.type)) &&_x000D_
      (typeof activeEl.selectionStart == "number")_x000D_
    ) {_x000D_
        text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);_x000D_
    } else if (window.getSelection) {_x000D_
        text = window.getSelection().toString();_x000D_
    }_x000D_
    return text;_x000D_
}_x000D_
_x000D_
document.onmouseup = document.onkeyup = document.onselectionchange = function() {_x000D_
  document.getElementById("sel").value = getSelectionText();_x000D_
};
_x000D_
Selection:_x000D_
<br>_x000D_
<textarea id="sel" rows="3" cols="50"></textarea>_x000D_
<p>Please select some text.</p>_x000D_
<input value="Some text in a text input">_x000D_
<br>_x000D_
<input type="search" value="Some text in a search input">_x000D_
<br>_x000D_
<input type="tel" value="4872349749823">_x000D_
<br>_x000D_
<textarea>Some text in a textarea</textarea>
_x000D_
_x000D_
_x000D_

How exactly does <script defer="defer"> work?

The defer attribute is a boolean attribute.

When present, it specifies that the script is executed when the page has finished parsing.

Note: The defer attribute is only for external scripts (should only be used if the src attribute is present).

Note: There are several ways an external script can be executed:

If async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing) If async is not present and defer is present: The script is executed when the page has finished parsing If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page

SQL Server - INNER JOIN WITH DISTINCT

select distinct a.FirstName, a.LastName, v.District from AddTbl a inner join ValTbl v on a.LastName = v.LastName order by a.FirstName;

hope this helps

How to create a jQuery plugin with methods?

Following is a small plug-in to have warning method for debugging purpose. Keep this code in jquery.debug.js file: JS:

jQuery.fn.warning = function() {
   return this.each(function() {
      alert('Tag Name:"' + $(this).prop("tagName") + '".');
   });
};

HTML:

<html>
   <head>
      <title>The jQuery Example</title>

      <script type = "text/javascript" 
         src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

      <script src = "jquery.debug.js" type = "text/javascript"></script>

      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("div").warning();
            $("p").warning();
         });
      </script> 
   </head>

   <body>
      <p>This is paragraph</p>
      <div>This is division</div>
   </body>

</html>

Getting time difference between two times in PHP

<?php
$start = strtotime("12:00");
$end = // Run query to get datetime value from db
$elapsed = $end - $start;
echo date("H:i", $elapsed);
?>

ReCaptcha API v2 Styling

In case someone struggling with the recaptcha of contact form 7 (wordpress) here is a solution working for me

.wpcf7-recaptcha{
clear: both;
float: left;
}
.wpcf7-recaptcha{
margin-right: 6px;
width: 206px;
height: 65px;
overflow: hidden;
border-right: 1px solid #D3D3D3;
}
.wpcf7-recaptcha iframe{
padding-bottom: 15px;
border-bottom: 1px solid #D3D3D3;
background: #F9F9F9;
border-left: 1px solid #d3d3d3;
}

enter image description here

Angular 2: Get Values of Multiple Checked Checkboxes

Here's a simple way using ngModel (final Angular 2)

<!-- my.component.html -->

<div class="form-group">
    <label for="options">Options:</label>
    <div *ngFor="let option of options">
        <label>
            <input type="checkbox"
                   name="options"
                   value="{{option.value}}"
                   [(ngModel)]="option.checked"/>
            {{option.name}}
        </label>
    </div>
</div>

// my.component.ts

@Component({ moduleId:module.id, templateUrl:'my.component.html'})

export class MyComponent {
  options = [
    {name:'OptionA', value:'1', checked:true},
    {name:'OptionB', value:'2', checked:false},
    {name:'OptionC', value:'3', checked:true}
  ]

  get selectedOptions() { // right now: ['1','3']
    return this.options
              .filter(opt => opt.checked)
              .map(opt => opt.value)
  }
}

Android AudioRecord example

Here I am posting you the some code example which record good quality of sound using AudioRecord API.

Note: If you use in emulator the sound quality will not much good because we are using sample rate 8k which only supports in emulator. In device use sample rate to 44.1k for better quality.

public class Audio_Record extends Activity {
    private static final int RECORDER_SAMPLERATE = 8000;
    private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
    private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
    private AudioRecord recorder = null;
    private Thread recordingThread = null;
    private boolean isRecording = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        setButtonHandlers();
        enableButtons(false);

        int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
                RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING); 
    }

    private void setButtonHandlers() {
        ((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
        ((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
    }

    private void enableButton(int id, boolean isEnable) {
        ((Button) findViewById(id)).setEnabled(isEnable);
    }

    private void enableButtons(boolean isRecording) {
        enableButton(R.id.btnStart, !isRecording);
        enableButton(R.id.btnStop, isRecording);
    }

    int BufferElements2Rec = 1024; // want to play 2048 (2K) since 2 bytes we use only 1024
    int BytesPerElement = 2; // 2 bytes in 16bit format

    private void startRecording() {

        recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
                RECORDER_SAMPLERATE, RECORDER_CHANNELS,
                RECORDER_AUDIO_ENCODING, BufferElements2Rec * BytesPerElement);

        recorder.startRecording();
        isRecording = true;
        recordingThread = new Thread(new Runnable() {
            public void run() {
                writeAudioDataToFile();
            }
        }, "AudioRecorder Thread");
        recordingThread.start();
    }

        //convert short to byte
    private byte[] short2byte(short[] sData) {
        int shortArrsize = sData.length;
        byte[] bytes = new byte[shortArrsize * 2];
        for (int i = 0; i < shortArrsize; i++) {
            bytes[i * 2] = (byte) (sData[i] & 0x00FF);
            bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
            sData[i] = 0;
        }
        return bytes;

    }

    private void writeAudioDataToFile() {
        // Write the output audio in byte

        String filePath = "/sdcard/voice8K16bitmono.pcm";
        short sData[] = new short[BufferElements2Rec];

        FileOutputStream os = null;
        try {
            os = new FileOutputStream(filePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        while (isRecording) {
            // gets the voice output from microphone to byte format

            recorder.read(sData, 0, BufferElements2Rec);
            System.out.println("Short writing to file" + sData.toString());
            try {
                // // writes the data to file from buffer
                // // stores the voice buffer
                byte bData[] = short2byte(sData);
                os.write(bData, 0, BufferElements2Rec * BytesPerElement);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void stopRecording() {
        // stops the recording activity
        if (null != recorder) {
            isRecording = false;
            recorder.stop();
            recorder.release();
            recorder = null;
            recordingThread = null;
        }
    }

    private View.OnClickListener btnClick = new View.OnClickListener() {
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.btnStart: {
                enableButtons(true);
                startRecording();
                break;
            }
            case R.id.btnStop: {
                enableButtons(false);
                stopRecording();
                break;
            }
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}

For more detail try this AUDIORECORD BLOG.

Happy Coding !!

jQuery - Illegal invocation

I think you need to have strings as the data values. It's likely something internally within jQuery that isn't encoding/serializing correctly the To & From Objects.

Try:

var data = {
    from : from.val(),
    to : to.val(),
    speed : speed
};

Notice also on the lines:

$(from).css(...
$(to).css(

You don't need the jQuery wrapper as To & From are already jQuery objects.

How can I get the day of a specific date with PHP

$datetime = DateTime::createFromFormat('Ymd', '20151102');

echo $datetime->format('D');

How to preview git-pull without doing fetch?

You can fetch from a remote repo, see the differences and then pull or merge.

This is an example for a remote repo called origin and a branch called master tracking the remote branch origin/master:

git checkout master                                                  
git fetch                                        
git diff origin/master
git pull --rebase origin master

What is the (function() { } )() construct in JavaScript?

This function is called self-invoking function. A self-invoking (also called self-executing) function is a nameless (anonymous) function that is invoked(Called) immediately after its definition. Read more here

What these functions do is that when the function is defined, The function is immediately called, which saves time and extra lines of code(as compared to calling it on a seperate line).

Here is an example:

_x000D_
_x000D_
(function() {_x000D_
    var x = 5 + 4;_x000D_
    console.log(x);_x000D_
})();
_x000D_
_x000D_
_x000D_

Oracle select most recent date record

you can't use aliases from select list inside the WHERE clause (because of the Order of Evaluation of a SELECT statement)

also you cannot use OVER clause inside WHERE clause - "You can specify analytic functions with this clause in the select list or ORDER BY clause." (citation from docs.oracle.com)

select *
from (select
  staff_id, site_id, pay_level, date, 
  max(date) over (partition by staff_id) max_date
  from owner.table
  where end_enrollment_date is null
)
where date = max_date

Dynamic height for DIV

set height: auto; If you want to have minimum height to x then you can write

height:auto;
min-height:30px;
height:auto !important;        /* for IE as it does not support min-height */
height:30px;                   /* for IE as it does not support min-height */

How to change the spinner background in Android?

You can set the spinners background color in xml like this:

android:background="YOUR_HEX_COLOR_CODE"

and if you use the drop down menu with you spinner you can set its background color like this:

android:popupBackground="YOUR_HEX_COLOR_CODE"

Break statement in javascript array map method

That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});

'sudo gem install' or 'gem install' and gem locations

In case you

  • installed ruby gems with sudo
  • want to install gems without sudo
  • don't want to install rvm/rbenv

add the following to your .bash_profile :

export GEM_HOME=/Users/‹your_user›/.gem
export PATH="$GEM_HOME/bin:$PATH"

Open a new tab in Terminal OR source ~/.bash_profile and you're good to go!

base64 encoded images in email signatures

The image should be embedded in the message as an attachment like this:

--boundary
Content-Type: image/png; name="sig.png"
Content-Disposition: inline; filename="sig.png"
Content-Transfer-Encoding: base64
Content-ID: <0123456789>
Content-Location: sig.png

base64 data

--boundary

And, the HTML part would reference the image like this:

<img src="cid:0123456789">

In some clients, src="sig.png" will work too.

You'd basically have a multipart/mixed, multipart/alternative, multipart/related message where the image attachment is in the related part.

Clients shouldn't block this image either as it isn't remote.

Or, here's a multipart/alternative, multipart/related example as an mbox file (save as windows newline format and put a blank line at the end. And, use no extension or the .mbs extension):

From 
From: [email protected]
To: [email protected]
Subject: HTML Messages with Embedded Pic in Signature
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="alternative_boundary"

This is a message with multiple parts in MIME format.

--alternative_boundary
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 8bit

test

-- 
[Picture of a Christmas Tree]

--alternative_boundary
Content-Type: multipart/related; boundary="related_boundary"

--related_boundary
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 8bit

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <p>test</p>
        <p class="sig">-- <br><img src="cid:0123456789"></p>
    </body>
</html>

--related_boundary
Content-Type: image/png; name="sig.png"
Content-Disposition: inline; filename="sig.png"
Content-Location: sig.png
Content-ID: <0123456789>
Content-Transfer-Encoding: base64

R0lGODlhKAA8AIMLAAD//wAhAABKAABrAACUAAC1AADeAAD/AGsAAP8zM///AP//
///M//////+ZAMwAACH/C05FVFNDQVBFMi4wAwGgDwAh+QQJFAALACwAAAAAKAA8
AAME+3DJSWt1Nuu9Mf+g5IzK6IXopaxn6orlKy/jMc6vQRy4GySABK+HAiaIoQdg
uUSCBAKAYTBwbgyGA2AgsGqo0wMh7K0YEuj0sUxRoAfqB1vycBN21Ki8vOofBndR
c1AKgH8ETE1lBgo7O2JaU2UFAgRoDGoAXV4PD2qYagl7Vp0JDKenfwado0QCAQOQ
DIcDBgIFVgYBAlOxswR5r1VIUbCHwH8HlQWFRLYABVOWamACCkiJAAehaX0rPZ1B
oQSg3Z04AuFqB2IMd+atLwUBtpAHqKdUtbwGM1BTOgA5YhBr374ZAxhAqRVLzA53
OwTEAjhDIZYs09aBASYq+94HfAq3cRt57sWDct2EvEsTpBMVF6sYeEpDQIFDdo62
BHwZApjEhjW94RyQTWK/FPx+Ahpg09GdOzoJ/ESx0JaOQ42e2tsiEYpCEFwAGi04
8g6gSgNOovD0gBeVjCPR2BIAkgOrmSNxPo3rbhgHZiMFPnLkBg2BAuQ2XdmlwK1Z
ooZu1sRz6xWlxd4U9GIHwOmdzFgCFKCERYNoeo2BZsPp0KY+A/OAfZDYWKJZLZBo
1mQXdlojvxNYiXrD8I+2uEvTdFJQksID0XjXiUwjJm6CzBVeBQgwBop1ZPpC8RKt
YN5RCpS6XiyMht093o8KcFFf/vKE0dCmaLeWYhQMwbeQaHLRfNk9o5Q13lQGklFQ
aMLFRLcwcN5qSWmGxS2jKQQFL9nEAgxsDEiwlAHaPPJWIfroo6FVEun0VkL4UABA
CAjUiIAFM2YQogzcoLCjC3HNsYB1aSBB5JFrZBABACH5BAkUAAsALAAAAAAoADwA
AwT7cMlJa3U2670x/6DkjKQXnleJrqnJruMxvq8xHDQbJEyC5yheAnh6MI5HYkgg
YNgGSo7BcGAMBNHNYGA7ELpZiyFBLg/DFvLArEBPHoAEgXDYChQP90IAoNYJCoGB
aACFhX8HBwoGegYAdHReijZoBXxmPWRYYQ8PZmSZZHmcnqBITp2jSgIBN5BVBFwC
BVkGAQJPiVV2rFCrCq1/sXUHAgQFAL45BncFNgSfW8wASoKBB59lhoVAnQqfDNCf
AJ05At5msHPiCeSqLwUBzF6nVnXSuIwvTDYGsXPhiMmSRUOWAC436HmZU+yGDQYF
81FhV+aevzUM3oHoZBD7W7Zs9VaUIhOn4pwE38p0srLCQCqSciBFUuBFGgEryj7E
Ojhg2yOG1hQMIMCEy4p8PB8llKmAIReiW040keUvmUygiexcwbWJwxUrzBDW+Thn
qLEB5UDUe0LxYwJmAhKk+pAqVLZE69qWGZpTQwG7ZISuw7uwzDFAXTXYYoJraKym
Q/HSASDpiiUFljbYitfYRtCF635yMRBUn4UA8aYclCw0shefW7gUgPxBKGPHA5pK
MpwsKy5AcmNZSIVHjdjI2eLwVZlK44IHQT8lkq7XTDznrAIEWMTErZwbsT/hQj1L
noXLV6YwS5eIJqIDf4tyLZB5Av1ZNrLzQSplrXVkOgxItBU1E+DCwC2xFZUME5dZ
c5AB9aw2jXkSQLhFIrj4xAx9szGWzwABdkGATwuAeEokW4wY24oK8MMViAjxxcc8
E0CUAYETIKAjAifgWGMI2ehBgVtCeleGEkYmeUYGEQAAIfkECRQACwAsAAAAACgA
PAADBPtwyUlrdTbrvTH/oOSMpBeeV4muqcmu4zG+r6EcNBskSoLnJ4VQCAw9ErzE
oxgSCBSGwYDJMRgOhIGAupFGsVEG12JAmpHicaU3QDPe6fHjoSAQDlIBY6leDIUD
dnp9C04DdXh3eAaEUTeKdwJRagUCBGdnW3JHmJh8XHNmWAeLDwCfRQIBA6MMiQMG
AgBcBgGSUgeuWQMAvb1MAgWruXAMrJYAUkU2wVGXDGZeAIxMCgVfaJhOVkB/PWeX
nXM5AnScSKR2dmZzqCwFUAKjo1l4XpLULNuwWXYHAHgWCYD15AXBgV+wEACg7sDA
A45oaLFy5ZKvXvYMEPCGYvvOwQOYAHRCQufFuU7/wp2Zo2AKCgPtwN3xR8/LLpcg
kg1khaVlQyw8GRAwlC8nvp2HeM5UR8CYxp05L8ay8YcplmLGtmniwCtKLFhJR9oR
amnAuBAiH9wK9G1kAgaxBCg5u6HdSUzp1LlNCqJAgZGBaC41Q6DAUAUfajm5ZUdK
v7z08ATjmKGWAltecaVTqE5oFisB/EIpSiH06IcKpQTa3JSVagPCWm7wZsgOwJkg
3xaTrJFkFgvtFHDywmt1J2iB2pC0C9x0yItnsLx1K8xdoQDYCcQ9I5KwaynaalUS
RnpBpYH4YiXoTipgIlIFtLSUFKwSBb/NtGCnb2Zl51fHo8hnhRZbSfCEKkgZkkcw
TgBgyVdxeQNRMNNMoMBOpBxFUSx+ObgYPgS1BBRss/jxxzwAqsbLRfwh1VJyF5WI
2AkIAIAAAiiUKMGMICDRXQIn6IiCW4Qs4NYZTByppBkbRAAAIf4ZQm95J3MgSGFw
cHkgSG9saWRheXMgUGFnZQA7

--related_boundary--

--alternative_boundary--

You can import that into Sylpheed or Thunderbird (with the Import/Export tools extension) or Opera's built-in mail client. Then, in Opera for example, you can toggle "prefer plain text" to see the difference between the HTML and text version. Anyway, you'll see the HTML version makes use of the embedded pic in the sig.

Refresh image with a new one at the same url

<img src='someurl.com/someimage.ext' onload='imageRefresh(this, 1000);'>

Then below in some javascript

<script language='javascript'>
 function imageRefresh(img, timeout) {
    setTimeout(function() {
     var d = new Date;
     var http = img.src;
     if (http.indexOf("&d=") != -1) { http = http.split("&d=")[0]; } 

     img.src = http + '&d=' + d.getTime();
    }, timeout);
  }
</script>

And so what this does is, when the image loads, schedules it to be reloaded in 1 second. I'm using this on a page with home security cameras of varying type.

Get first element from a dictionary

ill find easy way to find first element in Dictionary :)

 Dictionary<string, Dictionary<string, string>> like = 
 newDictionary<string,Dictionary<string, string>>();

 foreach(KeyValuePair<string, Dictionary<string, string>> _element in like)
 {
   Console.WriteLine(_element.Key); // or do something
   break;
 }

How is OAuth 2 different from OAuth 1?

Note there are serious security arguments against using Oauth 2:

one bleak article

and a more technical one

Note these are coming from Oauth 2's lead author.

Key points:

  • Oauth 2 offers no security on top of SSL while Oauth 1 is transport-independent.

  • in a sense SSL isn't secure in that the server does not verify the connection and the common client libraries make it easy to ignore failures.

    The problem with SSL/TLS, is that when you fail to verify the certificate on the client side, the connection still works. Any time ignoring an error leads to success, developers are going to do just that. The server has no way of enforcing certificate verification, and even if it could, an attacker will surely not.

  • you can fat-finger away all of your security, which is much harder to do in OAuth 1.0:

    The second common potential problem are typos. Would you consider it a proper design when omitting one character (the ‘s’ in ‘https’) voids the entire security of the token? Or perhaps sending the request (over a valid and verified SSL/TLS connection) to the wrong destination (say ‘http://gacebook.com’?). Remember, being able to use OAuth bearer tokens from the command line was clearly a use case bearer tokens advocates promoted.

cmd line rename file with date and time

following should be your right solution

ren somefile.txt  somefile_%time:~0,2%%time:~3,2%-%DATE:/=%.txt

Format cell if cell contains date less than today

Your first problem was you weren't using your compare symbols correctly.

< less than
> greater than
<= less than or equal to
>= greater than or equal to

To answer your other questions; get the condition to work on every cell in the column and what about blanks?

What about blanks?

Add an extra IF condition to check if the cell is blank or not, if it isn't blank perform the check. =IF(B2="","",B2<=TODAY())

Condition on every cell in column

enter image description here

What difference is there between WebClient and HTTPWebRequest classes in .NET?

Also WebClient doesn't have timeout property. And that's the problem, because dafault value is 100 seconds and that's too much to indicate if there's no Internet connection.

Workaround for that problem is here https://stackoverflow.com/a/3052637/1303422

How to move table from one tablespace to another in oracle 11g

Try this to move your table (tbl1) to tablespace (tblspc2).

alter table tb11 move tablespace tblspc2;

Convert a String to Modified Camel Case in Java or Title Case as is otherwise called

From commons-lang3

org.apache.commons.lang3.text.WordUtils.capitalizeFully(String str)

How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake

For C++, you could do:

export CXXFLAGS=-m32

This works with cmake.

Ruby: How to post a file via HTTP as multipart/form-data?

Here is my solution after trying other ones available on this post, I'm using it to upload photo on TwitPic:

  def upload(photo)
    `curl -F media=@#{photo.path} -F username=#{@username} -F password=#{@password} -F message='#{photo.title}' http://twitpic.com/api/uploadAndPost`
  end

jQuery: Return data after ajax call success

you can add async option to false and return outside the ajax call.

function testAjax() {
    var result="";
    $.ajax({
      url:"getvalue.php",
      async: false,  
      success:function(data) {
         result = data; 
      }
   });
   return result;
}

Download/Stream file from URL - asp.net

I do this quite a bit and thought I could add a simpler answer. I set it up as a simple class here, but I run this every evening to collect financial data on companies I'm following.

class WebPage
{
    public static string Get(string uri)
    {
        string results = "N/A";

        try
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            StreamReader sr = new StreamReader(resp.GetResponseStream());
            results = sr.ReadToEnd();
            sr.Close();
        }
        catch (Exception ex)
        {
            results = ex.Message;
        }
        return results;
    }
}

In this case I pass in a url and it returns the page as HTML. If you want to do something different with the stream instead you can easily change this.

You use it like this:

string page = WebPage.Get("http://finance.yahoo.com/q?s=yhoo");

Parsing a pcap file in python

I would use python-dpkt. Here is the documentation: http://www.commercialventvac.com/dpkt.html

This is all I know how to do though sorry.

#!/usr/local/bin/python2.7

import dpkt

counter=0
ipcounter=0
tcpcounter=0
udpcounter=0

filename='sampledata.pcap'

for ts, pkt in dpkt.pcap.Reader(open(filename,'r')):

    counter+=1
    eth=dpkt.ethernet.Ethernet(pkt) 
    if eth.type!=dpkt.ethernet.ETH_TYPE_IP:
       continue

    ip=eth.data
    ipcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_TCP: 
       tcpcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_UDP:
       udpcounter+=1

print "Total number of packets in the pcap file: ", counter
print "Total number of ip packets: ", ipcounter
print "Total number of tcp packets: ", tcpcounter
print "Total number of udp packets: ", udpcounter

Update:

Project on GitHub, documentation here

Check if Variable is Empty - Angular 2

It depends if you know the given variable Type. If you expect it to be an Object than you could check if myVar is an empty Object like this:

 public isEmpty(myVar): boolean {
     return (myVar && (Object.keys(myVar).length === 0));
 }

Otherwise: if (!myVar) {}, should do the job

How to change resolution (DPI) of an image?

DPI should not be stored in an bitmap image file, as most sources of data for bitmaps render it meaningless.

A bitmap image is stored as pixels. Pixels have no inherent size in any respect. It's only at render time - be it monitor, printer, or automated crossstitching machine - that DPI matters.

A 800x1000 pixel bitmap image, printed at 100 dpi, turns into a nice 8x10" photo. Printed at 200 dpi, the EXACT SAME bitmap image turns into a 4x5" photo.

Capture an image with a digital camera, and what does DPI mean? It's certainly not the size of the area focused onto the CCD imager - that depends on the distance, and with NASA returning images of galaxies that are 100,000 light years across, and 2 million light years apart, in the same field of view, what kind of DPI do you get from THAT information?

Don't fall victim to the idea of the DPI of a bitmap image - it's a mistake. A bitmap image has no physical dimensions (save for a few micrometers of storage space in RAM or hard drive). It's only a displayed image, or a printed image, that has a physical size in inches, or millimeters, or furlongs.

Saving excel worksheet to CSV files with filename+worksheet name using VB

The code above works perfectly with one minor flaw; the resulting file is not saved with a .csv extension. – Tensigh 2 days ago

I added the following to code and it saved my file as a csv. Thanks for this bit of code.It all worked as expected.

ActiveWorkbook.SaveAs Filename:=SaveToDirectory & ThisWorkbook.Name & "-" & WS.Name & ".csv", FileFormat:=xlCSV

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

Besides the solution of m79lkm above, my 2 cents on this topic is not to directly pipe the result in gzip but first dump it as a .sql file, and then gzip it. (Use && instead of | )

The dump itself will be faster. (for what I tested it was double as fast)

Otherwise you tables will be locked longer and the downtime/slow-responding of your application can bother the users. The mysqldump command is taking a lot of resources from your server.

So I would go for "&& gzip" instead of "| gzip"

Important: check for free disk space first with df -h since you will need more then piping | gzip.

mysqldump -u user -p[user_password] [database_name] > dumpfilename.sql && gzip dumpfilename.sql

-> which will also result in 1 file called dumpfilename.sql.gz

Furthermore the option --single-transaction prevents the tables being locked but still result in a solid backup. So you might consider to use that option. See docs here

mysqldump --single-transaction -u user -p[user_password] [database_name] > dumpfilename.sql && gzip dumpfilename.sql