Programs & Examples On #Channel api

The Channel API creates a persistent connection between your application and Google servers, allowing your application to send messages to JavaScript clients in real time without the use of polling.

HTTP Get with 204 No Content: Is that normal

204 No Content

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

According to the RFC part for the status code 204, it seems to me a valid choice for a GET request.

A 404 Not Found, 200 OK with empty body and 204 No Content have completely different meaning, sometimes we can't use proper status code but bend the rules and they will come back to bite you one day or later. So, if you can use proper status code, use it!

I think the choice of GET or POST is very personal as both of them will do the work but I would recommend you to keep a POST instead of a GET, for two reasons:

  • You want the other part (the servlet if I understand correctly) to perform an action not retrieve some data from it.
  • By default GET requests are cacheable if there are no parameters present in the URL, a POST is not.

TypeError: argument of type 'NoneType' is not iterable

If a function does not return anything, e.g.:

def test():
    pass

it has an implicit return value of None.

Thus, as your pick* methods do not return anything, e.g.:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")

the lines that call them, e.g.:

word = pickEasy()

set word to None, so wordInput in getInput is None. This means that:

if guess in wordInput:

is the equivalent of:

if guess in None:

and None is an instance of NoneType which does not provide iterator/iteration functionality, so you get that type error.

The fix is to add the return type:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")
    return word

This version of the application is not configured for billing through Google Play

In my case I saw the same message due to the different signatures of the installed apk and an uploaded to the market apk.

Convert.ToDateTime: how to set format

You can use Convert.ToDateTime is it is shown at How to convert a Datetime string to a current culture datetime string

DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;

var result = Convert.ToDateTime("12/01/2011", usDtfi)

Draggable div without jQuery UI

Here is an implementation without using jQuery at all -
http://thezillion.wordpress.com/2012/09/27/javascript-draggable-2-no-jquery

Embed the JS file (http://zillionhost.xtreemhost.com/tzdragg/tzdragg.js) in your HTML code, and put the following code -

<script>
win.onload = function(){
 tzdragg.drag('elem1, elem2, ..... elemn');
 // ^ IDs of the draggable elements separated by a comma.
}
</script>

And the code is also easy to learn.
http://thezillion.wordpress.com/2012/08/29/javascript-draggable-no-jquery

Disable submit button when form invalid with AngularJS

We can create a simple directive and disable the button until all the mandatory fields are filled.

angular.module('sampleapp').directive('disableBtn',
function() {
 return {
  restrict : 'A',
  link : function(scope, element, attrs) {
   var $el = $(element);
   var submitBtn = $el.find('button[type="submit"]');
   var _name = attrs.name;
   scope.$watch(_name + '.$valid', function(val) {
    if (val) {
     submitBtn.removeAttr('disabled');
    } else {
     submitBtn.attr('disabled', 'disabled');
    }
   });
  }
 };
}
);

For More Info click here

Get Android shared preferences value in activity/normal class

If you have a SharedPreferenceActivity by which you have saved your values

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String imgSett = prefs.getString(keyChannel, "");

if the value is saved in a SharedPreference in an Activity then this is the correct way to saving it.

SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString(keyChannel, email);
editor.commit();// commit is important here.

and this is how you can retrieve the values.

SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = (shared.getString(keyChannel, ""));

Also be aware that you can do so in a non-Activity class too but the only condition is that you need to pass the context of the Activity. use this context in to get the SharedPreferences.

mContext.getSharedPreferences(PREF_NAME, MODE_PRIVATE);

Convert character to Date in R

You may be overcomplicating things, is there any reason you need the stringr package?

 df <- data.frame(Date = c("10/9/2009 0:00:00", "10/15/2009 0:00:00"))
 as.Date(df$Date, "%m/%d/%Y %H:%M:%S")

[1] "2009-10-09" "2009-10-15"

More generally and if you need the time component as well, use strptime:

strptime(df$Date, "%m/%d/%Y %H:%M:%S")

I'm guessing at what your actual data might look at from the partial results you give.

How to get all elements inside "div" that starts with a known text

With modern browsers, this is easy without jQuery:

document.getElementById('yourParentDiv').querySelectorAll('[id^="q17_"]');

The querySelectorAll takes a selector (as per CSS selectors) and uses it to search children of the 'yourParentDiv' element recursively. The selector uses ^= which means "starts with".

Note that all browsers released since June 2009 support this.

Write output to a text file in PowerShell

Use the Out-File cmdlet

 Compare-Object ... | Out-File C:\filename.txt

Optionally, add -Encoding utf8 to Out-File as the default encoding is not really ideal for many uses.

How to get row from R data.frame

If you don't know the row number, but do know some values then you can use subset

x <- structure(list(A = c(5,    3.5, 3.25, 4.25,  1.5 ), 
                    B = c(4.25, 4,   4,    4.5,   4.5 ),
                    C = c(4.5,  2.5, 4,    2.25,  3   )
               ),
               .Names    = c("A", "B", "C"),
               class     = "data.frame",
               row.names = c(NA, -5L)
     )

subset(x, A ==5 & B==4.25 & C==4.5)

How to use order by with union all in sql?

Not an OP direct response, but I thought I would jimmy in here responding to the the OP's ERROR messsage, which may point you in another direction entirely!

All these answers are referring to an overall ORDER BY once the record set has been retrieved and you sort the lot.

What if you want to ORDER BY each portion of the UNION independantly, and still have them "joined" in the same SELECT?

SELECT pass1.* FROM 
 (SELECT TOP 1000 tblA.ID, tblA.CustomerName 
  FROM TABLE_A AS tblA ORDER BY 2) AS pass1
UNION ALL 
SELECT pass2.* FROM 
  (SELECT TOP 1000 tblB.ID, tblB.CustomerName 
   FROM TABLE_B AS tblB ORDER BY 2) AS pass2

Note the TOP 1000 is an arbitary number. Use a big enough number to capture all of the data you require.

Recursive file search using PowerShell

I use this to find files and then have PowerShell display the entire path of the results:

dir -Path C:\FolderName -Filter FileName.fileExtension -Recurse | %{$_.FullName}

You can always use the wildcard * in the FolderName and/or FileName.fileExtension. For example:

dir -Path C:\Folder* -Filter File*.file* -Recurse | %{$_.FullName}

The above example will search any folder in the C:\ drive beginning with the word Folder. So if you have a folder named FolderFoo and FolderBar PowerShell will show results from both of those folders.

The same goes for the file name and file extension. If you want to search for a file with a certain extension, but don't know the name of the file, you can use:

dir -Path C:\FolderName -Filter *.fileExtension -Recurse | %{$_.FullName}

Or vice versa:

dir -Path C:\FolderName -Filter FileName.* -Recurse | %{$_.FullName}

How to Use slideDown (or show) function on a table row?

The plug offered by Vinny is really close, but I found and fixed a couple of small issues.

  1. It greedily targeted td elements beyond just the children of the row being hidden. This would have been kind of ok if it had then sought out those children when showing the row. While it got close, they all ended up with "display: none" on them, rendering them hidden.
  2. It didn't target child th elements at all.
  3. For table cells with lots of content (like a nested table with lots of rows), calling slideRow('up'), regardless of the slideSpeed value provided, it'd collapse the view of the row as soon as the padding animation was done. I fixed it so the padding animation doesn't trigger until the slideUp() method on the wrapping is done.

    (function($){
        var sR = {
            defaults: {
                slideSpeed: 400
              , easing: false
              , callback: false
            }
          , thisCallArgs:{
                slideSpeed: 400
              , easing: false
              , callback: false
            }
          , methods:{
                up: function(arg1, arg2, arg3){
                    if(typeof arg1 == 'object'){
                        for(p in arg1){
                            sR.thisCallArgs.eval(p) = arg1[p];
                        }
                    }else if(typeof arg1 != 'undefined' && (typeof arg1 == 'number' || arg1 == 'slow' || arg1 == 'fast')){
                        sR.thisCallArgs.slideSpeed = arg1;
                    }else{
                        sR.thisCallArgs.slideSpeed = sR.defaults.slideSpeed;
                    }
    
                    if(typeof arg2 == 'string'){
                        sR.thisCallArgs.easing = arg2;
                    }else if(typeof arg2 == 'function'){
                        sR.thisCallArgs.callback = arg2;
                    }else if(typeof arg2 == 'undefined'){
                        sR.thisCallArgs.easing = sR.defaults.easing;    
                    }
                    if(typeof arg3 == 'function'){
                        sR.thisCallArgs.callback = arg3;
                    }else if(typeof arg3 == 'undefined' && typeof arg2 != 'function'){
                        sR.thisCallArgs.callback = sR.defaults.callback;    
                    }
                    var $cells = $(this).children('td, th');
                    $cells.wrapInner('<div class="slideRowUp" />');
                    var currentPadding = $cells.css('padding');
                    $cellContentWrappers = $(this).find('.slideRowUp');
                    $cellContentWrappers.slideUp(sR.thisCallArgs.slideSpeed, sR.thisCallArgs.easing, function(){
                        $(this).parent().animate({ paddingTop: '0px', paddingBottom: '0px' }, {
                            complete: function(){
                                $(this).children('.slideRowUp').replaceWith($(this).children('.slideRowUp').contents());
                                $(this).parent().css({ 'display': 'none' });
                                $(this).css({ 'padding': currentPadding });
                            }
                        });
                    });
                    var wait = setInterval(function(){
                        if($cellContentWrappers.is(':animated') === false){
                            clearInterval(wait);
                            if(typeof sR.thisCallArgs.callback == 'function'){
                                sR.thisCallArgs.callback.call(this);
                            }
                        }
                    }, 100);                                                                                                    
                    return $(this);
                }
              , down: function (arg1, arg2, arg3){
                    if(typeof arg1 == 'object'){
                        for(p in arg1){
                            sR.thisCallArgs.eval(p) = arg1[p];
                        }
                    }else if(typeof arg1 != 'undefined' && (typeof arg1 == 'number' || arg1 == 'slow' || arg1 == 'fast')){
                        sR.thisCallArgs.slideSpeed = arg1;
                    }else{
                        sR.thisCallArgs.slideSpeed = sR.defaults.slideSpeed;
                    }
    
                    if(typeof arg2 == 'string'){
                        sR.thisCallArgs.easing = arg2;
                    }else if(typeof arg2 == 'function'){
                        sR.thisCallArgs.callback = arg2;
                    }else if(typeof arg2 == 'undefined'){
                        sR.thisCallArgs.easing = sR.defaults.easing;    
                    }
                    if(typeof arg3 == 'function'){
                        sR.thisCallArgs.callback = arg3;
                    }else if(typeof arg3 == 'undefined' && typeof arg2 != 'function'){
                        sR.thisCallArgs.callback = sR.defaults.callback;    
                    }
                    var $cells = $(this).children('td, th');
                    $cells.wrapInner('<div class="slideRowDown" style="display:none;" />');
                    $cellContentWrappers = $cells.find('.slideRowDown');
                    $(this).show();
                    $cellContentWrappers.slideDown(sR.thisCallArgs.slideSpeed, sR.thisCallArgs.easing, function() { $(this).replaceWith( $(this).contents()); });
    
                    var wait = setInterval(function(){
                        if($cellContentWrappers.is(':animated') === false){
                            clearInterval(wait);
                            if(typeof sR.thisCallArgs.callback == 'function'){
                                sR.thisCallArgs.callback.call(this);
                            }
                        }
                    }, 100);
                    return $(this);
                }
            }
        };
    
        $.fn.slideRow = function(method, arg1, arg2, arg3){
            if(typeof method != 'undefined'){
                if(sR.methods[method]){
                    return sR.methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
                }
            }
        };
    })(jQuery);
    

Python argparse: default value or specified value

The difference between:

parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)

and

parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)

is thus:

myscript.py => debug is 7 (from default) in the first case and "None" in the second

myscript.py --debug => debug is 1 in each case

myscript.py --debug 2 => debug is 2 in each case

SQL query to make all data in a column UPPER CASE?

Permanent:

UPDATE
  MyTable
SET
  MyColumn = UPPER(MyColumn)

Temporary:

SELECT
  UPPER(MyColumn) AS MyColumn
FROM
  MyTable

What does "both" mean in <div style="clear:both">

Both means "every item in a set of two things". The two things being "left" and "right"

Does VBScript have a substring() function?

As Tmdean correctly pointed out you can use the Mid() function. The MSDN Library also has a great reference section on VBScript which you can find here:

VBScript Language Reference (MSDN Library)

How to retrieve element value of XML using Java?

Since you are using this for configuration, your best bet is apache commons-configuration. For simple files it's way easier to use than "raw" XML parsers.

See the XML how-to

Declare a const array

Since C# 6 you can write it like:

public static string[] Titles => new string[] { "German", "Spanish", "Corrects", "Wrongs" };

See also: C# : The New and Improved C# 6.0 (specifically the chapter "Expression Bodied Functions and Properties")

This will make a read-only static property, but it will still allow you to alter the content of the array returned, but when you call the property again, you will get the original, unaltered array again.

For clarification, this code is the same as (or actually a shorthand for):

public static string[] Titles
{
    get { return new string[] { "German", "Spanish", "Corrects", "Wrongs" }; }
}

Please note that there is a downside to this approach: A new array is actually instantiated on each and every reference, so if you are using a very large array, this might not be the most efficient solution. But if you re-use the same array (by putting it in a private attribute for instance) it will again open up the possibility to change the contents of the array.

If you want to have an immutable array (or list) you could also use:

public static IReadOnlyList<string> Titles { get; } = new string[] { "German", "Spanish", "Corrects", "Wrongs" };

But, this still has a risk for changes, as you can still cast it back to a string[] and alter the contents, as such:

((string[]) Titles)[1] = "French";

How to check if a variable is an integer in JavaScript?

You can use a simple regular expression:

function isInt(value) {
    var er = /^-?[0-9]+$/;
    return er.test(value);
}

How do I center content in a div using CSS?

To align horizontally it's pretty straight forward:

    <style type="text/css"> 
body  {
    margin: 0; 
    padding: 0;
    text-align: center;
}
.bodyclass #container { 
    width: ???px; /*SET your width here*/
    margin: 0 auto;
    text-align: left;
} 
</style>
<body class="bodyclass ">
<div id="container">type your content here</div>
</body>

and for vertical align, it's a bit tricky: here's the source

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
  <title>Universal vertical center with CSS</title>
  <style>
    .greenBorder {border: 1px solid green;} /* just borders to see it */
  </style>
</head>

<body>
  <div class="greenBorder" style="display: table; height: 400px; #position: relative; overflow: hidden;">
    <div style=" #position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">
      <div class="greenBorder" style=" #position: relative; #top: -50%">
        any text<br>
        any height<br>
        any content, for example generated from DB<br>
        everything is vertically centered
      </div>
    </div>
  </div>
</body>
</html>

Using Mockito's generic "any()" method

As I needed to use this feature for my latest project (at one point we updated from 1.10.19), just to keep the users (that are already using the mockito-core version 2.1.0 or greater) up to date, the static methods from the above answers should be taken from ArgumentMatchers class:

import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.ArgumentMatchers.any;

Please keep this in mind if you are planning to keep your Mockito artefacts up to date as possibly starting from version 3, this class may no longer exist:

As per 2.1.0 and above, Javadoc of org.mockito.Matchers states:

Use org.mockito.ArgumentMatchers. This class is now deprecated in order to avoid a name clash with Hamcrest * org.hamcrest.Matchers class. This class will likely be removed in version 3.0.

I have written a little article on mockito wildcards if you're up for further reading.

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

Removing node_modules and running npm install fixed those errors for me.

Others say: npm rebuild node-sass or npm audit fix might help.

Using SSIS BIDS with Visual Studio 2012 / 2013

Today March 6, 2013, Microsoft released SQL Server Data Tools – Business Intelligence for Visual Studio 2012 (SSDT BI) templates. With SSDT BI for Visual Studio 2012 you can develop and deploy SQL Server Business intelligence projects. Projects created in Visual Studio 2010 can be opened in Visual Studio 2012 and the other way around without upgrading or downgrading – it just works.

The download/install is named to ensure you get the SSDT templates that contain the Business Intelligence projects. The setup for these tools is now available from the web and can be downloaded in multiple languages right here: http://www.microsoft.com/download/details.aspx?id=36843

new DateTime() vs default(DateTime)

If you want to use default value for a DateTime parameter in a method, you can only use default(DateTime).

The following line will not compile:

    private void MyMethod(DateTime syncedTime = DateTime.MinValue)

This line will compile:

    private void MyMethod(DateTime syncedTime = default(DateTime))

Cross-platform way of getting temp directory in Python

That would be the tempfile module.

It has functions to get the temporary directory, and also has some shortcuts to create temporary files and directories in it, either named or unnamed.

Example:

import tempfile

print tempfile.gettempdir() # prints the current temporary directory

f = tempfile.TemporaryFile()
f.write('something on temporaryfile')
f.seek(0) # return to beginning of file
print f.read() # reads data back from the file
f.close() # temporary file is automatically deleted here

For completeness, here's how it searches for the temporary directory, according to the documentation:

  1. The directory named by the TMPDIR environment variable.
  2. The directory named by the TEMP environment variable.
  3. The directory named by the TMP environment variable.
  4. A platform-specific location:
    • On RiscOS, the directory named by the Wimp$ScrapDir environment variable.
    • On Windows, the directories C:\TEMP, C:\TMP, \TEMP, and \TMP, in that order.
    • On all other platforms, the directories /tmp, /var/tmp, and /usr/tmp, in that order.
  5. As a last resort, the current working directory.

json_encode(): Invalid UTF-8 sequence in argument

The problem is that this character is UTF8, but json_encode does not handle it correctly. To say more, there is a list of other characters (see Unicode characters list), that will trigger the same error, so stripping off this one (Å) will not correct an issue to the end.

What we have used is to convert these chars to html entities like this:

htmlentities( (string) $value, ENT_QUOTES, 'utf-8', FALSE);

Calling variable defined inside one function from another function

def oneFunction(lists):
    category=random.choice(list(lists.keys()))
    word=random.choice(lists[category])
    return word

def anotherFunction():
    for letter in word:             
        print("_",end=" ")

Error: fix the version conflict (google-services plugin)

Same error gets thrown when

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

is not added to bottom of the module build.gradle file.

Android getting value from selected radiobutton

mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        RadioButton radioButton = (RadioButton)group.findViewById(checkedId);
    }
});

jQuery - setting the selected value of a select control via its text description

 $('#theYear').on('change', function () {
 FY = $(this).find('option:selected').text();
 $('#theFolders').each(function () {
     $('option:not(:contains(' + FY + '))', this).hide();
 });
 $('#theFolders').val(0);
});

$('#theYear').on('mousedown', function () {
 $('#theFolders option').show().find('option:contains("Select")', this).attr('selected', 'selected');
});

Center HTML Input Text Field Placeholder

input{
   text-align:center;
}

is all you need.

Working example in FF6. This method doesn't seem to be cross-browser compatible.

Your previous CSS was attempting to center the text of an input element which had a class of "placeholder".

Regular Expression for alphanumeric and underscores

I believe you are not taking Latin and Unicode characters in your matches. For example, if you need to take "ã" or "ü" chars, the use of "\w" won't work.

You can, alternatively, use this approach:

^[A-ZÀ-Ýa-zà-ý0-9_]+$

Hope it helps!

Running java with JAVA_OPTS env variable has no effect

I don't know of any JVM that actually checks the JAVA_OPTS environment variable. Usually this is used in scripts which launch the JVM and they usually just add it to the java command-line.

The key thing to understand here is that arguments to java that come before the -jar analyse.jar bit will only affect the JVM and won't be passed along to your program. So, modifying the java line in your script to:

java $JAVA_OPTS -jar analyse.jar $*

Should "just work".

React Native Change Default iOS Simulator Device

Here is new path for changing iOS simulator you just need to change

default: 'iPhone 6' or something else 

Path:

<project_root>/node_modules/@react-native-community/cli/build/commands/runIOS/runIOS.js

Convert string to datetime

You could use the moment.js library.

Then simply:

var stringDate = '01-01-1970 00:03:44';
var momentDateObj = moment(stringDate);

Checkout their api also, helps with formatting, adding, subtracting (days, months, years, other moment objects).

I hope this helps.

Rhys

Implementing two interfaces in a class with same method. Which interface method is overridden?

If a type implements two interfaces, and each interface define a method that has identical signature, then in effect there is only one method, and they are not distinguishable. If, say, the two methods have conflicting return types, then it will be a compilation error. This is the general rule of inheritance, method overriding, hiding, and declarations, and applies also to possible conflicts not only between 2 inherited interface methods, but also an interface and a super class method, or even just conflicts due to type erasure of generics.


Compatibility example

Here's an example where you have an interface Gift, which has a present() method (as in, presenting gifts), and also an interface Guest, which also has a present() method (as in, the guest is present and not absent).

Presentable johnny is both a Gift and a Guest.

public class InterfaceTest {
    interface Gift  { void present(); }
    interface Guest { void present(); }

    interface Presentable extends Gift, Guest { }

    public static void main(String[] args) {
        Presentable johnny = new Presentable() {
            @Override public void present() {
                System.out.println("Heeeereee's Johnny!!!");
            }
        };
        johnny.present();                     // "Heeeereee's Johnny!!!"

        ((Gift) johnny).present();            // "Heeeereee's Johnny!!!"
        ((Guest) johnny).present();           // "Heeeereee's Johnny!!!"

        Gift johnnyAsGift = (Gift) johnny;
        johnnyAsGift.present();               // "Heeeereee's Johnny!!!"

        Guest johnnyAsGuest = (Guest) johnny;
        johnnyAsGuest.present();              // "Heeeereee's Johnny!!!"
    }
}

The above snippet compiles and runs.

Note that there is only one @Override necessary!!!. This is because Gift.present() and Guest.present() are "@Override-equivalent" (JLS 8.4.2).

Thus, johnny only has one implementation of present(), and it doesn't matter how you treat johnny, whether as a Gift or as a Guest, there is only one method to invoke.


Incompatibility example

Here's an example where the two inherited methods are NOT @Override-equivalent:

public class InterfaceTest {
    interface Gift  { void present(); }
    interface Guest { boolean present(); }

    interface Presentable extends Gift, Guest { } // DOES NOT COMPILE!!!
    // "types InterfaceTest.Guest and InterfaceTest.Gift are incompatible;
    //  both define present(), but with unrelated return types"
}

This further reiterates that inheriting members from an interface must obey the general rule of member declarations. Here we have Gift and Guest define present() with incompatible return types: one void the other boolean. For the same reason that you can't an void present() and a boolean present() in one type, this example results in a compilation error.


Summary

You can inherit methods that are @Override-equivalent, subject to the usual requirements of method overriding and hiding. Since they ARE @Override-equivalent, effectively there is only one method to implement, and thus there's nothing to distinguish/select from.

The compiler does not have to identify which method is for which interface, because once they are determined to be @Override-equivalent, they're the same method.

Resolving potential incompatibilities may be a tricky task, but that's another issue altogether.

References

Show Curl POST Request Headers? Is there a way to do this?

You can make you request headers by yourself using:

// open a socket connection on port 80
$fp = fsockopen($host, 80);

// send the request headers:
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Referer: $referer\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ". strlen($data) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);

$result = ''; 
while(!feof($fp)) {
    // receive the results of the request
    $result .= fgets($fp, 128);
}

// close the socket connection:
fclose($fp);

Like writen on how make request

Using ng-if as a switch inside ng-repeat?

Try to surround strings (hoot, story, article) with quotes ':

<div ng-repeat = "data in comments">
    <div ng-if="data.type == 'hoot' ">
        //different template with hoot data
    </div>
    <div ng-if="data.type == 'story' ">
        //different template with story data
    </div>
    <div ng-if="data.type == 'article' ">
        //different template with article data
    </div> 
</div>

Return in Scala

By default the last expression of a function will be returned. In your example there is another expression after the point, where you want your return value. If you want to return anything prior to your last expression, you still have to use return.

You could modify your example like this, to return a Boolean from the first part

def balanceMain(elem: List[Char]): Boolean = {
  if (elem.isEmpty) {
    // == is a Boolean resulting function as well, so your can write it this way
    count == 0
  } else {
    // keep the rest in this block, the last value will be returned as well
    if (elem.head == "(") {
      balanceMain(elem.tail, open, count + 1)
    }
    // some more statements
    ...
    // just don't forget your Boolean in the end
    someBoolExpression
  }
}

How does bitshifting work in Java?

byte x = 51; //00101011
byte y = (byte) (x >> 2); //00001010 aka Base(10) 10

map vs. hash_map in C++

The C++ spec doesn't say exactly what algorithm you must use for the STL containers. It does, however, put certain constraints on their performance, which rules out the use of hash tables for map and other associative containers. (They're most commonly implemented with red/black trees.) These constraints require better worst-case performance for these containers than hash tables can deliver.

Many people really do want hash tables, however, so hash-based STL associative containers have been a common extension for years. Consequently, they added unordered_map and such to later versions of the C++ standard.

Set start value for column with autoincrement

You need to set the Identity seed to that value:

CREATE TABLE orders
(
 id int IDENTITY(9586,1)
)

To alter an existing table:

ALTER TABLE orders ALTER COLUMN Id INT IDENTITY (9586, 1);

More info on CREATE TABLE (Transact-SQL) IDENTITY (Property)

How do I get time of a Python program's execution?

Timeit is a class in Python used to calculate the execution time of small blocks of code.

Default_timer is a method in this class which is used to measure the wall clock timing, not CPU execution time. Thus other process execution might interfere with this. Thus it is useful for small blocks of code.

A sample of the code is as follows:

from timeit import default_timer as timer

start= timer()

# Some logic

end = timer()

print("Time taken:", end-start)

How to set an iframe src attribute from a variable in AngularJS

You need also $sce.trustAsResourceUrl or it won't open the website inside the iframe:

_x000D_
_x000D_
angular.module('myApp', [])_x000D_
    .controller('dummy', ['$scope', '$sce', function ($scope, $sce) {_x000D_
_x000D_
    $scope.url = $sce.trustAsResourceUrl('https://www.angularjs.org');_x000D_
_x000D_
    $scope.changeIt = function () {_x000D_
        $scope.url = $sce.trustAsResourceUrl('https://docs.angularjs.org/tutorial');_x000D_
    }_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="dummy">_x000D_
    <iframe ng-src="{{url}}" width="300" height="200"></iframe>_x000D_
    <br>_x000D_
    <button ng-click="changeIt()">Change it</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ASP.NET: Session.SessionID changes between requests

my problem was that we had this set in web.config

<httpCookies httpOnlyCookies="true" requireSSL="true" />

this means that when debugging in non-SSL (the default), the auth cookie would not get sent back to the server. this would mean that the server would send a new auth cookie (with a new session) for every request back to the client.

the fix is to either set requiressl to false in web.config and true in web.release.config or turn on SSL while debugging:

turn on SSL

Verifying that a string contains only letters in C#

I think is a good case to use Regular Expressions:

public bool IsAlpha(string input)
{
    return Regex.IsMatch(input, "^[a-zA-Z]+$");
}

public bool IsAlphaNumeric(string input)
{
    return Regex.IsMatch(input, "^[a-zA-Z0-9]+$");
}

public bool IsAlphaNumericWithUnderscore(string input)
{
    return Regex.IsMatch(input, "^[a-zA-Z0-9_]+$");
}

Segmentation Fault - C

char *s  does not have some memory allocated . You need to allocate it manually in your case . You can do it as follows
s = (char *)malloc(100) ;

This would not lead to segmentation fault error as you will not be refering to an unknown location anymore

How can I apply a border only inside a table?

this works for me:

table {
    border-collapse: collapse;
    border-style: hidden;
}

table td, table th {
    border: 1px solid black;
}

view example ...

tested in FF 3.6 and Chromium 5.0, IE lacks support; from W3C:

Borders with the 'border-style' of 'hidden' take precedence over all other conflicting borders. Any border with this value suppresses all borders at this location.

Exercises to improve my Java programming skills

Go and buy the book titled "Java examples in a nutshell". In the book you will find most of practical examples.

XML Parser for C

Two examples with expat and libxml2. The second one is, IMHO, much easier to use since it creates a tree in memory, a data structure which is easy to work with. expat, on the other hand, does not build anything (you have to do it yourself), it just allows you to call handlers at specific events during the parsing. But expat may be faster (I didn't measure).

With expat, reading a XML file and displaying the elements indented:

/* 
   A simple test program to parse XML documents with expat
   <http://expat.sourceforge.net/>. It just displays the element
   names.

   On Debian, compile with:

   gcc -Wall -o expat-test -lexpat expat-test.c  

   Inspired from <http://www.xml.com/pub/a/1999/09/expat/index.html> 
*/

#include <expat.h>
#include <stdio.h>
#include <string.h>

/* Keep track of the current level in the XML tree */
int             Depth;

#define MAXCHARS 1000000

void
start(void *data, const char *el, const char **attr)
{
    int             i;

    for (i = 0; i < Depth; i++)
        printf("  ");

    printf("%s", el);

    for (i = 0; attr[i]; i += 2) {
        printf(" %s='%s'", attr[i], attr[i + 1]);
    }

    printf("\n");
    Depth++;
}               /* End of start handler */

void
end(void *data, const char *el)
{
    Depth--;
}               /* End of end handler */

int
main(int argc, char **argv)
{

    char           *filename;
    FILE           *f;
    size_t          size;
    char           *xmltext;
    XML_Parser      parser;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s filename\n", argv[0]);
        return (1);
    }
    filename = argv[1];
    parser = XML_ParserCreate(NULL);
    if (parser == NULL) {
        fprintf(stderr, "Parser not created\n");
        return (1);
    }
    /* Tell expat to use functions start() and end() each times it encounters
     * the start or end of an element. */
    XML_SetElementHandler(parser, start, end);
    f = fopen(filename, "r");
    xmltext = malloc(MAXCHARS);
    /* Slurp the XML file in the buffer xmltext */
    size = fread(xmltext, sizeof(char), MAXCHARS, f);
    if (XML_Parse(parser, xmltext, strlen(xmltext), XML_TRUE) ==
        XML_STATUS_ERROR) {
        fprintf(stderr,
            "Cannot parse %s, file may be too large or not well-formed XML\n",
            filename);
        return (1);
    }
    fclose(f);
    XML_ParserFree(parser);
    fprintf(stdout, "Successfully parsed %i characters in file %s\n", size,
        filename);
    return (0);
}

With libxml2, a program which displays the name of the root element and the names of its children:

/*
   Simple test with libxml2 <http://xmlsoft.org>. It displays the name
   of the root element and the names of all its children (not
   descendents, just children).

   On Debian, compiles with:
   gcc -Wall -o read-xml2 $(xml2-config --cflags) $(xml2-config --libs) \
                    read-xml2.c    

*/

#include <stdio.h>
#include <string.h>
#include <libxml/parser.h>

int
main(int argc, char **argv)
{
    xmlDoc         *document;
    xmlNode        *root, *first_child, *node;
    char           *filename;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s filename.xml\n", argv[0]);
        return 1;
    }
    filename = argv[1];

    document = xmlReadFile(filename, NULL, 0);
    root = xmlDocGetRootElement(document);
    fprintf(stdout, "Root is <%s> (%i)\n", root->name, root->type);
    first_child = root->children;
    for (node = first_child; node; node = node->next) {
        fprintf(stdout, "\t Child is <%s> (%i)\n", node->name, node->type);
    }
    fprintf(stdout, "...\n");
    return 0;
}

Javascript: How to check if a string is empty?

If you want to know if it's an empty string use === instead of ==.

if(variable === "") {
}

This is because === will only return true if the values on both sides are of the same type, in this case a string.

for example: (false == "") will return true, and (false === "") will return false.

automating telnet session using bash scripts

Here is how to use telnet in bash shell/expect

#!/usr/bin/expect
# just do a chmod 755 one the script
# ./YOUR_SCRIPT_NAME.sh $YOUHOST $PORT
# if you get "Escape character is '^]'" as the output it means got connected otherwise it has failed

set ip [lindex $argv 0]
set port [lindex $argv 1]

set timeout 5
spawn telnet $ip $port
expect "'^]'."

read.csv warning 'EOF within quoted string' prevents complete reading of file

You need to disable quoting.

cit <- read.csv("citations.CSV", quote = "", 
                 row.names = NULL, 
                 stringsAsFactors = FALSE)

str(cit)
## 'data.frame':    112543 obs. of  13 variables:
##  $ row.names    : chr  "10.2307/675394" "10.2307/30007362" "10.2307/4254931" "10.2307/20537934" ...
##  $ id           : chr  "10.2307/675394\t" "10.2307/30007362\t" "10.2307/4254931\t" "10.2307/20537934\t" ...
##  $ doi          : chr  "Archaeological Inference and Inductive Confirmation\t" "Sound and Sense in Cath Almaine\t" "Oak Galls Preserved by the Eruption of Mount Vesuvius in A.D. 79_ and Their Probable Use\t" "The Arts Four Thousand Years Ago\t" ...
##  $ title        : chr  "Bruce D. Smith\t" "Tomás Ó Cathasaigh\t" "Hiram G. Larew\t" "\t" ...
##  $ author       : chr  "American Anthropologist\t" "Ériu\t" "Economic Botany\t" "The Illustrated Magazine of Art\t" ...
##  $ journaltitle : chr  "79\t" "54\t" "41\t" "1\t" ...
##  $ volume       : chr  "3\t" "\t" "1\t" "3\t" ...
##  $ issue        : chr  "1977-09-01T00:00:00Z\t" "2004-01-01T00:00:00Z\t" "1987-01-01T00:00:00Z\t" "1853-01-01T00:00:00Z\t" ...
##  $ pubdate      : chr  "pp. 598-617\t" "pp. 41-47\t" "pp. 33-40\t" "pp. 171-172\t" ...
##  $ pagerange    : chr  "American Anthropological Association\tWiley\t" "Royal Irish Academy\t" "New York Botanical Garden Press\tSpringer\t" "\t" ...
##  $ publisher    : chr  "fla\t" "fla\t" "fla\t" "fla\t" ...
##  $ type         : logi  NA NA NA NA NA NA ...
##  $ reviewed.work: logi  NA NA NA NA NA NA ...

I think is because of this kind of lines (check "Thorn" and "Minus")

 readLines("citations.CSV")[82]
[1] "10.2307/3642839,10.2307/3642839\t,\"Thorn\" and \"Minus\" in Hieroglyphic Luvian Orthography\t,H. Craig Melchert\t,Anatolian Studies\t,38\t,\t,1988-01-01T00:00:00Z\t,pp. 29-42\t,British Institute at Ankara\t,fla\t,\t,"

Unit testing void methods?

Use Rhino Mocks to set what calls, actions and exceptions might be expected. Assuming you can mock or stub out parts of your method. Hard to know without knowing some specifics here about the method, or even context.

ResultSet exception - before start of result set

It's better if you create a class that has all the query methods, inclusively, in a different package, so instead of typing all the process in every class, you just call the method from that class.

Excel: Can I create a Conditional Formula based on the Color of a Cell?

Unfortunately, there is not a direct way to do this with a single formula. However, there is a fairly simple workaround that exists.

On the Excel Ribbon, go to "Formulas" and click on "Name Manager". Select "New" and then enter "CellColor" as the "Name". Jump down to the "Refers to" part and enter the following:

=GET.CELL(63,OFFSET(INDIRECT("RC",FALSE),1,1))

Hit OK then close the "Name Manager" window.

Now, in cell A1 enter the following:

=IF(CellColor=3,"FQS",IF(CellColor=6,"SM",""))

This will return FQS for red and SM for yellow. For any other color the cell will remain blank.

***If the value in A1 doesn't update, hit 'F9' on your keyboard to force Excel to update the calculations at any point (or if the color in B2 ever changes).

Below is a reference for a list of cell fill colors (there are 56 available) if you ever want to expand things: http://www.smixe.com/excel-color-pallette.html

Cheers.

::Edit::

The formula used in Name Manager can be further simplified if it helps your understanding of how it works (the version that I included above is a lot more flexible and is easier to use in checking multiple cell references when copied around as it uses its own cell address as a reference point instead of specifically targeting cell B2).

Either way, if you'd like to simplify things, you can use this formula in Name Manager instead:

=GET.CELL(63,Sheet1!B2)

Join vs. sub-query

Sub-queries are the logically correct way to solve problems of the form, "Get facts from A, conditional on facts from B". In such instances, it makes more logical sense to stick B in a sub-query than to do a join. It is also safer, in a practical sense, since you don't have to be cautious about getting duplicated facts from A due to multiple matches against B.

Practically speaking, however, the answer usually comes down to performance. Some optimisers suck lemons when given a join vs a sub-query, and some suck lemons the other way, and this is optimiser-specific, DBMS-version-specific and query-specific.

Historically, explicit joins usually win, hence the established wisdom that joins are better, but optimisers are getting better all the time, and so I prefer to write queries first in a logically coherent way, and then restructure if performance constraints warrant this.

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

You're missing service name:

 SQL> connect username/password@hostname:port/SERVICENAME

EDIT

If you can connect to the database from other computer try running there:

select sys_context('USERENV','SERVICE_NAME') from dual

and

select sys_context('USERENV','SID') from dual

Multiple inputs on one line

Yes, you can.

From cplusplus.com:

Because these functions are operator overloading functions, the usual way in which they are called is:

   strm >> variable;

Where strm is the identifier of a istream object and variable is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:

   strm >> variable1 >> variable2 >> variable3; //...

which is the same as performing successive extractions from the same object strm.

Just replace strm with cin.

SQL, How to Concatenate results?

Small update on Marc we will have additional " , " at the end. i used stuff function to remove extra semicolon .

       SELECT STUFF((  SELECT ',' + ModuleValue AS ModuleValue
                           FROM ModuleValue WHERE ModuleID=@ModuleID
                      FOR XML PATH('') 
                     ), 1, 1, '' )

how to fetch data from database in Hibernate

The correct way from hibernate doc:

    Session s = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = null;
    try {

        tx = s.beginTransaction();        

        // here get object
        List<Employee> list = s.createCriteria(Employee.class).list();

        tx.commit();

    } catch (HibernateException ex) {
        if (tx != null) {
            tx.rollback();
        }            
        Logger.getLogger("con").info("Exception: " + ex.getMessage());
        ex.printStackTrace(System.err);
    } finally {
        s.close(); 
    }

HibernateUtil code (can find at Google):

            public class HibernateUtil {

                private static final SessionFactory tmrSessionFactory;
                private static final Ejb3Configuration tmrEjb3Config;
                private static final EntityManagerFactory tmrEntityManagerFactory;

                static {

                    try {

                        tmrSessionFactory = new Configuration().configure("tmr.cfg.xml").buildSessionFactory();
                        tmrEjb3Config = new Ejb3Configuration().configure("tmr.cfg.xml");
                        tmrEntityManagerFactory = tmrEjb3Config.buildEntityManagerFactory();

                    } catch (HibernateException ex) {
                        Logger.getLogger("app").log(Level.WARN, ex.getMessage());
                        throw new ExceptionInInitializerError(ex);
                    }
                }

                public static SessionFactory getSessionFactory() {
                    return tmrSessionFactory;
                }

                /* getters and setters here */


            }

ScrollIntoView() causing the whole page to move

I had this problem too, and spent many hours trying to deal with it. I hope my resolution may still help some people.

My fix ended up being:

  • For Chrome: changing .scrollIntoView() to .scrollIntoView({block: 'nearest'}) (thanks to @jfrohn).
  • For Firefox: apply overflow: -moz-hidden-unscrollable; on the container element that shifts.
  • Not tested in other browsers.

Media Player called in state 0, error (-38,0)

enter image description here

above the picture,you can get the right way.

python setup.py uninstall

I had run python setup.py install once in my PyCharm, it installs all the packages into my conda base environment. Later when I want to remove all these packages, pip uninstall does not work. I had to delete them from /anaconda3/lib/python3.7/site-packages manually :(

So I don't see the reason why they use setup.py instead of writing requirements.txt file. The requirement file can be used to install packages in virtual environment and won't mess with system python packages.

Laravel 5: Retrieve JSON array from $request

You can use getContent() method on Request object.

$request->getContent() //json as a string.

How can I simulate an array variable in MySQL?

You can achieve this in MySQL using WHILE loop:

SET @myArrayOfValue = '2,5,2,23,6,';

WHILE (LOCATE(',', @myArrayOfValue) > 0)
DO
    SET @value = ELT(1, @myArrayOfValue);
    SET @myArrayOfValue= SUBSTRING(@myArrayOfValue, LOCATE(',',@myArrayOfValue) + 1);

    INSERT INTO `EXEMPLE` VALUES(@value, 'hello');
END WHILE;

EDIT: Alternatively you can do it using UNION ALL:

INSERT INTO `EXEMPLE`
(
 `value`, `message`
)
(
 SELECT 2 AS `value`, 'hello' AS `message`
 UNION ALL
 SELECT 5 AS `value`, 'hello' AS `message`
 UNION ALL
 SELECT 2 AS `value`, 'hello' AS `message`
 UNION ALL
 ...
);

Can I load a UIImage from a URL?

If you're really, absolutely positively sure that the NSURL is a file url, i.e. [url isFileURL] is guaranteed to return true in your case, then you can simply use:

[UIImage imageWithContentsOfFile:url.path]

Escape double quotes in Java

Yes you will have to escape all double quotes by a backslash.

Home does not contain an export named Home

This is a case where you mixed up default exports and named exports.

When dealing with the named exports, if you try to import them you should use curly braces as below,

import { Home } from './layouts/Home'; // if the Home is a named export

In your case the Home was exported as a default one. This is the one that will get imported from the module, when you don’t specify a certain name of a certain piece of code. When you import, and omit the curly braces, it will look for the default export in the module you’re importing from. So your import should be,

import Home from './layouts/Home'; // if the Home is a default export

Some references to look :

The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly

In case it helps, I've ran into this problem when passing null into a parameter for a generic TValue, to get around this you have to cast your null values:

(string)null

(int)null

etc.

Is there a simple way to remove unused dependencies from a maven pom.xml?

The Maven Dependency Plugin will help, especially the dependency:analyze goal:

dependency:analyze analyzes the dependencies of this project and determines which are: used and declared; used and undeclared; unused and declared.

Another thing that might help to do some cleanup is the Dependency Convergence report from the Maven Project Info Reports Plugin.

Build unsigned APK file with Android Studio

I would recommend you to build your APK file with Gradle:

  • Click the dropdown menu in the toolbar at the top (Open 'Edit Run/Debug configurations' dialog)
  • Select "Edit Configurations"
  • Click the "+"
  • Select "Gradle"
  • Choose your module as a Gradle project
  • In Tasks: enter assemble
  • Press Run

Your unsigned APK is now located in

ProjectName\app\build\outputs\apk

For detailed information on how to use Gradle, this tutorial is good to go: Building with Gradle in Android Studio. I also wrote a blog post on how to build an unsigned APK with Gradle.

If you moved your project from the other IDE and don't want to recompile, you may find your APK file that was already built in the IDE you moved from:

  • If you generated the Project with Android Studio, the APK file will be found in ProjectName/ProjectName/build/apk/...

  • Imported the project from eclipse: File should be in the same directory. Go to Project - Show in Explorer. There you should find the bin folder where your APK file is located in.

  • Imported from IntelliJ, the location would be ProjectName/out/production/...

Side note: As Chris Stratton mentioned in his comment:

Technically, what you want is an APK signed with a debug key. An APK that is actually unsigned will be refused by the device.

Two constructors

To call one constructor from another you need to use this() and you need to put it first. In your case the default constructor needs to call the one which takes an argument, not the other ways around.

MySQL Cannot Add Foreign Key Constraint

I had this same issue then i corrected the Engine name as Innodb in both parent and child tables and corrected the reference field name FOREIGN KEY (c_id) REFERENCES x9o_parent_table(c_id)
then it works fine and the tables are installed correctly. This will be use full for someone.

Heroku deployment error H10 (App crashed)

The solution I posted on Dev and worked for most people using React:

https://medium.com/@uros.randelovic/causes-of-heroku-h10-app-crashed-error-and-how-to-solve-them-70495914d2a3?sk=1c51cf95e904f754a43a4b63a06b5503

npm install serve --s
"scripts": {
"dev": "react-scripts start",
"start": "serve -s build",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"heroku-postbuild": "npm run build"
}

How to change an application icon programmatically in Android?

Try this solution

<activity android:name=".SplashActivity"
        android:label="@string/app_name"
        android:icon="@drawable/ic_launcher">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity-alias android:label="ShortCut"
        android:icon="@drawable/ic_short_cut"
        android:name=".SplashActivityAlias"
        android:enabled="false"
        android:targetActivity=".SplashActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity-alias>

Add the following code when you want to change your app icon

PackageManager pm = getPackageManager();
                    pm.setComponentEnabledSetting(
                            new ComponentName(YourActivity.this,
                                    "your_package_name.SplashActivity"),
                            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                            PackageManager.DONT_KILL_APP);

                    pm.setComponentEnabledSetting(
                            new ComponentName(YourActivity.this,
                                    "your_package_name.SplashActivityAlias"),
                            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                            PackageManager.DONT_KILL_APP);

Connect Java to a MySQL database

HOW
  • To set up the Driver to run a quick sample
1. Go to https://dev.mysql.com/downloads/connector/j/, get the latest version of Connector/J

2. Remember to set the classpath to include the path of the connector jar file.
If we don't set it correctly, below errors can occur:

No suitable driver found for jdbc:mysql://127.0.0.1:3306/msystem_development

java.lang.ClassNotFoundException: com.mysql.jdbc:Driver
  • To set up the CLASSPATH

Method 1: set the CLASSPATH variable.

export CLASSPATH=".:mysql-connector-java-VERSION.jar"
java MyClassFile

In the above command, I have set the CLASSPATH to the current folder and mysql-connector-java-VERSION.jar file. So when the java MyClassFile command executed, java application launcher will try to load all the Java class in CLASSPATH. And it found the Drive class => BOOM errors was gone.

Method 2:

java -cp .:mysql-connector-java-VERSION.jar MyClassFile

Note: Class.forName("com.mysql.jdbc.Driver"); This is deprecated at this moment 2019 Apr.

Hope this can help someone!

Insert/Update/Delete with function in SQL Server

You can't update tables from a function like you would a stored procedure, but you CAN update table variables.

So for example, you can't do this in your function:

create table MyTable
(
    ID int,
    column1 varchar(100)
)
update [MyTable]
set column1='My value'

but you can do:

declare @myTable table
(
    ID int,
    column1 varchar(100)
)

Update @myTable
set column1='My value'

Setting default values for columns in JPA

  1. @Column(columnDefinition='...') doesn't work when you set the default constraint in database while inserting the data.
  2. You need to make insertable = false and remove columnDefinition='...' from annotation, then database will automatically insert the default value from the database.
  3. E.g. when you set varchar gender is male by default in database.
  4. You just need to add insertable = false in Hibernate/JPA, it will work.

How do I indent multiple lines at once in Notepad++?

Just install the NppAutoIndent plug-in, select Plugins > NppAutoIndent > Ignore Language and then Plugins > NppAutoIndent > Smart Indent.

Horizontal swipe slider with jQuery and touch devices support?

Have you seen FlexSlider from WooThemes? I've used it on several recent projects with great success. It's touch enabled too so it will work on both mouse-based browsers as well as touch-based browsers in iOS and Android.

Space between border and content? / Border distance from content?

You usually use padding to add distance between a border and a content.However, background are spread on padding.

You can still do it with nested element.

html :

<div id="outter">
    <div id="inner">
        test
    </div>
</div>

outter div :

border-style: ridge;
border-color: #567498;
border-spacing:10px;
min-width: 100px;
min-height: 100px;
float:left;

inner div :

width: 100px;
min-height: 100px;
margin: 10px;
background-image: -webkit-gradient(
    linear,
    left bottom,
    left top,
    color-stop(0, rgb(39,54,73)),
    color-stop(1, rgb(30,42,54))
);
background-image: -moz-linear-gradient(
    center bottom,
    rgb(39,54,73) 0%,
    rgb(30,42,54) 100%
        );}

angularjs to output plain text instead of html

Use ng-bind-html this is only proper and simplest way

How to 'bulk update' with Django?

Django 2.2 version now has a bulk_update method (release notes).

https://docs.djangoproject.com/en/stable/ref/models/querysets/#bulk-update

Example:

# get a pk: record dictionary of existing records
updates = YourModel.objects.filter(...).in_bulk()
....
# do something with the updates dict
....
if hasattr(YourModel.objects, 'bulk_update') and updates:
    # Use the new method
    YourModel.objects.bulk_update(updates.values(), [list the fields to update], batch_size=100)
else:
    # The old & slow way
    with transaction.atomic():
        for obj in updates.values():
            obj.save(update_fields=[list the fields to update])

Detect change to selected date with bootstrap-datepicker

$(document).ready(function(){

$("#dateFrom").datepicker({
    todayBtn:  1,
    autoclose: true,
}).on('changeDate', function (selected) {
    var minDate = new Date(selected.date.valueOf());
    $('#dateTo').datepicker('setStartDate', minDate);
});

$("#dateTo").datepicker({
    todayBtn:  1,
    autoclose: true,}) ;

});

How to detect DataGridView CheckBox event change?

I've tried some answers from here, but I've always had some kind of problem (like double clicking or using the keyboard). So, I combined some of them and got a consistent behavior (it's not perfect, but works properly).

void gridView_CellContentClick(object sender, DataGridViewCellEventArgs e) {
  if(gridView.CurrentCell.GetType() != typeof(DataGridViewCheckBoxCell))
    return;
  if(!gridView.CurrentCell.IsInEditMode)
    return;
  if(!gridView.IsCurrentCellDirty)
    return;
  gridView.EndEdit();
}

void gridView_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e) {
  if(e.ColumnIndex == gridView.Columns["cFlag"].Index && e.RowIndex >= 0)
    gridView.EndEdit();
}

void gridView_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
  if(e.ColumnIndex != gridView.Columns["cFlag"].Index || e.RowIndex < 0)
    return;

  // Do your stuff here.

}

Given an array of numbers, return array of products of all other numbers (no division)

Here is my concise solution using python.

from functools import reduce

def excludeProductList(nums_):
    after = [reduce(lambda x, y: x*y, nums_[i:]) for i in range(1, len(nums_))] + [1]
    before = [1] + [reduce(lambda x, y: x*y, nums_[:i]) for i in range(1, len(nums_))]
    zippedList =  list(zip(before, after))
    finalList = list(map(lambda x: x[0]*x[1], zippedList))
    return finalList

How can I get form data with JavaScript/jQuery?

Here is a working JavaScript only implementation which correctly handles checkboxes, radio buttons, and sliders (probably other input types as well, but I've only tested these).

function setOrPush(target, val) {
    var result = val;
    if (target) {
        result = [target];
        result.push(val);
    }
    return result;
}

function getFormResults(formElement) {
    var formElements = formElement.elements;
    var formParams = {};
    var i = 0;
    var elem = null;
    for (i = 0; i < formElements.length; i += 1) {
        elem = formElements[i];
        switch (elem.type) {
            case 'submit':
                break;
            case 'radio':
                if (elem.checked) {
                    formParams[elem.name] = elem.value;
                }
                break;
            case 'checkbox':
                if (elem.checked) {
                    formParams[elem.name] = setOrPush(formParams[elem.name], elem.value);
                }
                break;
            default:
                formParams[elem.name] = setOrPush(formParams[elem.name], elem.value);
        }
    }
    return formParams;
}

Working example:

_x000D_
_x000D_
    function setOrPush(target, val) {_x000D_
      var result = val;_x000D_
      if (target) {_x000D_
        result = [target];_x000D_
        result.push(val);_x000D_
      }_x000D_
      return result;_x000D_
    }_x000D_
_x000D_
    function getFormResults(formElement) {_x000D_
      var formElements = formElement.elements;_x000D_
      var formParams = {};_x000D_
      var i = 0;_x000D_
      var elem = null;_x000D_
      for (i = 0; i < formElements.length; i += 1) {_x000D_
        elem = formElements[i];_x000D_
        switch (elem.type) {_x000D_
          case 'submit':_x000D_
            break;_x000D_
          case 'radio':_x000D_
            if (elem.checked) {_x000D_
              formParams[elem.name] = elem.value;_x000D_
            }_x000D_
            break;_x000D_
          case 'checkbox':_x000D_
            if (elem.checked) {_x000D_
              formParams[elem.name] = setOrPush(formParams[elem.name], elem.value);_x000D_
            }_x000D_
            break;_x000D_
          default:_x000D_
            formParams[elem.name] = setOrPush(formParams[elem.name], elem.value);_x000D_
        }_x000D_
      }_x000D_
      return formParams;_x000D_
    }_x000D_
_x000D_
    //_x000D_
    // Boilerplate for running the snippet/form_x000D_
    //_x000D_
_x000D_
    function ok() {_x000D_
      var params = getFormResults(document.getElementById('main_form'));_x000D_
      document.getElementById('results_wrapper').innerHTML = JSON.stringify(params, null, ' ');_x000D_
    }_x000D_
_x000D_
    (function() {_x000D_
      var main_form = document.getElementById('main_form');_x000D_
      main_form.addEventListener('submit', function(event) {_x000D_
        event.preventDefault();_x000D_
        ok();_x000D_
      }, false);_x000D_
    })();
_x000D_
<form id="main_form">_x000D_
  <div id="questions_wrapper">_x000D_
    <p>what is a?</p>_x000D_
    <div>_x000D_
      <input type="radio" required="" name="q_0" value="a" id="a_0">_x000D_
      <label for="a_0">a</label>_x000D_
      <input type="radio" required="" name="q_0" value="b" id="a_1">_x000D_
      <label for="a_1">b</label>_x000D_
      <input type="radio" required="" name="q_0" value="c" id="a_2">_x000D_
      <label for="a_2">c</label>_x000D_
      <input type="radio" required="" name="q_0" value="d" id="a_3">_x000D_
      <label for="a_3">d</label>_x000D_
    </div>_x000D_
    <div class="question range">_x000D_
      <label for="a_13">A?</label>_x000D_
      <input type="range" required="" name="q_3" id="a_13" min="0" max="10" step="1" list="q_3_dl">_x000D_
      <datalist id="q_3_dl">_x000D_
        <option value="0"></option>_x000D_
        <option value="1"></option>_x000D_
        <option value="2"></option>_x000D_
        <option value="3"></option>_x000D_
        <option value="4"></option>_x000D_
        <option value="5"></option>_x000D_
        <option value="6"></option>_x000D_
        <option value="7"></option>_x000D_
        <option value="8"></option>_x000D_
        <option value="9"></option>_x000D_
        <option value="10"></option>_x000D_
      </datalist>_x000D_
    </div>_x000D_
    <p>A and/or B?</p>_x000D_
    <div>_x000D_
      <input type="checkbox" name="q_4" value="A" id="a_14">_x000D_
      <label for="a_14">A</label>_x000D_
      <input type="checkbox" name="q_4" value="B" id="a_15">_x000D_
      <label for="a_15">B</label>_x000D_
    </div>_x000D_
  </div>_x000D_
  <button id="btn" type="submit">OK</button>_x000D_
</form>_x000D_
<div id="results_wrapper"></div>
_x000D_
_x000D_
_x000D_

edit:

If you're looking for a more complete implementation, then take a look at this section of the project I made this for. I'll update this question eventually with the complete solution I came up with, but maybe this will be helpful to someone.

Parsing Json rest api response in C#

Create a C# class that maps to your Json and use Newsoft JsonConvert to Deserialise it.

For example:

public Class MyResponse
{
    public Meta Meta { get; set; }
    public Response Response { get; set; }
}

How to create a String with carriage returns?

It depends on what you mean by "multiple lines". Different operating systems use different line separators.

In Java, \r is always carriage return, and \n is line feed. On Unix, just \n is enough for a newline, whereas many programs on Windows require \r\n. You can get at the platform default newline use System.getProperty("line.separator") or use String.format("%n") as mentioned in other answers.

But really, you need to know whether you're trying to produce OS-specific newlines - for example, if this is text which is going to be transmitted as part of a specific protocol, then you should see what that protocol deems to be a newline. For example, RFC 2822 defines a line separator of \r\n and this should be used even if you're running on Unix. So it's all about context.

MySQL joins and COUNT(*) from another table

Your groups_main table has a key column named id. I believe you can only use the USING syntax for the join if the groups_fans table has a key column with the same name, which it probably does not. So instead, try this:

LEFT JOIN groups_fans AS m ON m.group_id = g.id

Or replace group_id with whatever the appropriate column name is in the groups_fans table.

How can I convert a hex string to a byte array?

I think this may work.

public static byte[] StrToByteArray(string str)
    {
        Dictionary<string, byte> hexindex = new Dictionary<string, byte>();
        for (int i = 0; i <= 255; i++)
            hexindex.Add(i.ToString("X2"), (byte)i);

        List<byte> hexres = new List<byte>();
        for (int i = 0; i < str.Length; i += 2)            
            hexres.Add(hexindex[str.Substring(i, 2)]);

        return hexres.ToArray();
    }

How can I compare two strings in java and define which of them is smaller than the other alphabetically?

Haven't you heard about the Comparable interface being implemented by String ? If no, try to use

"abcda".compareTo("abcza")

And it will output a good root for a solution to your problem.

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

Loop through list with both content and index

Like everyone else:

for i, val in enumerate(data):
    print i, val

but also

for i, val in enumerate(data, 1):
    print i, val

In other words, you can specify as starting value for the index/count generated by enumerate() which comes in handy if you don't want your index to start with the default value of zero.

I was printing out lines in a file the other day and specified the starting value as 1 for enumerate(), which made more sense than 0 when displaying information about a specific line to the user.

Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone

Building on D.A.'s suggestion that "the only way to do what you want is to modify the underlying data" and using numpy to modify the underlying data...

This works for me, and is pretty fast:

def tz_to_naive(datetime_index):
    """Converts a tz-aware DatetimeIndex into a tz-naive DatetimeIndex,
    effectively baking the timezone into the internal representation.

    Parameters
    ----------
    datetime_index : pandas.DatetimeIndex, tz-aware

    Returns
    -------
    pandas.DatetimeIndex, tz-naive
    """
    # Calculate timezone offset relative to UTC
    timestamp = datetime_index[0]
    tz_offset = (timestamp.replace(tzinfo=None) - 
                 timestamp.tz_convert('UTC').replace(tzinfo=None))
    tz_offset_td64 = np.timedelta64(tz_offset)

    # Now convert to naive DatetimeIndex
    return pd.DatetimeIndex(datetime_index.values + tz_offset_td64)

$date + 1 year?

strtotime() is returning bool(false), because it can't parse the string '+one year' (it doesn't understand "one"). false is then being implicitly cast to the integer timestamp 0. It's a good idea to verify strtotime()'s output isn't bool(false) before you go shoving it in other functions.

From the docs:

Return Values

Returns a timestamp on success, FALSE otherwise. Previous to PHP 5.1.0, this function would return -1 on failure.

Auto refresh code in HTML using meta tags

<meta http-equiv="refresh" content="600; url=index.php">

600 is the amount of seconds between refresh cycles.

GetFiles with multiple extensions

You can get every file, then filter the array:

public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dirInfo, params string[] extensions)
{
    var allowedExtensions = new HashSet<string>(extensions, StringComparer.OrdinalIgnoreCase);

    return dirInfo.EnumerateFiles()
                  .Where(f => allowedExtensions.Contains(f.Extension));
}

This will be (marginally) faster than every other answer here.
In .Net 3.5, replace EnumerateFiles with GetFiles (which is slower).

And use it like this:

var files = new DirectoryInfo(...).GetFilesByExtensions(".jpg", ".mov", ".gif", ".mp4");

Get response from PHP file using AJAX

<script type="text/javascript">
        function returnwasset(){
            alert('return sent');
            $.ajax({
                type: "POST",
                url: "process.php",
                data: somedata;
                dataType:'text'; //or HTML, JSON, etc.
                success: function(response){
                    alert(response);
                    //echo what the server sent back...
                }
            });
        }
    </script>

Collections.sort with multiple fields

I had the same issue and I needed an algorithm using a config file. In This way you can use multiple fields define by a configuration file (simulate just by a List<String) config)

  public static void test() {  
    // Associate your configName with your Comparator 
    Map<String, Comparator<DocumentDto>> map = new HashMap<>();
    map.put("id", new IdSort());
    map.put("createUser", new DocumentUserSort());
    map.put("documentType", new DocumentTypeSort());
    /**
      In your config.yml file, you'll have something like
      sortlist: 
        - documentType
        - createUser
        - id
    */
    List<String> config = new ArrayList<>();
    config.add("documentType");
    config.add("createUser");
    config.add("id");
    

    List<Comparator<DocumentDto>> sorts = new ArrayList<>();

    for (String comparator : config) {
        sorts.add(map.get(comparator));
    }

    // Begin creation of the list 
    DocumentDto d1 = new DocumentDto();
    d1.setDocumentType(new DocumentTypeDto());
    d1.getDocumentType().setCode("A");
    d1.setId(1);
    d1.setCreateUser("Djory");

    DocumentDto d2 = new DocumentDto();
    d2.setDocumentType(new DocumentTypeDto());
    d2.getDocumentType().setCode("A");
    d2.setId(2);
    d2.setCreateUser("Alex");

    DocumentDto d3 = new DocumentDto();
    d3.setDocumentType(new DocumentTypeDto());
    d3.getDocumentType().setCode("A");
    d3.setId(3);
    d3.setCreateUser("Djory");

    DocumentDto d4 = new DocumentDto();
    d4.setDocumentType(new DocumentTypeDto());
    d4.getDocumentType().setCode("A");
    d4.setId(4);
    d4.setCreateUser("Alex");

    DocumentDto d5 = new DocumentDto();
    d5.setDocumentType(new DocumentTypeDto());
    d5.getDocumentType().setCode("D");
    d5.setId(5);
    d5.setCreateUser("Djory");

    DocumentDto d6 = new DocumentDto();
    d6.setDocumentType(new DocumentTypeDto());
    d6.getDocumentType().setCode("B");
    d6.setId(6);
    d6.setCreateUser("Alex");

    DocumentDto d7 = new DocumentDto();
    d7.setDocumentType(new DocumentTypeDto());
    d7.getDocumentType().setCode("B");
    d7.setId(7);
    d7.setCreateUser("Alex");

    List<DocumentDto> documents = new ArrayList<>();

    documents.add(d1);
    documents.add(d2);
    documents.add(d3);
    documents.add(d4);
    documents.add(d5);
    documents.add(d6);
    documents.add(d7);
    // End creation of the list


    // The Sort 
    Stream<DocumentDto> docStream = documents.stream();

    // we need to reverse this list in order to sort by documentType first because stream are pull-based, last sorted() will have the priority
    Collections.reverse(sorts);

    for(Comparator<DocumentDto> entitySort : sorts){
        docStream = docStream.sorted(entitySort);
    }
    documents = docStream.collect(Collectors.toList());
    // documents has been sorted has you configured
    // in case of equality second sort will be used.

    System.out.println(documents);

  }

Comparator objects are really simple.

public class IdSort implements Comparator<DocumentDto> {

    @Override
    public int compare(DocumentDto o1, DocumentDto o2) {
        return o1.getId().compareTo(o2.getId());
    }
}
public class DocumentUserSort implements Comparator<DocumentDto> {

    @Override
    public int compare(DocumentDto o1, DocumentDto o2) {
        return o1.getCreateUser().compareTo(o2.getCreateUser());
    }
}
public class DocumentTypeSort implements Comparator<DocumentDto> {

    @Override
    public int compare(DocumentDto o1, DocumentDto o2) {
        return o1.getDocumentType().getCode().compareTo(o2.getDocumentType().getCode());
    }
}

Conclusion : this method isn't has efficient but you can create generic sort using a file configuration in this way.

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

I had this issue also, I solved it instantly with this answer from a similar thread

In my case, I didn't want to delete the dependent record on key deletion. If this is the case in your situation just simply change the Boolean value in the migration to false:

AddForeignKey("dbo.Stories", "StatusId", "dbo.Status", "StatusID", cascadeDelete: false);

Chances are, if you are creating relationships which throw this compiler error but DO want to maintain cascade delete; you have an issue with your relationships.

What is a software framework?

I'm very late to answer it. But, I would like to share one example, which I only thought of today. If I told you to cut a piece of paper with dimensions 5m by 5m, then surely you would do that. But suppose I ask you to cut 1000 pieces of paper of the same dimensions. In this case, you won't do the measuring 1000 times; obviously, you would make a frame of 5m by 5m, and then with the help of it you would be able to cut 1000 pieces of paper in less time. So, what you did was make a framework which would do a specific type of task. Instead of performing the same type of task again and again for the same type of applications, you create a framework having all those facilities together in one nice packet, hence providing the abstraction for your application and more importantly many applications.

How to edit nginx.conf to increase file size upload

You can increase client_max_body_size and upload_max_filesize + post_max_size all day long. Without adjusting HTTP timeout it will never work.

//You need to adjust this, and probably on PHP side also. client_body_timeout 2min // 1GB fileupload

Select rows from a data frame based on values in a vector

Another option would be to use a keyed data.table:

library(data.table)
setDT(dt, key = 'fct')[J(vc)]  # or: setDT(dt, key = 'fct')[.(vc)]

which results in:

   fct X
1:   a 2
2:   a 7
3:   a 1
4:   c 3
5:   c 5
6:   c 9
7:   c 2
8:   c 4

What this does:

  • setDT(dt, key = 'fct') transforms the data.frame to a data.table (which is an enhanced form of a data.frame) with the fct column set as key.
  • Next you can just subset with the vc vector with [J(vc)].

NOTE: when the key is a factor/character variable, you can also use setDT(dt, key = 'fct')[vc] but that won't work when vc is a numeric vector. When vc is a numeric vector and is not wrapped in J() or .(), vc will work as a rowindex.

A more detailed explanation of the concept of keys and subsetting can be found in the vignette Keys and fast binary search based subset.

An alternative as suggested by @Frank in the comments:

setDT(dt)[J(vc), on=.(fct)]

When vc contains values that are not present in dt, you'll need to add nomatch = 0:

setDT(dt, key = 'fct')[J(vc), nomatch = 0]

or:

setDT(dt)[J(vc), on=.(fct), nomatch = 0]

Replace string in text file using PHP

This works like a charm, fast and accurate:

function replace_string_in_file($filename, $string_to_replace, $replace_with){
    $content=file_get_contents($filename);
    $content_chunks=explode($string_to_replace, $content);
    $content=implode($replace_with, $content_chunks);
    file_put_contents($filename, $content);
}

Usage:

$filename="users/data/letter.txt";
$string_to_replace="US$";
$replace_with="Yuan";
replace_string_in_file($filename, $string_to_replace, $replace_with);

// never forget about EXPLODE when it comes about string parsing // it's a powerful and fast tool

What is Turing Complete?

Here is the simplest explanation

Alan Turing created a machine that can take a program, run that program, and show some result. But then he had to create different machines for different programs. So he created "Universal Turing Machine" that can take ANY program and run it.

Programming languages are similar to those machines (although virtual). They take programs and run them. Now, a programing language is called "Turing complete", if it can run any program (irrespective of the language) that a Turing machine can run given enough time and memory.

For example: Let's say there is a program that takes 10 numbers and adds them. A Turing machine can easily run this program. But now imagine that for some reason your programming language can't perform the same addition. This would make it "Turing incomplete" (so to speak). On the other hand, if it can run any program that the universal Turing machine can run, then it's Turing complete.

Most modern programming languages (e.g. Java, JavaScript, Perl, etc.) are all Turing complete because they each implement all the features required to run programs like addition, multiplication, if-else condition, return statements, ways to store/retrieve/erase data and so on.

Update: You can learn more on my blog post: "JavaScript Is Turing Complete" — Explained

SQL Server NOLOCK and joins

Neither. You set the isolation level to READ UNCOMMITTED which is always better than giving individual lock hints. Or, better still, if you care about details like consistency, use snapshot isolation.

VBA macro that search for file in multiple subfolders

This sub will populate a Collection with all files matching the filename or pattern you pass in.

Sub GetFiles(StartFolder As String, Pattern As String, _
             DoSubfolders As Boolean, ByRef colFiles As Collection)

    Dim f As String, sf As String, subF As New Collection, s
    
    If Right(StartFolder, 1) <> "\" Then StartFolder = StartFolder & "\"
    
    f = Dir(StartFolder & Pattern)
    Do While Len(f) > 0
        colFiles.Add StartFolder & f
        f = Dir()
    Loop
    
    If DoSubfolders then
        sf = Dir(StartFolder, vbDirectory)
        Do While Len(sf) > 0
            If sf <> "." And sf <> ".." Then
                If (GetAttr(StartFolder & sf) And vbDirectory) <> 0 Then
                        subF.Add StartFolder & sf
                End If
            End If
            sf = Dir()
        Loop
    
        For Each s In subF
            GetFiles CStr(s), Pattern, True, colFiles
        Next s
    End If

End Sub

Usage:

Dim colFiles As New Collection

GetFiles "C:\Users\Marek\Desktop\Makro\", FName & ".xls", True, colFiles
If colFiles.Count > 0 Then
    'work with found files
End If

Adding onClick event dynamically using jQuery

$("#bfCaptchaEntry").click(function(){
    myFunction();
});

How to find Current open Cursors in Oracle

This could work:

SELECT    sql_text "SQL Query", 
          Count(*) AS "Open Cursors" 
FROM      v$open_cursor 
GROUP BY  sql_text 
HAVING    Count(*) > 2 
ORDER BY  Count(*) DESC; 

ExpressJS How to structure an application?

I don't think it's a good approach to add routes to config. A better structure could be something like this:

application/
| - app.js
| - config.js
| - public/ (assets - js, css, images)
| - views/ (all your views files)
| - libraries/ (you can also call it modules/ or routes/)
    | - users.js
    | - products.js
    | - etc...

So products.js and users.js will contain all your routes will all logic within.

Can't connect to MySQL server on 'localhost' (10061) after Installation

I also faced the same issue and resolved it by below setups:

  1. Check the MYSQL service in the windows service. If it is there and not running then start it. It will solve your problem.

    You can find the services window by navigating to windows Start menu and typing 'services' in the search bar. Select the 'Services' option with the cogs next to it (not the executable file) and the below window will appear. Scroll down to find 'MySql (version)'. When you select MySql you should see an option in the left pane that says 'Start the service'. Click this and a dialogue should appear to indicate Windows is attempting to start the service. Once started the left pane will now give you the option to stop, pause and restart the service and you will now be able to connect to your MySql from the windows cmd line.

enter image description here

  1. If MYSQL service is not present in windows service then follow below setups.

    a. Open cmd as administrator.

    b. cd to C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin

    c. Run the command: C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin>mysqld.exe --install

    d. Check the MySql in the windows service, And if it is not running, Start it by clicking on the service.

    e. If your using XAMMP . Start MySQL at the XAMMP control Panel.


How to open a second activity on click of button in android app

From Activity : where you are currently ?

To Activity : where you want to go ?

Intent i = new Intent( MainActivity.this, SendPhotos.class); startActivity(i);

Both Activity must be included in manifest file otherwise it will not found the class file and throw Force close.

Edit your Mainactivity.java

crate button's object;

now Write code for click event.

        Button btn = (button)findViewById(R.id.button1);
         btn.LoginButton.setOnClickListener(new View.OnClickListener() 
       {

                @Override
                public void onClick(View v) 
                {
                 //put your intent code here
                }
   });

Hope it will work for you.

List All Google Map Marker Images

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(12, 18)
);

Unable to read repository at http://download.eclipse.org/releases/indigo

Also try if in the eclipse paths there is some duplicated
Luna - http://download.eclipse.org/releases/luna
Luna - http://download.eclipse.org/releases/luna/1234567...

Try both of them, one may work.

In my case, with 2 eclispes installed, in one of them the path
Luna - http://download.eclipse.org/releases/luna

works, in the other one, i must select:
Luna - http://download.eclipse.org/releases/luna/123456...

In both the internal browser can access to internet. Both are Luna (but one is RCM, the other one i don't remember).

Re-ordering factor levels in data frame

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))

Page vs Window in WPF?

Page Control can be contained in Window Control but vice versa is not possible

You can use Page control within the Window control using NavigationWindow and Frame controls. Window is the root control that must be used to hold/host other controls (e.g. Button) as container. Page is a control which can be hosted in other container controls like NavigationWindow or Frame. Page control has its own goal to serve like other controls (e.g. Button). Page is to create browser like applications. So if you host Page in NavigationWindow, you will get the navigation implementation built-in. Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer).

WPF provides support for browser style navigation inside standalone application using Page class. User can create multiple pages, navigate between those pages along with data.There are multiple ways available to Navigate through one page to another page.

How to elegantly check if a number is within a range?

Regarding elegance, the closest thing to the mathematical notation (a <= x <= b) slightly improves readability:

public static bool IsBetween(this int value, int min, int max)
{
    return min <= value && value <= max;
}

For further illustration:

public static bool IsOutside(this int value, int min, int max)
{
    return value < min || max < value;
}

jQuery - Add active class and remove active from other element on click

You can remove class active from all .tab and use $(this) to target current clicked .tab:

$(document).ready(function() {
    $(".tab").click(function () {
        $(".tab").removeClass("active");
        $(this).addClass("active");     
    });
});

Your code won't work because after removing class active from all .tab, you also add class active to all .tab again. So you need to use $(this) instead of $('.tab') to add the class active only to the clicked .tab anchor

Updated Fiddle

cleanest way to skip a foreach if array is empty

$items = array('a','b','c');

if(is_array($items)) {
  foreach($items as $item) {
    print $item;
  }
}

How to convert a char array to a string?

There is a small problem missed in top-voted answers. Namely, character array may contain 0. If we will use constructor with single parameter as pointed above we will lose some data. The possible solution is:

cout << string("123\0 123") << endl;
cout << string("123\0 123", 8) << endl;

Output is:

123
123 123

Convert Time DataType into AM PM Format:

Try this:

select CONVERT(varchar(15),CAST('2014-05-28 16:07:54.647' AS TIME),100) as CreatedTime

Python: PIP install path, what is the correct location for this and other addons?

Modules go in site-packages and executables go in your system's executable path. For your environment, this path is /usr/local/bin/.

To avoid having to deal with this, simply use easy_install, distribute or pip. These tools know which files need to go where.

Which loop is faster, while or for?

I find the fastest loop is a reverse while loop, e.g:

var i = myArray.length;
while(i--){
  // Do something
}

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

in SQL*Plus you could also use a REFCURSOR variable:

SQL> VARIABLE x REFCURSOR
SQL> DECLARE
  2   V_Sqlstatement Varchar2(2000);
  3  BEGIN
  4   V_Sqlstatement := 'SELECT * FROM DUAL';
  5   OPEN :x for v_Sqlstatement;
  6  End;
  7  /

ProcÚdure PL/SQL terminÚe avec succÞs.

SQL> print x;

D
-
X

Terminating idle mysql connections

I don't see any problem, unless you are not managing them using a connection pool.

If you use connection pool, these connections are re-used instead of initiating new connections. so basically, leaving open connections and re-use them it is less problematic than re-creating them each time.

How to search contents of multiple pdf files?

Recoll is a fantastic full-text GUI search application for Unix/Linux that supports dozens of different formats, including PDF. It can even pass the exact page number and search term of a query to the document viewer and thus allows you to jump to the result right from its GUI.

Recoll also comes with a viable command-line interface and a web-browser interface.

How can you get the Manifest Version number from the App's (Layout) XML variables?

I believe that was already answered here.

String versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;

OR

int versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;

Java: Multiple class declarations in one file

According to Effective Java 2nd edition (Item 13):

"If a package-private top-level class (or interface) is used by only one class, consider making the top-level class a private nested class of the sole class that uses it (Item 22). This reduces its accessibility from all the classes in its package to the one class that uses it. But it is far more important to reduce the accessibility of a gratuitously public class than a package-private top-level class: ... "

The nested class may be static or non-static based on whether the member class needs access to the enclosing instance (Item 22).

Writing to a new file if it doesn't exist, and appending to a file if it does

Using the pathlib module (python's object-oriented filesystem paths)

Just for kicks, this is perhaps the latest pythonic version of the solution.

from pathlib import Path 

path = Path(f'{player}.txt')
path.touch()  # default exists_ok=True
with path.open('a') as highscore:
   highscore.write(f'Username:{player}')

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

We can use ng-src but when ng-src's value became null, '' or undefined, ng-src will not work. So just use ng-if for this case:

http://jsfiddle.net/Hx7B9/299/

<div ng-app>
    <div ng-controller="AppCtrl"> 
        <a href='#'><img ng-src="{{link}}" ng-if="!!link"/></a>
        <button ng-click="changeLink()">Change Image</button>
    </div>
</div>

How do I connect to a Websphere Datasource with a given JNDI name?

Find below code to get database connection from your web app server. Just create datasource in app server and use following code to get connection :

// To Get DataSource
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("jdbc/abcd");
// Get Connection and Statement
Connection c = ds.getConnection();
stmt = c.createStatement();

Import naming and sql classes. No need to add any xml file or to edit anything in project.
That's it..

How do I read image data from a URL in Python?

For those doing some sklearn/numpy post processing (i.e. Deep learning) you can wrap the PIL object with np.array(). This might save you from having to Google it like I did:

from PIL import Image
import requests
import numpy as np
from StringIO import StringIO

response = requests.get(url)
img = np.array(Image.open(StringIO(response.content)))

SQL Server JOIN missing NULL values

You can be explicit about the joins:

SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 INNER JOIN
     Table2
      ON (Table1.Col1 = Table2.Col1 or Table1.Col1 is NULL and Table2.Col1 is NULL) AND
         (Table1.Col2 = Table2.Col2 or Table1.Col2 is NULL and Table2.Col2 is NULL)

In practice, I would be more likely to use coalesce() in the join condition:

SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 INNER JOIN
     Table2
     ON (coalesce(Table1.Col1, '') = coalesce(Table2.Col1, '')) AND
        (coalesce(Table1.Col2, '') = coalesce(Table2.Col2, ''))

Where '' would be a value not in either of the tables.

Just a word of caution. In most databases, using any of these constructs prevents the use of indexes.

How do I find the absolute position of an element using jQuery?

.offset() will return the offset position of an element as a simple object, eg:

var position = $(element).offset(); // position = { left: 42, top: 567 }

You can use this return value to position other elements at the same spot:

$(anotherElement).css(position)

Create listview in fragment android

The inflate() method takes three parameters:

  1. The id of a layout XML file (inside R.layout),
  2. A parent ViewGroup into which the fragment's View is to be inserted,

  3. A third boolean telling whether the fragment's View as inflated from the layout XML file should be inserted into the parent ViewGroup.

In this case we pass false because the View will be attached to the parent ViewGroup elsewhere, by some of the Android code we call (in other words, behind our backs). When you pass false as last parameter to inflate(), the parent ViewGroup is still used for layout calculations of the inflated View, so you cannot pass null as parent ViewGroup .

 View rootView = inflater.inflate(R.layout.fragment_photos, container, false);

So, You need to call rootView in here

ListView lv = (ListView)rootView.findViewById(R.id.lv_contact);

Spring MVC Multipart Request with JSON

This must work!

client (angular):

$scope.saveForm = function () {
      var formData = new FormData();
      var file = $scope.myFile;
      var json = $scope.myJson;
      formData.append("file", file);
      formData.append("ad",JSON.stringify(json));//important: convert to JSON!
      var req = {
        url: '/upload',
        method: 'POST',
        headers: {'Content-Type': undefined},
        data: formData,
        transformRequest: function (data, headersGetterFunction) {
          return data;
        }
      };

Backend-Spring Boot:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public @ResponseBody
    Advertisement storeAd(@RequestPart("ad") String adString, @RequestPart("file") MultipartFile file) throws IOException {

        Advertisement jsonAd = new ObjectMapper().readValue(adString, Advertisement.class);
//do whatever you want with your file and jsonAd

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

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

What properties can I use with event.target?

event.target returns the node that was targeted by the function. This means you can do anything you want to do with any other node like one you'd get from document.getElementById

I'm tried with jQuery

var _target = e.target;
console.log(_target.attr('href'));

Return an error :

.attr not function

But _target.attributes.href.value was works.

How do I include a pipe | in my linux find -exec command?

You can also pipe to a while loop that can do multiple actions on the file which find locates. So here is one for looking in jar archives for a given java class file in folder with a large distro of jar files

find /usr/lib/eclipse/plugins -type f -name \*.jar | while read jar; do echo $jar; jar tf $jar | fgrep IObservableList ; done

the key point being that the while loop contains multiple commands referencing the passed in file name separated by semicolon and these commands can include pipes. So in that example I echo the name of the matching file then list what is in the archive filtering for a given class name. The output looks like:

/usr/lib/eclipse/plugins/org.eclipse.core.contenttype.source_3.4.1.R35x_v20090826-0451.jar /usr/lib/eclipse/plugins/org.eclipse.core.databinding.observable_1.2.0.M20090902-0800.jar org/eclipse/core/databinding/observable/list/IObservableList.class /usr/lib/eclipse/plugins/org.eclipse.search.source_3.5.1.r351_v20090708-0800.jar /usr/lib/eclipse/plugins/org.eclipse.jdt.apt.core.source_3.3.202.R35x_v20091130-2300.jar /usr/lib/eclipse/plugins/org.eclipse.cvs.source_1.0.400.v201002111343.jar /usr/lib/eclipse/plugins/org.eclipse.help.appserver_3.1.400.v20090429_1800.jar

in my bash shell (xubuntu10.04/xfce) it really does make the matched classname bold as the fgrep highlights the matched string; this makes it really easy to scan down the list of hundreds of jar files that were searched and easily see any matches.

on windows you can do the same thing with:

for /R %j in (*.jar) do @echo %j & @jar tf %j | findstr IObservableList

note that in that on windows the command separator is '&' not ';' and that the '@' suppresses the echo of the command to give a tidy output just like the linux find output above; although findstr is not make the matched string bold so you have to look a bit closer at the output to see the matched class name. It turns out that the windows 'for' command knows quite a few tricks such as looping through text files...

enjoy

How to write both h1 and h2 in the same line?

h1 and h2 are native display: block elements.

Make them display: inline so they behave like normal text.

You should also reset the default padding and margin that the elements have.

How to clear the cache in NetBeans

tl;dr You might not need to whack your entire NetBeans cache.


My problem manifested as running a clean build didn't delete the previous build folder or testuserdir folder, while I was using NetBeans 8.0.2.

The first time I had this problem, Ray Slater's answer above helped me immensely. I had two Project Groups, and had to close each project in both groups, close NetBeans, clear the cache, then add my projects back to my groups before it would work again.

Later, this problem cropped up again with NetBeans 8.1. I closed NetBeans, and ran ant build clean at the command line, and it worked. When I reopened NetBeans, the problem was resolved. It occurs to me that NetBeans was keeping something open and just needed to be closed in order to delete the folders.


Update
I finally figured out what was going on. Somehow, my NetBeans "Module Suite Project" (yellow/orange puzzle pieces icon) had been closed and the "Module Project" (purple puzzle piece icon) having the same exact name as the "Module Suite Project" was open. Building clean cleaned that particular Project correctly, but did not clean the entire Suite.

Now that I have the "Module Suite Project" opened correctly again, things work as expected. This explains why ant build clean worked, since it was done on the command line at the right level to clean the whole Suite.

I suspect I didn't strictly need to clean out my NetBeans cache at all though perhaps doing so actually fixed the issue of why it was only showing the "Module Project" instead of the "Module Suite Project", thereby doing the right thing when I clicked build clean... If I had simply realized that the Suite was no longer open and only the Project was, I could have fixed it in three seconds.

How can I increase the size of a bootstrap button?

You can try to use btn-sm, btn-xs and btn-lg classes like this:

.btn-xl {
    padding: 10px 20px;
    font-size: 20px;
    border-radius: 10px;
}

JSFIDDLE DEMO

You can make use of Bootstrap .btn-group-justified css class. Or you can simply add:

.btn-xl {
    padding: 10px 20px;
    font-size: 20px;
    border-radius: 10px;
    width:50%;    //Specify your width here
}

JSFIDDLE DEMO

Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers

For Nginx, the only thing that worked for me was adding this header:

add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';

Along with the Access-Control-Allow-Origin header:

add_header 'Access-Control-Allow-Origin' '*';

Then reloaded the nginx config and it worked great. Credit https://gist.github.com/algal/5480916.

Get Value of Row in Datatable c#

Dont use a foreach then. Use a 'for loop'. Your code is a bit messed up but you could do something like...

for (Int32 i = 0; i < dt_pattern.Rows.Count; i++)
{
    double yATmax = ToDouble(dt_pattern.Rows[i+1]["Ampl"].ToString()) + AT;
}

Note you would have to take into account during the last row there will be no 'i+1' so you will have to use an if statement to catch that.

VBoxManage: error: Failed to create the host-only adapter

I fixed this error by installing VirtualBox 4.2 instead of 4.3. I think the latest version of vagrant and VB 4.3 are incompatible on a fedora system.

How can I get a JavaScript stack trace when I throw an exception?

In Firefox it seems that you don't need to throw the exception. It's sufficient to do

e = new Error();
console.log(e.stack);

How to exit an if clause

The only thing that would apply this without additional methods is elif as the following example

a = ['yearly', 'monthly', 'quartly', 'semiannual', 'monthly', 'quartly', 'semiannual', 'yearly']
# start the condition
if 'monthly' in b: 
    print('monthly') 
elif 'quartly' in b: 
    print('quartly') 
elif 'semiannual' in b: 
    print('semiannual') 
elif 'yearly' in b: 
    print('yearly') 
else: 
    print('final') 

Changing java platform on which netbeans runs

on Fedora it is currently impossible to set a new jdk-HOME to some sdk. They designed it such that it will always break. Try --jdkhome [whatever] but in all likelihood it will break and show some cryptic nonsensical error message as usual.

How to change the URI (URL) for a remote Git repository?

git remote set-url {name} {url}

ex) git remote set-url origin https://github.com/myName/GitTest.git

Get cursor position (in characters) within a text Input field

_x000D_
_x000D_
const inpT = document.getElementById("text-box");_x000D_
const inpC = document.getElementById("text-box-content");_x000D_
// swch gets  inputs ._x000D_
var swch;_x000D_
// swch  if corsur is active in inputs defaulte is false ._x000D_
var isSelect = false;_x000D_
_x000D_
var crnselect;_x000D_
// on focus_x000D_
function setSwitch(e) {_x000D_
  swch = e;_x000D_
  isSelect = true;_x000D_
  console.log("set Switch: " + isSelect);_x000D_
}_x000D_
// on click ev_x000D_
function setEmoji() {_x000D_
  if (isSelect) {_x000D_
    console.log("emoji added :)");_x000D_
    swch.value += ":)";_x000D_
    swch.setSelectionRange(2,2 );_x000D_
    isSelect = true;_x000D_
  }_x000D_
_x000D_
}_x000D_
// on not selected on input . _x000D_
function onout() {_x000D_
  // ??????  ??? ?? ?? _x000D_
  crnselect = inpC.selectionStart;_x000D_
  _x000D_
  // return input select not active after 200 ms ._x000D_
  var len = swch.value.length;_x000D_
  setTimeout(() => {_x000D_
   (len == swch.value.length)? isSelect = false:isSelect = true;_x000D_
  }, 200);_x000D_
}
_x000D_
<h1> Try it !</h1>_x000D_
    _x000D_
  <input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box" size="20" value="title">_x000D_
  <input type="text" onfocus = "setSwitch(this)"  onfocusout = "onout()"  id="text-box-content" size="20" value="content">_x000D_
<button onclick="setEmoji()">emogi :) </button>
_x000D_
_x000D_
_x000D_

Most efficient way to concatenate strings?

Try this 2 pieces of code and you will find the solution.

 static void Main(string[] args)
    {
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < 10000000; i++)
        {
            s.Append( i.ToString());
        }
        Console.Write("End");
        Console.Read();
    }

Vs

static void Main(string[] args)
    {
        string s = "";
        for (int i = 0; i < 10000000; i++)
        {
            s += i.ToString();
        }
        Console.Write("End");
        Console.Read();
    }

You will find that 1st code will end really quick and the memory will be in a good amount.

The second code maybe the memory will be ok, but it will take longer... much longer. So if you have an application for a lot of users and you need speed, use the 1st. If you have an app for a short term one user app, maybe you can use both or the 2nd will be more "natural" for developers.

Cheers.

Triangle Draw Method

There is not a drawTriangle method neither in Graphics nor Graphics2D. You need to do it by yourself. You can draw three lines using the drawLine method or use one these methods:

These methods work with polygons. You may change the prefix draw to fill when you want to fill the polygon defined by the point set. I inserted the documentation links. Take a look to learn how to use them.

There is the GeneralPath class too. It can be used with Graphics2D, which is capable to draw Shapes. Take a look:

FileNotFoundException while getting the InputStream object from HttpURLConnection

To anyone with this problem in the future, the reason is because the status code was a 404 (or in my case was a 500). It appears the InpuStream function will throw an error when the status code is not 200.

In my case I control my own server and was returning a 500 status code to indicate an error occurred. Despite me also sending a body with a string message detailing the error, the inputstream threw an error regardless of the body being completely readable.

If you control your server I suppose this can be handled by sending yourself a 200 status code and then handling whatever the string error response was.

Check if SQL Connection is Open or Closed

To check OleDbConnection State use this:

if (oconn.State == ConnectionState.Open)
{
    oconn.Close();
}

State return the ConnectionState

public override ConnectionState State { get; }

Here are the other ConnectionState enum

public enum ConnectionState
    {
        //
        // Summary:
        //     The connection is closed.
        Closed = 0,
        //
        // Summary:
        //     The connection is open.
        Open = 1,
        //
        // Summary:
        //     The connection object is connecting to the data source. (This value is reserved
        //     for future versions of the product.)
        Connecting = 2,
        //
        // Summary:
        //     The connection object is executing a command. (This value is reserved for future
        //     versions of the product.)
        Executing = 4,
        //
        // Summary:
        //     The connection object is retrieving data. (This value is reserved for future
        //     versions of the product.)
        Fetching = 8,
        //
        // Summary:
        //     The connection to the data source is broken. This can occur only after the connection
        //     has been opened. A connection in this state may be closed and then re-opened.
        //     (This value is reserved for future versions of the product.)
        Broken = 16
    }

How to get past the login page with Wget?

I had the same problem. My solution was to do the login via Chrome and save the cookies data to a text file. This is easily done with this Chrome extension: Chrome cookie.txt export extension.

When you get the cookies data, there is also an example on how to use them with wget. A simple copy-paste command line is provided to you.

How to order results with findBy() in Doctrine

The second parameter of findBy is for ORDER.

$ens = $em->getRepository('AcmeBinBundle:Marks')
          ->findBy(
             array('type'=> 'C12'), 
             array('id' => 'ASC')
           );

enum Values to NSString (iOS)

Below is a example of Enum Struct that is Objective-C friendly in the event you need to use Swift Code in Legacy projects written in Objective-C.

Example:

contentType.filename. toString()

returns "filename"


contentType.filename. rawValue

returns the Int Value, 1 (since its the second item on struct)

@objc enum contentType:Int {

    //date when content was created [RFC2183]
    case creationDate

    //name to be used when creating file    [RFC2183]
    case filename

    //whether or not processing is required [RFC3204]
    case handling

    //date when content was last modified   [RFC2183]
    case modificationDate

    //original field name in form   [RFC7578]
    case name

    //Internet media type (and parameters) of the preview output desired from a processor by the author of the MIME content [RFC-ietf-appsawg-text-markdown-12]
    case previewType

    //date when content was last read   [RFC2183]
    case readDate

    //approximate size of content in octets [RFC2183]
    case size

    //type or use of audio content  [RFC2421]
    case voice

    func toString() -> String {
        switch self {
        case .creationDate:
            return "creation-date"
        case .filename:
            return "filename"
        case .handling:
            return "handling"
        case .modificationDate:
            return "modification-date"
        case .name:
            return "name"
        case .previewType:
            return "preview-type"
        case .readDate:
                return "read-date"
        case .size:
            return "size"
        case .voice:
            return "voice"
        }
    }//eom
}//eo-enum

How to make the background image to fit into the whole page without repeating using plain css?

These three line all together worked for me.

background-image: url("pages/images/backImage.png");
background-size: 100%;
background-repeat: no-repeat;

Is it really impossible to make a div fit its size to its content?

You can use:

width: -webkit-fit-content;
height: -webkit-fit-content;
width: -moz-fit-content;
height: -moz-fit-content;

EDIT: No. see http://red-team-design.com/horizontal-centering-using-css-fit-content-value/

ALSO: http://dev.w3.org/csswg/css-box-3/

CSS-moving text from left to right

I like using the following to prevent things being outside my div elements. It helps with CSS rollovers too.

.marquee{
    overflow:hidden;
}

this will hide anything that moves/is outside of the div which will prevent the browser expanding and causing a scroll bar to appear.

MySQL my.cnf performance tuning recommendations

Try starting with the Percona wizard and comparing their recommendations against your current settings one by one. Don't worry there aren't as many applicable settings as you might think.

https://tools.percona.com/wizard

Update circa 2020: Sorry, this tool reached it's end of life: https://www.percona.com/blog/2019/04/22/end-of-life-query-analyzer-and-mysql-configuration-generator/

Everyone points to key_buffer_size first which you have addressed. With 96GB memory I'd be wary of any tiny default value (likely to be only 96M!).

"Cannot verify access to path (C:\inetpub\wwwroot)", when adding a virtual directory

I have the same problem and the solution was uncheck the "use ports 80 and 443" on skype advanced configuration!

Proper way to initialize C++ structs

That seems to me the easiest way. Structure members can be initialized using curly braces ‘{}’. For example, following is a valid initialization.

struct Point 
{ 
   int x, y; 
};  

int main() 
{ 
   // A valid initialization. member x gets value 0 and y 
   // gets value 1.  The order of declaration is followed. 
   struct Point p1 = {0, 1};  
}

There is good information about structs in c++ - https://www.geeksforgeeks.org/structures-in-cpp/

Why does this CSS margin-top style not work?

Create new block formatting context

You can use display: flow-root on the parent element to prevent margin collapsing through the containing element as it creates new Block Formatting Context.

Changing the value of the overflow property to auto or using flexbox will have the same effect.

https://codepen.io/rachelandrew/pen/VJXjEp

Remove quotes from a character vector in R

Easiest way is :

> a = "some string"
> write(a, stdout())  # Can specify stderr() also.
some string

Gives you the option to print to stderr if you're doing some error handling printing.

Multi-dimensional associative arrays in JavaScript

Get the value for an array of associative arrays's property when the property name is an integer:

Starting with an Associative Array where the property names are integers:

var categories = [
    {"1":"Category 1"},
    {"2":"Category 2"},
    {"3":"Category 3"},
    {"4":"Category 4"}
];

Push items to the array:

categories.push({"2300": "Category 2300"});
categories.push({"2301": "Category 2301"});

Loop through array and do something with the property value.

for (var i = 0; i < categories.length; i++) {
    for (var categoryid in categories[i]) {
        var category = categories[i][categoryid];
        // log progress to the console
        console.log(categoryid + " : " + category);
        //  ... do something
    }
}

Console output should look like this:

1 : Category 1
2 : Category 2
3 : Category 3
4 : Category 4
2300 : Category 2300
2301 : Category 2301

As you can see, you can get around the associative array limitation and have a property name be an integer.

NOTE: The associative array in my example is the json you would have if you serialized a Dictionary[] object.

How to determine the version of Gradle?

2019-05-08 Android Studios needs an upgrade. upgrade Android Studios to 3.3.- and the error with .R; goes away.

Also the above methods also work.

Using GregorianCalendar with SimpleDateFormat

tl;dr

LocalDate.parse(
    "23-Mar-2017" ,
    DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US ) 
)

Avoid legacy date-time classes

The Question and other Answers are now outdated, using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

Using java.time

You seem to be dealing with date-only values. So do not use a date-time class. Instead use LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.

Specify a Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.

Parse a string.

String input = "23-Mar-2017" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( input , f );

Generate a string.

String output = ld.format( f );

If you were given numbers rather than text for the year, month, and day-of-month, use LocalDate.of.

LocalDate ld = LocalDate.of( 2017 , 3 , 23 );  // ( year , month 1-12 , day-of-month )

See this code run live at IdeOne.com.

input: 23-Mar-2017

ld.toString(): 2017-03-23

output: 23-Mar-2017


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Reordering arrays

Immutable version, no side effects (doesn’t mutate original array):

const testArr = [1, 2, 3, 4, 5];

function move(from, to, arr) {
    const newArr = [...arr];

    const item = newArr.splice(from, 1)[0];
    newArr.splice(to, 0, item);

    return newArr;
}

console.log(move(3, 1, testArr));

// [1, 4, 2, 3, 5]

codepen: https://codepen.io/mliq/pen/KKNyJZr

Android Studio AVD - Emulator: Process finished with exit code 1

Sometimes things need a system restart (in my case).

How to debug Ruby scripts

I just discovered this gem ( turns Pry into a debugger for MRI Ruby 2.0+ )

https://github.com/deivid-rodriguez/pry-byebug

Install with:

gem install pry-byebug

then use exactly like pry, mark the line you want to break at:

require 'pry'; binding.pry

Unlike vanilla pry however, this gem has some key GDB-like navigation commands such as next, step and break:

break SomeClass#run            # Break at the start of `SomeClass#run`.
break Foo#bar if baz?          # Break at `Foo#bar` only if `baz?`.
break app/models/user.rb:15    # Break at line 15 in user.rb.
break 14                       # Break at line 14 in the current file.

No Activity found to handle Intent : android.intent.action.VIEW

I have two ideas:

First: if you want to play 3gp file you should use mime types "audio/3gpp" or "audio/mpeg"

And second: you can try use method setData(data) for intent without any mime type.

Django request get parameters

You can use [] to extract values from a QueryDict object like you would any ordinary dictionary.

# HTTP POST variables
request.POST['section'] # => [39]
request.POST['MAINS'] # => [137]

# HTTP GET variables
request.GET['section'] # => [39]
request.GET['MAINS'] # => [137]

# HTTP POST and HTTP GET variables (Deprecated since Django 1.7)
request.REQUEST['section'] # => [39]
request.REQUEST['MAINS'] # => [137]

How to find the 'sizeof' (a pointer pointing to an array)?

int main() 
{
    int days[] = {1,2,3,4,5};
    int *ptr = days;
    printf("%u\n", sizeof(days));
    printf("%u\n", sizeof(ptr));

    return 0;
}

Size of days[] is 20 which is no of elements * size of it's data type. While the size of pointer is 4 no matter what it is pointing to. Because a pointer points to other element by storing it's address.

PHP cURL HTTP PUT

Just been doing that myself today... here is code I have working for me...

$data = array("a" => $a);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));

$response = curl_exec($ch);

if (!$response) 
{
    return false;
}

src: http://www.lornajane.net/posts/2009/putting-data-fields-with-php-curl

Comparing two arrays of objects, and exclude the elements who match values into new array in JS

well, this using lodash or vanilla javascript it depends on the situation.

but for just return the array that contains the duplicates it can be achieved by the following, offcourse it was taken from @1983

var result = result1.filter(function (o1) {
    return result2.some(function (o2) {
        return o1.id === o2.id; // return the ones with equal id
   });
});
// if you want to be more clever...
let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));

How to remove the default link color of the html hyperlink 'a' tag?

I had this challenge when I was working on a Rails 6 application using Bootstrap 4.

My challenge was that I didn't want this styling to override the default link styling in the application.

So I created a CSS file called custom.css or custom.scss.

And then defined a new CSS rule with the following properties:

.remove_link_colour {
  a, a:hover, a:focus, a:active {
      color: inherit;
      text-decoration: none;
  }
}

Then I called this rule wherever I needed to override the default link styling.

<div class="product-card__buttons">
  <button class="btn btn-success remove_link_colour" type="button"><%= link_to 'Edit', edit_product_path(product) %></button>
  <button class="btn btn-danger remove_link_colour" type="button"><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %></button>
</div>

This solves the issue of overriding the default link styling and removes the default colour, hover, focus, and active styling in the buttons only in places where I call the CSS rule.

That's all.

I hope this helps

Convert nested Python dict to object?

I know there's already a lot of answers here already and I'm late to the party but this method will recursively and 'in place' convert a dictionary to an object-like structure... Works in 3.x.x

def dictToObject(d):
    for k,v in d.items():
        if isinstance(v, dict):
            d[k] = dictToObject(v)
    return namedtuple('object', d.keys())(*d.values())

# Dictionary created from JSON file
d = {
    'primaryKey': 'id', 
    'metadata': 
        {
            'rows': 0, 
            'lastID': 0
        }, 
    'columns': 
        {
            'col2': {
                'dataType': 'string', 
                'name': 'addressLine1'
            }, 
            'col1': {
                'datatype': 'string', 
                'name': 'postcode'
            }, 
            'col3': {
                'dataType': 'string', 
                'name': 'addressLine2'
            }, 
            'col0': {
                'datatype': 'integer', 
                'name': 'id'
            }, 
            'col4': {
                'dataType': 'string', 
                'name': 'contactNumber'
            }
        }, 
        'secondaryKeys': {}
}

d1 = dictToObject(d)
d1.columns.col1 # == object(datatype='string', name='postcode')
d1.metadata.rows # == 0

CSS: How to position two elements on top of each other, without specifying a height?

Due to absolute positioning removing the elements from the document flow position: absolute is not the right tool for the job. Depending on the exact layout you want to create you will be successful using negative margins, position:relative or maybe even transform: translate. Show us a sample of what you want to do we can help you better.

Reload an iframe with jQuery

If you are cross-domain, simply setting the src back to the same url will not always trigger a reload, even if the location hash changes.

Ran into this problem while manually constructing Twitter button iframes, which wouldn't refresh when I updated the urls.

Twitter like buttons have the form: .../tweet_button.html#&_version=2&count=none&etc=...

Since Twitter uses the document fragment for the url, changing the hash/fragment didn't reload the source, and the button targets didn't reflect my new ajax-loaded content.

You can append a query string parameter for force the reload (eg: "?_=" + Math.random() but that will waste bandwidth, especially in this example where Twitter's approach was specifically trying to enable caching.

To reload something which only changes with hash tags, you need to remove the element, or change the src, wait for the thread to exit, then assign it back. If the page is still cached, this shouldn't require a network hit, but does trigger the frame reload.

 var old = iframe.src;
 iframe.src = '';
 setTimeout( function () {
    iframe.src = old;
 }, 0);

Update: Using this approach creates unwanted history items. Instead, remove and recreate the iframe element each time, which keeps this back() button working as expected. Also nice not to have the timer.

CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

According to the GNU make manual:

CFLAGS: Extra flags to give to the C compiler.
CXXFLAGS: Extra flags to give to the C++ compiler.
CPPFLAGS: Extra flags to give to the C preprocessor and programs that use it (the C and Fortran compilers).

src: https://www.gnu.org/software/make/manual/make.html#index-CFLAGS
note: PP stands for PreProcessor (and not Plus Plus), i.e.

CPP: Program for running the C preprocessor, with results to standard output; default ‘$(CC) -E’.

These variables are used by the implicit rules of make

Compiling C programs
n.o is made automatically from n.c with a recipe of the form
‘$(CC) $(CPPFLAGS) $(CFLAGS) -c’.

Compiling C++ programs
n.o is made automatically from n.cc, n.cpp, or n.C with a recipe of the form
‘$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c’.
We encourage you to use the suffix ‘.cc’ for C++ source files instead of ‘.C’.

src: https://www.gnu.org/software/make/manual/make.html#Catalogue-of-Rules

Trees in Twitter Bootstrap

For those still searching for a tree with CSS3, this is a fantastic piece of code I found on the net:

http://thecodeplayer.com/walkthrough/css3-family-tree

HTML

<div class="tree">
  <ul>
    <li>
      <a href="#">Parent</a>
      <ul>
        <li>
          <a href="#">Child</a>
          <ul>
            <li>
              <a href="#">Grand Child</a>
            </li>
          </ul>
        </li>
        <li>
          <a href="#">Child</a>
          <ul>
            <li><a href="#">Grand Child</a></li>
            <li>
              <a href="#">Grand Child</a>
              <ul>
                <li>
                  <a href="#">Great Grand Child</a>
                </li>
                <li>
                  <a href="#">Great Grand Child</a>
                </li>
                <li>
                  <a href="#">Great Grand Child</a>
                </li>
              </ul>
            </li>
            <li><a href="#">Grand Child</a></li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</div>

CSS

* {margin: 0; padding: 0;}

.tree ul {
  padding-top: 20px; position: relative;

  transition: all 0.5s;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
}

.tree li {
  float: left; text-align: center;
  list-style-type: none;
  position: relative;
  padding: 20px 5px 0 5px;

  transition: all 0.5s;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
}

/*We will use ::before and ::after to draw the connectors*/

.tree li::before, .tree li::after{
  content: '';
  position: absolute; top: 0; right: 50%;
  border-top: 1px solid #ccc;
  width: 50%; height: 20px;
}
.tree li::after{
  right: auto; left: 50%;
  border-left: 1px solid #ccc;
}

/*We need to remove left-right connectors from elements without 
any siblings*/
.tree li:only-child::after, .tree li:only-child::before {
  display: none;
}

/*Remove space from the top of single children*/
.tree li:only-child{ padding-top: 0;}

/*Remove left connector from first child and 
right connector from last child*/
.tree li:first-child::before, .tree li:last-child::after{
  border: 0 none;
}
/*Adding back the vertical connector to the last nodes*/
.tree li:last-child::before{
  border-right: 1px solid #ccc;
  border-radius: 0 5px 0 0;
  -webkit-border-radius: 0 5px 0 0;
  -moz-border-radius: 0 5px 0 0;
}
.tree li:first-child::after{
  border-radius: 5px 0 0 0;
  -webkit-border-radius: 5px 0 0 0;
  -moz-border-radius: 5px 0 0 0;
}

/*Time to add downward connectors from parents*/
.tree ul ul::before{
  content: '';
  position: absolute; top: 0; left: 50%;
  border-left: 1px solid #ccc;
  width: 0; height: 20px;
}

.tree li a{
  border: 1px solid #ccc;
  padding: 5px 10px;
  text-decoration: none;
  color: #666;
  font-family: arial, verdana, tahoma;
  font-size: 11px;
  display: inline-block;

  border-radius: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;

  transition: all 0.5s;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
}

/*Time for some hover effects*/
/*We will apply the hover effect the the lineage of the element also*/
.tree li a:hover, .tree li a:hover+ul li a {
  background: #c8e4f8; color: #000; border: 1px solid #94a0b4;
}
/*Connector styles on hover*/
.tree li a:hover+ul li::after, 
.tree li a:hover+ul li::before, 
.tree li a:hover+ul::before, 
.tree li a:hover+ul ul::before{
  border-color:  #94a0b4;
}

PS: apart from the code, I also like the way the site shows it in action... really innovative.

Parse an URL in JavaScript

One liner:

location.search.replace('?','').split('&').reduce(function(s,c){var t=c.split('=');s[t[0]]=t[1];return s;},{})

differences in application/json and application/x-www-form-urlencoded

webRequest.ContentType = "application/x-www-form-urlencoded";

  1. Where does application/x-www-form-urlencoded's name come from?

    If you send HTTP GET request, you can use query parameters as follows:

    http://example.com/path/to/page?name=ferret&color=purple

    The content of the fields is encoded as a query string. The application/x-www-form- urlencoded's name come from the previous url query parameter but the query parameters is in where the body of request instead of url.

    The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character

    e.g. field1=value1&field2=value2

  2. It can be simple request called simple - don't trigger a preflight check

    Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests

    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.

request.ContentType = "application/json; charset=utf-8";

  1. The data will be json format.

axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.

{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    "Bar",
    "Eek"
  ],
  "stock": {
    "warehouse": 300,
    "retail": 20
  }
}
  1. "application/json" Content-Type is one of the Preflighted requests.

Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.

  1. application/json is beginner-friendly. URL encoded arrays can be a nightmare!

How to align flexbox columns left and right?

I came up with 4 methods to achieve the results. Here is demo

Method 1:

#a {
    margin-right: auto;
}

Method 2:

#a {
    flex-grow: 1;
}

Method 3:

#b {
    margin-left: auto;
}

Method 4:

#container {
    justify-content: space-between;
}

Get Insert Statement for existing row in MySQL

I wrote a php function that will do this. I needed to make an insert statement in case a record needs to be replaced after deletion for a history table:

function makeRecoverySQL($table, $id)
{
    // get the record          
    $selectSQL = "SELECT * FROM `" . $table . "` WHERE `id` = " . $id . ';';

    $result = mysql_query($selectSQL, $YourDbHandle);
    $row = mysql_fetch_assoc($result); 

    $insertSQL = "INSERT INTO `" . $table . "` SET ";
    foreach ($row as $field => $value) {
        $insertSQL .= " `" . $field . "` = '" . $value . "', ";
    }
    $insertSQL = trim($insertSQL, ", ");

    return $insertSQL;
}

Iterate through string array in Java

You have to maintain the serial how many times you are accessing the array.Use like this

int lookUpTime=0;

    for(int i=lookUpTime;i<lookUpTime+2 && i<elements.length();i++)
     {
    // do something with elements[i]
    }

lookUpTime++;

C# HttpClient 4.5 multipart/form-data upload

Here is another example on how to use HttpClient to upload a multipart/form-data.

It uploads a file to a REST API and includes the file itself (e.g. a JPG) and additional API parameters. The file is directly uploaded from local disk via FileStream.

See here for the full example including additional API specific logic.

public static async Task UploadFileAsync(string token, string path, string channels)
{
    // we need to send a request with multipart/form-data
    var multiForm = new MultipartFormDataContent();

    // add API method parameters
    multiForm.Add(new StringContent(token), "token");
    multiForm.Add(new StringContent(channels), "channels");

    // add file and directly upload it
    FileStream fs = File.OpenRead(path);
    multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(path));

    // send request to API
    var url = "https://slack.com/api/files.upload";
    var response = await client.PostAsync(url, multiForm);
}

What does asterisk * mean in Python?

A single star means that the variable 'a' will be a tuple of extra parameters that were supplied to the function. The double star means the variable 'kw' will be a variable-size dictionary of extra parameters that were supplied with keywords.

Although the actual behavior is spec'd out, it still sometimes can be very non-intuitive. Writing some sample functions and calling them with various parameter styles may help you understand what is allowed and what the results are.

def f0(a)
def f1(*a)
def f2(**a)
def f3(*a, **b)
etc...

PHP - add 1 day to date format mm-dd-yyyy

$date = DateTime::createFromFormat('m-d-Y', '04-15-2013');
$date->modify('+1 day');
echo $date->format('m-d-Y');

See it in action

Or in PHP 5.4+

echo (DateTime::createFromFormat('m-d-Y', '04-15-2013'))->modify('+1 day')->format('m-d-Y');

reference

How to disable javax.swing.JButton in java?

The code is very long so I can't paste all the code.

There could be any number of reasons why your code doesn't work. Maybe you declared the button variables twice so you aren't actually changing enabling/disabling the button like you think you are. Maybe you are blocking the EDT.

You need to create a SSCCE to post on the forum.

So its up to you to isolate the problem. Start with a simple frame thas two buttons and see if your code works. Once you get that working, then try starting a Thread that simply sleeps for 10 seconds to see if it still works.

Learn how the basice work first before writing a 200 line program.

Learn how to do some basic debugging, we are not mind readers. We can't guess what silly mistake you are doing based on your verbal description of the problem.

How to open a new HTML page using jQuery?

use window.open("file2.html"); to open on new window,

or use window.location.href = "file2.html" to open on same window.

Check if inputs form are empty jQuery

var empty = true;
$('input[type="text"]').each(function() {
   if ($(this).val() != "") {
      empty = false;
      return false;
   }
});

This should look all the input and set the empty var to false, if at least one is not empty.

EDIT:

To match the OP edit request, this can be used to filter input based on name substring.

$('input[name*="denominationcomune_"]').each(...

Find the 2nd largest element in an array with minimum number of comparisons

Sort the array into ascending order then assign a variable to the (n-1)th term.

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

I have the same error I was replacing my Set with a new one get from Jackson.

To solve this I keep the existing set, I remove from the old set the element unknown into the new list with retainAll. Then I add the new ones with addAll.

    this.oldSet.retainAll(newSet);
    this.oldSet.addAll(newSet);

No need to have the Session and manipulate it.