Programs & Examples On #Asp.net 3.5

asp.net-3.5 is the 3.5 version of web development framework asp.net, part of .Net. It features: ASP.NET AJAX as a part of the runtime, new LINQ data capabilities, improved support for CSS.

How to initialize a list with constructor?

Using a collection initializer

From C# 3, you can use collection initializers to construct a List and populate it using a single expression. The following example constructs a Human and its ContactNumbers:

var human = new Human(1, "Address", "Name") {
    ContactNumbers = new List<ContactNumber>() {
        new ContactNumber(1),
        new ContactNumber(2),
        new ContactNumber(3)
    }
}

Specializing the Human constructor

You can change the constructor of the Human class to provide a way to populate the ContactNumbers property:

public class Human
{
    public Human(int id, string address, string name, IEnumerable<ContactNumber> contactNumbers) : this(id, address, name)
    {
        ContactNumbers = new List<ContactNumber>(contactNumbers);
    }

    public Human(int id, string address, string name, params ContactNumber[] contactNumbers) : this(id, address, name)
    {
        ContactNumbers = new List<ContactNumber>(contactNumbers);
    }
}

// Using the first constructor:
List<ContactNumber> numbers = List<ContactNumber>() {
    new ContactNumber(1),
    new ContactNumber(2),
    new ContactNumber(3)
};

var human = new Human(1, "Address", "Name", numbers);

// Using the second constructor:
var human = new Human(1, "Address", "Name",
    new ContactNumber(1),
    new ContactNumber(2),
    new ContactNumber(3)
);

Bottom line

Which alternative is a best practice? Or at least a good practice? You judge it! IMO, the best practice is to write the program as clearly as possible to anyone who has to read it. Using the collection initializer is a winner for me, in this case. With much less code, it can do almost the same things as the alternatives -- at least, the alternatives I gave...

Convert a string to a datetime

Try to see if the following code helps you:

Dim iDate As String = "05/05/2005"
Dim oDate As DateTime = Convert.ToDateTime(iDate)

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

The ideal scenario is to have <add value="default.aspx" /> in config so the application can be deployed to any server without having to reconfigure. IMHO I think the implementation within IIS is poor.

We've used the following to make our default document setup more robust and as a result more SEO friendly by using canonical URL's:

<configuration>
  <system.webServer>
    <defaultDocument>
      <files>
        <remove value="default.aspx" />
        <add value="default.aspx" />
      </files>
    </defaultDocument>
  </system.webServer>
</configuration>

Works OK for us.

Unable to convert MySQL date/time value to System.DateTime

if "allow zero datetime=true" is not working then use the following sollutions:-

Add this to your connection string: "allow zero datetime=no" - that made the type cast work perfectly.

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

I've added upon the code submitted by jSnake04 and Dasun herein. I've added code to create lists of objects from JArray instances. It has two-way recursion but as it is functioning on a fixed, finite tree model, there is no risk of stack overflow unless the data is massive.

/// <summary>
/// Deserialize the given JSON string data (<paramref name="data"/>) into a
///   dictionary.
/// </summary>
/// <param name="data">JSON string.</param>
/// <returns>Deserialized dictionary.</returns>
private IDictionary<string, object> DeserializeData(string data)
{
    var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(data);

    return DeserializeData(values);
}

/// <summary>
/// Deserialize the given JSON object (<paramref name="data"/>) into a dictionary.
/// </summary>
/// <param name="data">JSON object.</param>
/// <returns>Deserialized dictionary.</returns>
private IDictionary<string, object> DeserializeData(JObject data)
{
    var dict = data.ToObject<Dictionary<String, Object>>();

    return DeserializeData(dict);
}

/// <summary>
/// Deserialize any elements of the given data dictionary (<paramref name="data"/>) 
///   that are JSON object or JSON arrays into dictionaries or lists respectively.
/// </summary>
/// <param name="data">Data dictionary.</param>
/// <returns>Deserialized dictionary.</returns>
private IDictionary<string, object> DeserializeData(IDictionary<string, object> data)
{
    foreach (var key in data.Keys.ToArray()) 
    {
        var value = data[key];

        if (value is JObject)
            data[key] = DeserializeData(value as JObject);

        if (value is JArray)
            data[key] = DeserializeData(value as JArray);
    }

    return data;
}

/// <summary>
/// Deserialize the given JSON array (<paramref name="data"/>) into a list.
/// </summary>
/// <param name="data">Data dictionary.</param>
/// <returns>Deserialized list.</returns>
private IList<Object> DeserializeData(JArray data)
{
    var list = data.ToObject<List<Object>>();

    for (int i = 0; i < list.Count; i++)
    {
        var value = list[i];

        if (value is JObject)
            list[i] = DeserializeData(value as JObject);

        if (value is JArray)
            list[i] = DeserializeData(value as JArray);
    }

    return list;
}

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

It's because there's no symlinks for libpng. You need to link libpng again.

brew unlink libpng && brew link libpng

And you may get some error. I fixed that error by correcting permission. Maybe it's because of uninstalled macports.

sudo chown -R yourid:staff /usr/local/share/man/

Create link again and it'll work.

Using Thymeleaf when the value is null

This can also be handled using the elvis operator ?: which will add a default value when the field is null:

<span th:text="${object.property} ?: 'default value'"></span>

C++ - How to append a char to char*?

Remove those char * ret declarations inside if blocks which hide outer ret. Therefor you have memory leak and on the other hand un-allocated memory for ret.

To compare a c-style string you should use strcmp(array,"") not array!="". Your final code should looks like below:

char* appendCharToCharArray(char* array, char a)
{
    size_t len = strlen(array);

    char* ret = new char[len+2];

    strcpy(ret, array);    
    ret[len] = a;
    ret[len+1] = '\0';

    return ret;
}

Note that, you must handle the allocated memory of returned ret somewhere by delete[] it.

 

Why you don't use std::string? it has .append method to append a character at the end of a string:

std::string str;

str.append('x');
// or
str += x;

Mockito: Inject real objects into private @Autowired fields

In Addition to @Dev Blanked answer, if you want to use an existing bean that was created by Spring the code can be modified to:

@RunWith(MockitoJUnitRunner.class)
public class DemoTest {

    @Inject
    private ApplicationContext ctx;

    @Spy
    private SomeService service;

    @InjectMocks
    private Demo demo;

    @Before
    public void setUp(){
        service = ctx.getBean(SomeService.class);
    }

    /* ... */
}

This way you don't need to change your code (add another constructor) just to make the tests work.

Exporting PDF with jspdf not rendering CSS

To remove black background only add background-color: white; to the style of

How to change the height of a div dynamically based on another div using css?

#container-of-boxes {
    display: table;
    width: 1158px;
}
#box-1 {
    width: 578px;
}
#box-2 {
    width: 386px;
}
#box-3 {
    width: 194px;
}
#box-1, #box-2, #box-3 {
    min-height: 210px;
    padding-bottom: 20px;
    display: table-cell;
    height: auto;
    overflow: hidden;
}
  • The container must have display:table
  • The boxes inside container must be: display:table-cell
  • Don't put floats.

Can I run HTML files directly from GitHub, instead of just viewing their source?

To piggyback on @niutech's answer, you can make a very simple bookmark snippet.
Using Chrome, though it works similarly with other browsers

  1. Right click your bookmark bar
  2. Click Add File
  3. Name it something like Github HTML
  4. For the URL type javascript:top.location="http://htmlpreview.github.com/?"+document.URL
  5. When you're on a github file view page (not raw.github.com) click the bookmark link and you're golden.

How do I discard unstaged changes in Git?

If all the staged files were actually committed, then the branch can simply be reset e.g. from your GUI with about three mouse clicks: Branch, Reset, Yes!

So what I often do in practice to revert unwanted local changes is to commit all the good stuff, and then reset the branch.

If the good stuff is committed in a single commit, then you can use "amend last commit" to bring it back to being staged or unstaged if you'd ultimately like to commit it a little differently.

This might not be the technical solution you are looking for to your problem, but I find it a very practical solution. It allows you to discard unstaged changes selectively, resetting the changes you don't like and keeping the ones you do.

So in summary, I simply do commit, branch reset, and amend last commit.

Python dict how to create key or append an element to key?

dictionary['key'] = dictionary.get('key', []) + list_to_append

Running bash script from within python

Actually, you just have to add the shell=True argument:

subprocess.call("sleep.sh", shell=True)

But beware -

Warning Invoking the system shell with shell=True can be a security hazard if combined with untrusted input. See the warning under Frequently Used Arguments for details.

source

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

Proceed following steps at ubuntu-18.04:

Step 1) locate sql.lib.php

It will show something like:

/usr/share/phpmyadmin/libraries/sql.lib.php

Step 2) Open terminal (Alt t) and write:

sudo /usr/sbin/pma-configure

Step 3)sudo gedit /usr/share/phpmyadmin/libraries/sql.lib.php and search below function:

 

    function PMA_isRememberSortingOrder($analyzed_sql_results)
     {
        return $GLOBALS['cfg']['RememberSorting']
            && ! ($analyzed_sql_results['is_count']
                || $analyzed_sql_results['is_export']
                || $analyzed_sql_results['is_func']
                || $analyzed_sql_results['is_analyse'])
            && $analyzed_sql_results['select_from']
            && ((empty($analyzed_sql_results['select_expr']))
                || (count($analyzed_sql_results['select_expr'] == 1)
                    && ($analyzed_sql_results['select_expr'][0] == '*')))
            && count($analyzed_sql_results['select_tables']) == 1;
     }

Step 4) Replace above function with:


     function PMA_isRememberSortingOrder($analyzed_sql_results)
     {
        return $GLOBALS['cfg']['RememberSorting']
            && ! ($analyzed_sql_results['is_count']
                || $analyzed_sql_results['is_export']
                || $analyzed_sql_results['is_func']
                || $analyzed_sql_results['is_analyse'])
            && $analyzed_sql_results['select_from']
            && ((empty($analyzed_sql_results['select_expr']))
                || (count($analyzed_sql_results['select_expr']) == 1)
                    && ($analyzed_sql_results['select_expr'][0] == '*'))
            && count($analyzed_sql_results['select_tables']) == 1;
     }

Step 4) Save & close file and below command on terminal

sudo /usr/sbin/pma-secure

Step 5) sudo service mysql reload

Step 6) sudo service apache2 reload

It works for me.. Goodluck

Declaring an enum within a class

I prefer following approach (code below). It solves the "namespace pollution" problem, but also it is much more typesafe (you can't assign and even compare two different enumerations, or your enumeration with any other built-in types etc).

struct Color
{
    enum Type
    {
        Red, Green, Black
    };
    Type t_;
    Color(Type t) : t_(t) {}
    operator Type () const {return t_;}
private:
   //prevent automatic conversion for any other built-in types such as bool, int, etc
   template<typename T>
    operator T () const;
};

Usage:

Color c = Color::Red;
switch(c)
{
   case Color::Red:
     //????????? ???
   break;
}
Color2 c2 = Color2::Green;
c2 = c; //error
c2 = 3; //error
if (c2 == Color::Red ) {} //error
If (c2) {} error

I create macro to facilitate usage:

#define DEFINE_SIMPLE_ENUM(EnumName, seq) \
struct EnumName {\
   enum type \
   { \
      BOOST_PP_SEQ_FOR_EACH_I(DEFINE_SIMPLE_ENUM_VAL, EnumName, seq)\
   }; \
   type v; \
   EnumName(type v) : v(v) {} \
   operator type() const {return v;} \
private: \
    template<typename T> \
    operator T () const;};\

#define DEFINE_SIMPLE_ENUM_VAL(r, data, i, record) \
    BOOST_PP_TUPLE_ELEM(2, 0, record) = BOOST_PP_TUPLE_ELEM(2, 1, record),

Usage:

DEFINE_SIMPLE_ENUM(Color,
             ((Red, 1))
             ((Green, 3))
             )

Some references:

  1. Herb Sutter, Jum Hyslop, C/C++ Users Journal, 22(5), May 2004
  2. Herb Sutter, David E. Miller, Bjarne Stroustrup Strongly Typed Enums (revision 3), July 2007

Command failed due to signal: Segmentation fault: 11

For anyone else coming across this... I found the issue was caused by importing a custom framework, I have no idea how to correct it. But simply removing the import and any code referencing items from the framework fixes the issue.

(?°?°)?? ???

Hope this can save someone a few hours chasing down which line is causing the issue.

Group By Eloquent ORM

Laravel 5

This is working for me (i use laravel 5.6).

$collection = MyModel::all()->groupBy('column');

If you want to convert the collection to plain php array, you can use toArray()

$array = MyModel::all()->groupBy('column')->toArray();

How do I resolve `The following packages have unmet dependencies`

I just solved this issue. The problem was in version conflict. Nodejs 10 installed with npm. So before installing nodejs - remove old npm. Or remove new node -> remove npm -> install node again.

This is the only way which helped me.

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

Enable cross-origin requests in ASP.NET Web API click for more info

Enable CORS in the WebService app. First, add the CORS NuGet package. In Visual Studio, from the Tools menu, select NuGet Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:

Install-Package Microsoft.AspNet.WebApi.Cors

This command installs the latest package and updates all dependencies, including the core Web API libraries. Use the -Version flag to target a specific version. The CORS package requires Web API 2.0 or later.

Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method:

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Next, add the [EnableCors] attribute to your controller/ controller methods

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebService.Controllers
{
    [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }
}

Enable Cross-Origin Requests (CORS) in ASP.NET Core

How can I make visible an invisible control with jquery? (hide and show not work)

You can't do this with jQuery, visible="false" in asp.net means the control isn't rendered into the page. If you want the control to go to the client, you need to do style="display: none;" so it's actually in the HTML, otherwise there's literally nothing for the client to show, since the element wasn't in the HTML your server sent.

If you remove the visible attribute and add the style attribute you can then use jQuery to show it, like this:

$("#elementID").show();

Old Answer (before patrick's catch)

To change visibility, you need to use .css(), like this:

$("#elem").css('visibility', 'visible');

Unless you need to have the element occupy page space though, use display: none; instead of visibility: hidden; in your CSS, then just do:

$("#elem").show();

The .show() and .hide() functions deal with display instead of visibility, like most of the jQuery functions :)

Floating Point Exception C++ Why and what is it?

A "floating point number" is how computers usually represent numbers that are not integers -- basically, a number with a decimal point. In C++ you declare them with float instead of int. A floating point exception is an error that occurs when you try to do something impossible with a floating point number, such as divide by zero.

Invoke a second script with arguments from a script

You can execute it same as SQL query. first, build your command/Expression and store in a variable and execute/invoke.

$command =  ".\yourExternalScriptFile.ps1" + " -param1 '$paramValue'"

It is pretty forward, I don't think it needs explanations. So all set to execute your command now,

Invoke-Expression $command

I would recommend catching the exception here

"Use the new keyword if hiding was intended" warning

In the code below, Class A implements the interface IShow and implements its method ShowData. Class B inherits Class A. In order to use ShowData method in Class B, we have to use keyword new in the ShowData method in order to hide the base class Class A method and use override keyword in order to extend the method.

interface IShow
{
    protected void ShowData();
}

class A : IShow
{
    protected void ShowData()
    {
        Console.WriteLine("This is Class A");
    }
}

class B : A
{
    protected new void ShowData()
    {
        Console.WriteLine("This is Class B");
    }
}

JavaScript override methods

_x000D_
_x000D_
function A() {_x000D_
    var c = new C();_x000D_
 c.modify = function(){_x000D_
  c.x = 123;_x000D_
  c.y = 333;_x000D_
 }_x000D_
 c.sum();_x000D_
}_x000D_
_x000D_
function B() {_x000D_
    var c = new C();_x000D_
 c.modify = function(){_x000D_
  c.x = 999;_x000D_
  c.y = 333;_x000D_
 }_x000D_
 c.sum();_x000D_
}_x000D_
_x000D_
_x000D_
C = function () {_x000D_
   this.x = 10;_x000D_
   this.y = 20;_x000D_
_x000D_
   this.modify = function() {_x000D_
      this.x = 30;_x000D_
      this.y = 40;_x000D_
   };_x000D_
   _x000D_
   this.sum = function(){_x000D_
 this.modify();_x000D_
 console.log("The sum is: " + (this.x+this.y));_x000D_
   }_x000D_
}_x000D_
_x000D_
A();_x000D_
B();
_x000D_
_x000D_
_x000D_

Change MySQL default character set to UTF-8 in my.cnf?

To set the default to UTF-8, you want to add the following to my.cnf/my.ini

[client]
default-character-set=utf8mb4

[mysql]
default-character-set=utf8mb4


[mysqld]
collation-server = utf8mb4_unicode_520_ci
init-connect='SET NAMES utf8mb4'
character-set-server = utf8mb4

If you want to change the character set for an existing DB, let me know... your question didn't specify it directly so I am not sure if that's what you want to do.

Edit: I replaced utf8 with utf8mb4 in the original answer due to utf8 only being a subset of UTF-8. MySQL and MariaDB both call UTF-8 utf8mb4.

Run parallel multiple commands at once in the same terminal

I am suggesting a much simpler utility I just wrote. It's currently called par, but will be renamed soon to either parl or pll, haven't decided yet.

https://github.com/k-bx/par

API is as simple as:

par "script1.sh" "script2.sh" "script3.sh"

Prefixing commands can be done via:

par "PARPREFIX=[script1] script1.sh" "script2.sh" "script3.sh"

Bootstrap radio button "checked" flag

In case you want to use bootstrap radio to check one of them depends on the result of your checked var in the .ts file.

component.html

<h1>Radio Group #1</h1>
<div class="btn-group btn-group-toggle" data-toggle="buttons" >
   <label [ngClass]="checked ? 'active' : ''" class="btn btn-outline-secondary">
     <input name="radio" id="radio1" value="option1" type="radio"> TRUE
   </label>
   <label [ngClass]="!checked ? 'active' : ''" class="btn btn-outline-secondary">
     <input name="radio" id="radio2" value="option2" type="radio"> FALSE
   </label>
</div>

component.ts file

@Component({
  selector: '',
  templateUrl: './.component.html',
  styleUrls: ['./.component.css']
})
export class radioComponent implements OnInit {
  checked = true;
}

git: diff between file in local repo and origin

I tried a couple of solution but I thing easy way like this (you are in the local folder):

#!/bin/bash
git fetch

var_local=`cat .git/refs/heads/master`
var_remote=`git log origin/master -1 | head -n1 | cut -d" " -f2`

if [ "$var_remote" = "$var_local" ]; then
    echo "Strings are equal." #1
else
    echo "Strings are not equal." #0 if you want
fi

Then you did compare local git and remote git last commit number....

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

Return value from nested function in Javascript

Just FYI, Geocoder is asynchronous so the accepted answer while logical doesn't really work in this instance. I would prefer to have an outside object that acts as your updater.

var updater = {};

function geoCodeCity(goocoord) { 
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        'latLng': goocoord
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            updater.currentLocation = results[1].formatted_address;
        } else {
            if (status == "ERROR") { 
                    console.log(status);
                }
        }
    });
};

python filter list of dictionaries based on key value

Use filter, or if the number of dictionaries in exampleSet is too high, use ifilter of the itertools module. It would return an iterator, instead of filling up your system's memory with the entire list at once:

from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
    print elem

How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

Attempting to provide a concise update, based on Enzero's answer.

  • Install the Bootstrap.Datepicker package.

    PM> install-package Bootstrap.Datepicker
    ...
    Successfully installed 'Bootstrap.Datepicker 1.7.1' to ...
    
  • In AppStart/BundleConfig.cs, add the related scripts and styles in the bundles.

    bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
          //...,
          "~/Scripts/bootstrap-datepicker.js",
          "~/Scripts/locales/bootstrap-datepicker.YOUR-LOCALE-CODE-HERE.min.js"));
    
    bundles.Add(new StyleBundle("~/Content/css").Include(
          ...,
          "~/Content/bootstrap-datepicker3.css"));
    
  • In the related view, in the scripts' section, enable and customize datepicker.

    @section scripts{
        <script type="text/javascript">
            //...
            $('.datepicker').datepicker({
                format: 'dd/mm/yyyy', //choose the date format you prefer
                language: "YOUR-LOCALE-CODE-HERE",
                orientation: 'left bottom'
            });
        </script>
    
  • Eventually add the datepicker class in the related control. For instance, in a TextBox and for a date format in the like of "31/12/2018" this would be:

    @Html.TextBox("YOUR-STRING-FOR-THE-DATE", "{0:dd/MM/yyyy}", new { @class = "datepicker" })
    

You have not accepted the license agreements of the following SDK components

In linux

 1. Open a terminal
 2. Write: "cd $ANDROID_HOME/tools/bin (this path can be /home/your-user/Android/Sdk/tools/bin)"
 3. Write: "./sdkmanager --licenses"
 4. To accept All licenses listed, write: "y"
 5. Ready!

If your are building an app with Ionic Framework, just write again the command to build it.

Convert laravel object to array

If you want to get only ID in array, can use array_map:

    $data = array_map(function($object){
        return $object->ID;
    }, $data);

With that, return an array with ID in every pos.

How do I encode URI parameter values?

Jersey's UriBuilder encodes URI components using application/x-www-form-urlencoded and RFC 3986 as needed. According to the Javadoc

Builder methods perform contextual encoding of characters not permitted in the corresponding URI component following the rules of the application/x-www-form-urlencoded media type for query parameters and RFC 3986 for all other components. Note that only characters not permitted in a particular component are subject to encoding so, e.g., a path supplied to one of the path methods may contain matrix parameters or multiple path segments since the separators are legal characters and will not be encoded. Percent encoded values are also recognized where allowed and will not be double encoded.

Printing one character at a time from a string, using the while loop

Other answers have already given you the code you need to iterate though a string using a while loop (or a for loop) but I thought it might be useful to explain the difference between the two types of loops.

while loops repeat some code until a certain condition is met. For example:

import random

sum = 0
while sum < 100:
    sum += random.randint(0,100) #add a random number between 0 and 100 to the sum
    print sum

This code will keep adding random numbers between 0 and 100 until the total is greater or equal to 100. The important point is that this loop could run exactly once (if the first random number is 100) or it could run forever (if it keeps selecting 0 as the random number). We can't predict how many times the loop will run until after it completes.

for loops are basically just while loops but we use them when we want a loop to run a preset number of times. Java for loops usually use some sort of a counter variable (below I use i), and generally makes the similarity between while and for loops much more explicit.

for (int i=0; i < 10; i++) { //starting from 0, until i is 10, adding 1 each iteration
    System.out.println(i);
}

This loop will run exactly 10 times. This is just a nicer way to write this:

int i = 0;
while (i < 10) { //until i is 10
   System.out.println(i);
   i++; //add one to i 
}

The most common usage for a for loop is to iterate though a list (or a string), which Python makes very easy:

for item in myList:
    print item

or

for character in myString:
    print character

However, you didn't want to use a for loop. In that case, you'll need to look at each character using its index. Like this:

print myString[0] #print the first character
print myString[len(myString) - 1] # print the last character.

Knowing that you can make a for loop using only a while loop and a counter and knowing that you can access individual characters by index, it should now be easy to access each character one at a time using a while loop.

HOWEVER in general you'd use a for loop in this situation because it's easier to read.

Remove local git tags that are no longer on the remote repository

TortoiseGit can compare tags now.

Left log is on remote, right is at local.

enter image description here

Using the Compare tags feature of Sync dialog:

enter image description here

Also see TortoiseGit issue 2973

How to create empty constructor for data class in Kotlin Android

You have 2 options here:

  1. Assign a default value to each primary constructor parameter:

    data class Activity(
        var updated_on: String = "",
        var tags: List<String> = emptyList(),
        var description: String = "",
        var user_id: List<Int> = emptyList(),
        var status_id: Int = -1,
        var title: String = "",
        var created_at: String = "",
        var data: HashMap<*, *> = hashMapOf<Any, Any>(),
        var id: Int = -1,
        var counts: LinkedTreeMap<*, *> = LinkedTreeMap<Any, Any>()
    ) 
    
  2. Declare a secondary constructor that has no parameters:

    data class Activity(
        var updated_on: String,
        var tags: List<String>,
        var description: String,
        var user_id: List<Int>,
        var status_id: Int,
        var title: String,
        var created_at: String,
        var data: HashMap<*, *>,
        var id: Int,
        var counts: LinkedTreeMap<*, *>
    ) {
        constructor() : this("", emptyList(), 
                             "", emptyList(), -1, 
                             "", "", hashMapOf<Any, Any>(), 
                             -1, LinkedTreeMap<Any, Any>()
                             )
    }
    

If you don't rely on copy or equals of the Activity class or don't use the autogenerated data class methods at all you could use regular class like so:

class ActivityDto {
    var updated_on: String = "",
    var tags: List<String> = emptyList(),
    var description: String = "",
    var user_id: List<Int> = emptyList(),
    var status_id: Int = -1,
    var title: String = "",
    var created_at: String = "",
    var data: HashMap<*, *> = hashMapOf<Any, Any>(),
    var id: Int = -1,
    var counts: LinkedTreeMap<*, *> = LinkedTreeMap<Any, Any>()
}

Not every DTO needs to be a data class and vice versa. In fact in my experience I find data classes to be particularly useful in areas that involve some complex business logic.

What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors

Don't know if this will be everybody's answer, but after some digging, here's what we came up with.

The error is obviously caused by the fact that the listener was not accepting connections, but why would we get that error when other tests could connect fine (we could also connect no problem through sqlplus)? The key to the issue wasn't that we couldn't connect, but that it was intermittent

After some investigation, we found that there was some static data created during the class setup that would keep open connections for the life of the test class, creating new ones as it went. Now, even though all of the resources were properly released when this class went out of scope (via a finally{} block, of course), there were some cases during the run when this class would swallow up all available connections (okay, bad practice alert - this was unit test code that connected directly rather than using a pool, so the same problem could not happen in production).

The fix was to not make that class static and run in the class setup, but instead use it in the per method setUp and tearDown methods.

So if you get this error in your own apps, slap a profiler on that bad boy and see if you might have a connection leak. Hope that helps.

How to get a date in YYYY-MM-DD format from a TSQL datetime field?

If you want to use it as a date instead of a varchar again afterwards, don't forget to convert it back:

select convert(datetime,CONVERT(char(10), GetDate(),126))

bash: mkvirtualenv: command not found

On Windows 7 and Git Bash this helps me:

  1. Create a ~/.bashrc file (under your user home folder)
  2. Add line export WORKON_HOME=$HOME/.virtualenvs (you must create this folder if it doesn't exist)
  3. Add line source "C:\Program Files (x86)\Python36-32\Scripts\virtualenvwrapper.sh" (change path for your virtualenvwrapper.sh)

Restart your git bash and mkvirtualenv command now will work nicely.

How to hash a string into 8 digits?

I am sharing our nodejs implementation of the solution as implemented by @Raymond Hettinger.

var crypto = require('crypto');
var s = 'she sells sea shells by the sea shore';
console.log(BigInt('0x' + crypto.createHash('sha1').update(s).digest('hex'))%(10n ** 8n));

Developing C# on Linux

Mono Develop is what you want, if you have used visual studio you should find it simple enough to get started.

If I recall correctly you should be able to install with sudo apt-get install monodevelop

When to use HashMap over LinkedList or ArrayList and vice-versa

I will put here some real case examples and scenarios when to use one or another, it might be of help for somebody else:

HashMap

When you have to use cache in your application. Redis and membase are some type of extended HashMap. (Doesn't matter the order of the elements, you need quick ( O(1) ) read access (a value), using a key).

LinkedList

When the order is important (they are ordered as they were added to the LinkedList), the number of elements are unknown (don't waste memory allocation) and you require quick insertion time ( O(1) ). A list of to-do items that can be listed sequentially as they are added is a good example.

Getting result of dynamic SQL into a variable for sql-server

this could be a solution?

declare @step2cmd nvarchar(200)
DECLARE @rcount NUMERIC(18,0)   
set @step2cmd = 'select count(*) from uat.ap.ztscm_protocollo' --+ @nometab
EXECUTE @rcount=sp_executesql @step2cmd
select @rcount

How to display items side-by-side without using tables?

It depends on what you want to do and what type of data/information you are displaying. In general, tables are reserved for displaying tabular data.

An alternate for your situation would be to use css. A simple option would be to float your image and give it a margin:

<p>
    <img style="float: left; margin: 5px;" ... />
    Text goes here...
</p>

This would cause the text to wrap around the image. If you don't want the text to wrap around the image, put the text in a separate container:

<div>
    <img style="float: left; margin: ...;" ... />
    <p style="float: right;">Text goes here...</p>
</div>

Note that it may be necessary to assign a width to the paragraph tag to display the way you'd like. Also note, for elements that appear below floated elements, you may need to add the style "clear: left;" (or clear: right, or clear: both).

How to prevent rm from reporting that a file was not found?

Yes, -f is the most suitable option for this.

Git "error: The branch 'x' is not fully merged"

C:\inetpub\wwwroot\ember-roomviewer>git branch -d guided-furniture
warning: not deleting branch 'guided-furniture' that is not yet merged to
         'refs/remotes/origin/guided-furniture', even though it is merged to HEAD.
error: The branch 'guided-furniture' is not fully merged.
If you are sure you want to delete it, run 'git branch -D guided-furniture'.

The solution for me was simply that the feature branch needed to be pushed up to the remote. Then when I ran:

git push origin guided-furniture
/* You might need to fetch here */
git branch -d guided-furniture

Deleted branch guided-furniture (was 1813496).

Setting new value for an attribute using jQuery

Works fine for me

See example here. http://jsfiddle.net/blowsie/c6VAy/

Make sure your jquery is inside $(document).ready function or similar.

Also you can improve your code by using jquery data

$('#amount').data('min','1000');

<div id="amount" data-min=""></div>

Update,

A working example of your full code (pretty much) here. http://jsfiddle.net/blowsie/c6VAy/3/

Can't stop rails server

Also, Make sure that you are doing command Cntrl+C in the same terminal (tab) which is used to start the server.

In my case, I had 2 tabs but i forgot to stop the server from correct tab and i was wondering why Cntrl+C is not working.

How the single threaded non blocking IO model works in Node.js

Node.js uses libuv behind the scenes. libuv has a thread pool (of size 4 by default). Therefore Node.js does use threads to achieve concurrency.

However, your code runs on a single thread (i.e., all of the callbacks of Node.js functions will be called on the same thread, the so called loop-thread or event-loop). When people say "Node.js runs on a single thread" they are really saying "the callbacks of Node.js run on a single thread".

How to get the first element of the List or Set?

In Java >=8 you could also use the Streaming API:

Optional<String> first = set.stream().findFirst();

(Useful if the Set/List may be empty.)

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

if you use external libraries in your program and you try to pack all together in a jar file it's not that simple, because of classpath issues etc.

I'd prefer to use OneJar for this issue.

How to change symbol for decimal point in double.ToString()?

If you have an Asp.Net web application, you can also set it in the web.config so that it is the same throughout the whole web application

<system.web>
    ...
    <globalization 
        requestEncoding="utf-8" 
        responseEncoding="utf-8" 
        culture="en-GB" 
        uiCulture="en-GB" 
        enableClientBasedCulture="false"/>
    ...
</system.web>

Algorithm to find Largest prime factor of a number

The following C++ algorithm is not the best one, but it works for numbers under a billion and its pretty fast

#include <iostream>
using namespace std;

// ------ is_prime ------
// Determines if the integer accepted is prime or not
bool is_prime(int n){
    int i,count=0;
    if(n==1 || n==2)
      return true;
    if(n%2==0)
      return false;
    for(i=1;i<=n;i++){
    if(n%i==0)
        count++;
    }
    if(count==2)
      return true;
    else
      return false;
 }
 // ------ nextPrime -------
 // Finds and returns the next prime number
 int nextPrime(int prime){
     bool a = false;
     while (a == false){
         prime++;
         if (is_prime(prime))
            a = true;
     }
  return prime;
 }
 // ----- M A I N ------
 int main(){

      int value = 13195;
      int prime = 2;
      bool done = false;

      while (done == false){
          if (value%prime == 0){
             value = value/prime;
             if (is_prime(value)){
                 done = true;
             }
          } else {
             prime = nextPrime(prime);
          }
      }
        cout << "Largest prime factor: " << value << endl;
 }

Check a collection size with JSTL

<c:if test="${companies.size() > 0}">

</c:if>

This syntax works only in EL 2.2 or newer (Servlet 3.0 / JSP 2.2 or newer). If you're facing a XML parsing error because you're using JSPX or Facelets instead of JSP, then use gt instead of >.

<c:if test="${companies.size() gt 0}">

</c:if>

If you're actually facing an EL parsing error, then you're probably using a too old EL version. You'll need JSTL fn:length() function then. From the documentation:

length( java.lang.Object) - Returns the number of items in a collection, or the number of characters in a string.

Put this at the top of JSP page to allow the fn namespace:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

Or if you're using JSPX or Facelets:

<... xmlns:fn="http://java.sun.com/jsp/jstl/functions">

And use like this in your page:

<p>The length of the companies collection is: ${fn:length(companies)}</p>

So to test with length of a collection:

<c:if test="${fn:length(companies) gt 0}">

</c:if>

Alternatively, for this specific case you can also simply use the EL empty operator:

<c:if test="${not empty companies}">

</c:if>

CSS: Auto resize div to fit container width

I have updated your jsfiddle and here is CSS changes you need to do:

#content
{
    min-width:700px;
    margin-right: -210px;
    width:100%;
    float:left;
    background-color:AppWorkspace;
}

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I had the same problem of "gpg: keyserver timed out" with a couple of different servers. Finally, it turned out that I didn't need to do that manually at all. On a Debian system, the simple solution which fixed it was just (as root or precede with sudo):

aptitude install debian-archive-keyring

In case it is some other keyring you need, check out

apt-cache search keyring | grep debian

My squeeze system shows all these:

debian-archive-keyring       - GnuPG archive keys of the Debian archive
debian-edu-archive-keyring   - GnuPG archive keys of the Debian Edu archive
debian-keyring               - GnuPG keys of Debian Developers
debian-ports-archive-keyring - GnuPG archive keys of the debian-ports archive
emdebian-archive-keyring     - GnuPG archive keys for the emdebian repository

How to access a dictionary key value present inside a list?

You haven't provided enough context to provide an accurate answer (i.e. how do you want to handle identical keys in multiple dicts?)

One answer is to iterate the list, and attempt to get 'd'

mylist = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
myvalues = [i['d'] for i in mylist if 'd' in i]

Another answer is to access the dict directly (by list index), though you have to know that the key is present

mylist[1]['d']

How to make an authenticated web request in Powershell?

The PowerShell is almost exactly the same.

$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
$webpage = $webclient.DownloadString($url)

Error when creating a new text file with python?

import sys

def write():
    print('Creating new text file') 

    name = raw_input('Enter name of text file: ')+'.txt'  # Name of text file coerced with +.txt

    try:
        file = open(name,'a')   # Trying to create a new file or open one
        file.close()

    except:
        print('Something went wrong! Can\'t tell what?')
        sys.exit(0) # quit Python

write()

this will work promise :)

What's the difference between process.cwd() vs __dirname?

$ find proj

proj
proj/src
proj/src/index.js

$ cat proj/src/index.js

console.log("process.cwd() = " + process.cwd());
console.log("__dirname = " + __dirname);

$ cd proj; node src/index.js

process.cwd() = /tmp/proj
__dirname = /tmp/proj/src

How to install a private NPM module without my own registry?

This was what I was looking for:

# Get the latest from GitHub, public repo:
$ npm install username/my-new-project --save-dev
# Bitbucket, private repo:
$ npm install git+https://token:[email protected]/username/my-new-project.git#master
$ npm install git+ssh://[email protected]/username/my-new-project.git#master

# … or from Bitbucket, public repo:
$ npm install git+ssh://[email protected]/username/my-new-project.git#master --save-dev
# Bitbucket, private repo:
$ npm install git+https://username:[email protected]/username/my-new-project.git#master
$ npm install git+ssh://[email protected]/username/my-new-project.git#master
# Or, if you published as npm package:
$ npm install my-new-project --save-dev

Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES

According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.

This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.

select num_rows from all_tables where table_name = 'MY_TABLE'

This query counts the current number of rows in MY_TABLE

select count(*) from my_table

By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.

  1. In the documentation there's an asterisk by the column name, which leads to this note:

    Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.

    This means that unless you have gathered statistics on the table then this column will not have any data.

  2. Statistics gathered in 11g+ with the default estimate_percent, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.

If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.

Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

Spring boot + spring mvn

with issue

@PostMapping("/addDonation")
public String addDonation(@RequestBody DonatorDTO donatorDTO) {

with solution

@RequestMapping(value = "/addDonation", method = RequestMethod.POST)
@ResponseBody
public GenericResponse addDonation(final DonatorDTO donatorDTO, final HttpServletRequest request){

How to run .APK file on emulator

You need to install the APK on the emulator. You can do this with the adb command line tool that is included in the Android SDK.

adb -e install -r yourapp.apk

Once you've done that you should be able to run the app.

The -e and -r flags might not be necessary. They just specify that you are using an emulator (if you also have a device connected) and that you want to replace the app if it already exists.

Is it possible to output a SELECT statement from a PL/SQL block?

It depends on what you need the result for.

If you are sure that there's going to be only 1 row, use implicit cursor:

DECLARE
   v_foo foobar.foo%TYPE;
   v_bar foobar.bar%TYPE;
BEGIN
   SELECT foo,bar FROM foobar INTO v_foo, v_bar;
   -- Print the foo and bar values
   dbms_output.put_line('foo=' || v_foo || ', bar=' || v_bar);
EXCEPTION
   WHEN NO_DATA_FOUND THEN
     -- No rows selected, insert your exception handler here
   WHEN TOO_MANY_ROWS THEN
     -- More than 1 row seleced, insert your exception handler here
END;

If you want to select more than 1 row, you can use either an explicit cursor:

DECLARE
   CURSOR cur_foobar IS
     SELECT foo, bar FROM foobar;

   v_foo foobar.foo%TYPE;
   v_bar foobar.bar%TYPE;
BEGIN
   -- Open the cursor and loop through the records
   OPEN cur_foobar;
   LOOP
      FETCH cur_foobar INTO v_foo, v_bar;
      EXIT WHEN cur_foobar%NOTFOUND;
      -- Print the foo and bar values
      dbms_output.put_line('foo=' || v_foo || ', bar=' || v_bar);
   END LOOP;
   CLOSE cur_foobar;
END;

or use another type of cursor:

BEGIN
   -- Open the cursor and loop through the records
   FOR v_rec IN (SELECT foo, bar FROM foobar) LOOP       
   -- Print the foo and bar values
   dbms_output.put_line('foo=' || v_rec.foo || ', bar=' || v_rec.bar);
   END LOOP;
END;

jQuery scroll to ID from different page

I would like to recommend using the scrollTo plugin

http://demos.flesler.com/jquery/scrollTo/

You can the set scrollto by jquery css selector.

$('html,body').scrollTo( $(target), 800 );

I have had great luck with the accuracy of this plugin and its methods, where other methods of achieving the same effect like using .offset() or .position() have failed to be cross browser for me in the past. Not saying you can't use such methods, I'm sure there is a way to do it cross browser, I've just found scrollTo to be more reliable.

MySQL delete multiple rows in one query conditions unique to each row

You were very close, you can use this:

DELETE FROM table WHERE (col1,col2) IN ((1,2),(3,4),(5,6))

Please see this fiddle.

Best way to simulate "group by" from bash?

It seems that you have to either use a big amount of code to simulate hashes in bash to get linear behavior or stick to the quadratic superlinear versions.

Among those versions, saua's solution is the best (and simplest):

sort -n ip_addresses.txt | uniq -c

I found http://unix.derkeiler.com/Newsgroups/comp.unix.shell/2005-11/0118.html. But it's ugly as hell...

How do I wrap text in a pre tag?

Try using

<pre style="white-space:normal;">. 

Or better throw CSS.

How can I format decimal property to currency?

Below would also work, but you cannot put in the getter of a decimal property. The getter of a decimal property can only return a decimal, for which formatting does not apply.

decimal moneyvalue = 1921.39m; 
string currencyValue = moneyvalue.ToString("C");

What is the difference between sscanf or atoi to convert a string to an integer?

You have 3 choices:

  1. atoi

This is probably the fastest if you're using it in performance-critical code, but it does no error reporting. If the string does not begin with an integer, it will return 0. If the string contains junk after the integer, it will convert the initial part and ignore the rest. If the number is too big to fit in int, the behaviour is unspecified.

  1. sscanf

Some error reporting, and you have a lot of flexibility for what type to store (signed/unsigned versions of char/short/int/long/long long/size_t/ptrdiff_t/intmax_t).

The return value is the number of conversions that succeed, so scanning for "%d" will return 0 if the string does not begin with an integer. You can use "%d%n" to store the index of the first character after the integer that's read in another variable, and thereby check to see if the entire string was converted or if there's junk afterwards. However, like atoi, behaviour on integer overflow is unspecified.

  1. strtol and family

Robust error reporting, provided you set errno to 0 before making the call. Return values are specified on overflow and errno will be set. You can choose any number base from 2 to 36, or specify 0 as the base to auto-interpret leading 0x and 0 as hex and octal, respectively. Choices of type to convert to are signed/unsigned versions of long/long long/intmax_t.

If you need a smaller type you can always store the result in a temporary long or unsigned long variable and check for overflow yourself.

Since these functions take a pointer to pointer argument, you also get a pointer to the first character following the converted integer, for free, so you can tell if the entire string was an integer or parse subsequent data in the string if needed.


Personally, I would recommend the strtol family for most purposes. If you're doing something quick-and-dirty, atoi might meet your needs.

As an aside, sometimes I find I need to parse numbers where leading whitespace, sign, etc. are not supposed to be accepted. In this case it's pretty damn easy to roll your own for loop, eg.,

for (x=0; (unsigned)*s-'0'<10; s++) 
    x=10*x+(*s-'0');

Or you can use (for robustness):

if (isdigit(*s))
    x=strtol(s, &s, 10);
else /* error */ 

Activity has leaked window that was originally added

Best solution is put this before showing progressbar or progressDialog

if (getApplicationContext().getWindow().getDecorView().isShown()) {

  //Show Your Progress Dialog

}

How to write lists inside a markdown table?

another solution , you can add <br> tag to your table

    |Method name| Behavior |
    |--|--|
    | OnAwakeLogicController(); | Its called when MainLogicController is loaded into the memory , its also hold the following actions :- <br> 1. Checking Audio Settings <br>2. Initializing Level Controller|

enter image description here

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS

This is all i can find out. Not sure if it helps, but thought I'd add it to the mix.

WORD-WRAP

This property specifies whether the current rendered line should break if the content exceeds the boundary of the specified rendering box for an element (this is similar in some ways to the ‘clip’ and ‘overflow’ properties in intent.) This property should only apply if the element has a visual rendering, is an inline element with explicit height/width, is absolutely positioned and/or is a block element.

WORD-BREAK

This property controls the line breaking behavior within words. It is especially useful in cases where multiple languages are used within an element.

PostgreSQL IF statement

DO
$do$
BEGIN
   IF EXISTS (SELECT FROM orders) THEN
      DELETE FROM orders;
   ELSE
      INSERT INTO orders VALUES (1,2,3);
   END IF;
END
$do$

There are no procedural elements in standard SQL. The IF statement is part of the default procedural language PL/pgSQL. You need to create a function or execute an ad-hoc statement with the DO command.

You need a semicolon (;) at the end of each statement in plpgsql (except for the final END).

You need END IF; at the end of the IF statement.

A sub-select must be surrounded by parentheses:

    IF (SELECT count(*) FROM orders) > 0 ...

Or:

    IF (SELECT count(*) > 0 FROM orders) ...

This is equivalent and much faster, though:

    IF EXISTS (SELECT FROM orders) ...

Alternative

The additional SELECT is not needed. This does the same, faster:

DO
$do$
BEGIN
   DELETE FROM orders;
   IF NOT FOUND THEN
      INSERT INTO orders VALUES (1,2,3);
   END IF;
END
$do$

Though unlikely, concurrent transactions writing to the same table may interfere. To be absolutely sure, write-lock the table in the same transaction before proceeding as demonstrated.

How to get current CPU and RAM usage in Python?

Use the psutil library. On Ubuntu 18.04, pip installed 5.5.0 (latest version) as of 1-30-2019. Older versions may behave somewhat differently. You can check your version of psutil by doing this in Python:

from __future__ import print_function  # for Python2
import psutil
print(psutil.__versi??on__)

To get some memory and CPU stats:

from __future__ import print_function
import psutil
print(psutil.cpu_percent())
print(psutil.virtual_memory())  # physical memory usage
print('memory % used:', psutil.virtual_memory()[2])

The virtual_memory (tuple) will have the percent memory used system-wide. This seemed to be overestimated by a few percent for me on Ubuntu 18.04.

You can also get the memory used by the current Python instance:

import os
import psutil
pid = os.getpid()
py = psutil.Process(pid)
memoryUse = py.memory_info()[0]/2.**30  # memory use in GB...I think
print('memory use:', memoryUse)

which gives the current memory use of your Python script.

There are some more in-depth examples on the pypi page for psutil.

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

I found this blog post which cleared up a few things. To quote the most relevant bit:

Mixed Active Content is now blocked by default in Firefox 23!

What is Mixed Content?
When a user visits a page served over HTTP, their connection is open for eavesdropping and man-in-the-middle (MITM) attacks. When a user visits a page served over HTTPS, their connection with the web server is authenticated and encrypted with SSL and hence safeguarded from eavesdroppers and MITM attacks.

However, if an HTTPS page includes HTTP content, the HTTP portion can be read or modified by attackers, even though the main page is served over HTTPS. When an HTTPS page has HTTP content, we call that content “mixed”. The webpage that the user is visiting is only partially encrypted, since some of the content is retrieved unencrypted over HTTP. The Mixed Content Blocker blocks certain HTTP requests on HTTPS pages.

The resolution, in my case, was to simply ensure the jquery includes were as follows (note the removal of the protocol):

<link rel="stylesheet" href="//code.jquery.com/ui/1.8.10/themes/smoothness/jquery-ui.css" type="text/css">
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.min.js"></script>

Note that the temporary 'fix' is to click on the 'shield' icon in the top-left corner of the address bar and select 'Disable Protection on This Page', although this is not recommended for obvious reasons.

UPDATE: This link from the Firefox (Mozilla) support pages is also useful in explaining what constitutes mixed content and, as given in the above paragraph, does actually provide details of how to display the page regardless:

Most websites will continue to work normally without any action on your part.

If you need to allow the mixed content to be displayed, you can do that easily:

Click the shield icon Mixed Content Shield in the address bar and choose Disable Protection on This Page from the dropdown menu.

The icon in the address bar will change to an orange warning triangle Warning Identity Icon to remind you that insecure content is being displayed.

To revert the previous action (re-block mixed content), just reload the page.

Linq order by, group by and order by each group?

I think you want an additional projection that maps each group to a sorted-version of the group:

.Select(group => group.OrderByDescending(student => student.Grade))

It also appears like you might want another flattening operation after that which will give you a sequence of students instead of a sequence of groups:

.SelectMany(group => group)

You can always collapse both into a single SelectMany call that does the projection and flattening together.


EDIT: As Jon Skeet points out, there are certain inefficiencies in the overall query; the information gained from sorting each group is not being used in the ordering of the groups themselves. By moving the sorting of each group to come before the ordering of the groups themselves, the Max query can be dodged into a simpler First query.

CSS - make div's inherit a height

You need to take out a float: left; property... because when you use float the parent div do not grub the height of it's children... If you want the parent dive to get the children height you need to give to the parent div a css property overflow:hidden; But to solve your problem you can use display: table-cell; instead of float... it will automatically scale the div height to its parent height...

Vertically center text in a 100% height div?

Modern solution - works in all browsers and IE9+

caniuse - browser support.

.v-center {
  position: relative;
  top: 50%;
  -webkit-transform: translateY(-50%);
      -ms-transform: translateY(-50%);
          transform: translateY(-50%);
}

Example: http://jsbin.com/rehovixufe/1/

Simple line plots using seaborn

Since seaborn also uses matplotlib to do its plotting you can easily combine the two. If you only want to adopt the styling of seaborn the set_style function should get you started:

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

sns.set_style("darkgrid")
plt.plot(np.cumsum(np.random.randn(1000,1)))
plt.show()

Result:

enter image description here

Difference between staticmethod and classmethod

A quick hack-up ofotherwise identical methods in iPython reveals that @staticmethod yields marginal performance gains (in the nanoseconds), but otherwise it seems to serve no function. Also, any performance gains will probably be wiped out by the additional work of processing the method through staticmethod() during compilation (which happens prior to any code execution when you run a script).

For the sake of code readability I'd avoid @staticmethod unless your method will be used for loads of work, where the nanoseconds count.

C++ Convert string (or char*) to wstring (or wchar_t*)

If you have QT and if you are lazy to implement a function and stuff you can use

std::string str;
QString(str).toStdWString()

PHP reindex array?

array_values does the job :

$myArray  = array_values($myArray);

Also some other php function do not preserve the keys, i.e. reset the index.

How to handle configuration in Go

The JSON format worked for me quite well. The standard library offers methods to write the data structure indented, so it is quite readable.

See also this golang-nuts thread.

The benefits of JSON are that it is fairly simple to parse and human readable/editable while offering semantics for lists and mappings (which can become quite handy), which is not the case with many ini-type config parsers.

Example usage:

conf.json:

{
    "Users": ["UserA","UserB"],
    "Groups": ["GroupA"]
}

Program to read the configuration

import (
    "encoding/json"
    "os"
    "fmt"
)

type Configuration struct {
    Users    []string
    Groups   []string
}

file, _ := os.Open("conf.json")
defer file.Close()
decoder := json.NewDecoder(file)
configuration := Configuration{}
err := decoder.Decode(&configuration)
if err != nil {
  fmt.Println("error:", err)
}
fmt.Println(configuration.Users) // output: [UserA, UserB]

Convert to binary and keep leading zeros in Python

you can use rjust string method of python syntax: string.rjust(length, fillchar) fillchar is optional

and for your Question you acn write like this

'0b'+ '1'.rjust(8,'0)

so it wil be '0b00000001'

How do I dump an object's fields to the console?

puts foo.to_json

might come in handy since the json module is loaded by default

What is the purpose of Node.js module.exports and how do you use it?

the refer link is like this:

exports = module.exports = function(){
    //....
}

the properties of exports or module.exports ,such as functions or variables , will be exposed outside

there is something you must pay more attention : don't override exports .

why ?

because exports just the reference of module.exports , you can add the properties onto the exports ,but if you override the exports , the reference link will be broken .

good example :

exports.name = 'william';

exports.getName = function(){
   console.log(this.name);
}

bad example :

exports = 'william';

exports = function(){
     //...
}

If you just want to exposed only one function or variable , like this:

// test.js
var name = 'william';

module.exports = function(){
    console.log(name);
}   

// index.js
var test = require('./test');
test();

this module only exposed one function and the property of name is private for the outside .

Right way to convert data.frame to a numeric matrix, when df also contains strings?

Edit 2: See @flodel's answer. Much better.

Try:

# assuming SFI is your data.frame
as.matrix(sapply(SFI, as.numeric))  

Edit: or as @ CarlWitthoft suggested in the comments:

matrix(as.numeric(unlist(SFI)),nrow=nrow(SFI))

How to detect input type=file "change" for the same file?

I ran into same issue, i red through he solutions above but they did not get any good explanation what was really happening.

This solution i wrote https://jsfiddle.net/r2wjp6u8/ does no do many changes in the DOM tree, it just changes values of the input field. From performance aspect it should be bit better.

Link to fiddle: https://jsfiddle.net/r2wjp6u8/

<button id="btnSelectFile">Upload</button>

<!-- Not displaying the Inputfield because the design changes on each browser -->
<input type="file" id="fileInput" style="display: none;">
<p>
  Current File: <span id="currentFile"></span>
</p>
<hr>
<div class="log"></div>


<script>
// Get Logging Element
var log = document.querySelector('.log');

// Load the file input element.
var inputElement = document.getElementById('fileInput');
inputElement.addEventListener('change', currentFile);

// Add Click behavior to button
document.getElementById('btnSelectFile').addEventListener('click', selectFile);

function selectFile() {
  if (inputElement.files[0]) {
    // Check how manyf iles are selected and display filename
    log.innerHTML += '<p>Total files: ' + inputElement.files.length + '</p>'
    // Reset the Input Field
    log.innerHTML += '<p>Removing file: ' + inputElement.files[0].name + '</p>'
    inputElement.value = '';
    // Check how manyf iles are selected and display filename
    log.innerHTML += '<p>Total files: ' + inputElement.files.length + '</p>'
    log.innerHTML += '<hr>'
  }

  // Once we have a clean slide, open fiel select dialog.
  inputElement.click();
};

function currentFile() {
    // If Input Element has a file
  if (inputElement.files[0]) {
    document.getElementById('currentFile').innerHTML = inputElement.files[0].name;
  }
}

</scrip>

Cannot assign requested address using ServerSocket.socketBind

if your are using server, there's "public network IP" and "internal network IP". Use the "internal network IP" in your file /etc/hosts and "public network IP" in your code. if you use "public network IP" in your file /etc/hosts then you will get this error.

Add data dynamically to an Array

Like this?:

$array[] = 'newItem';

How to initialize static variables

Here is a hopefully helpful pointer, in a code example. Note how the initializer function is only called once.

Also, if you invert the calls to StaticClass::initializeStStateArr() and $st = new StaticClass() you'll get the same result.

$ cat static.php
<?php

class StaticClass {

  public static  $stStateArr = NULL;

  public function __construct() {
    if (!isset(self::$stStateArr)) {
      self::initializeStStateArr();
    }
  }

  public static function initializeStStateArr() {
    if (!isset(self::$stStateArr)) {
      self::$stStateArr = array('CA' => 'California', 'CO' => 'Colorado',);
      echo "In " . __FUNCTION__. "\n";
    }
  }

}

print "Starting...\n";
StaticClass::initializeStStateArr();
$st = new StaticClass();

print_r (StaticClass::$stStateArr);

Which yields :

$ php static.php
Starting...
In initializeStStateArr
Array
(
    [CA] => California
    [CO] => Colorado
)

"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3

I had this same error in python 3.2.

I have script for email sending and:

csv.reader(open('work_dir\uslugi1.csv', newline='', encoding='utf-8'))

when I remove first char in file uslugi1.csv works fine.

Java Replace Line In Text File

If replacement is of different length:

  1. Read file until you find the string you want to replace.
  2. Read into memory the part after text you want to replace, all of it.
  3. Truncate the file at start of the part you want to replace.
  4. Write replacement.
  5. Write rest of the file from step 2.

If replacement is of same length:

  1. Read file until you find the string you want to replace.
  2. Set file position to start of the part you want to replace.
  3. Write replacement, overwriting part of file.

This is the best you can get, with constraints of your question. However, at least the example in question is replacing string of same length, So the second way should work.

Also be aware: Java strings are Unicode text, while text files are bytes with some encoding. If encoding is UTF8, and your text is not Latin1 (or plain 7-bit ASCII), you have to check length of encoded byte array, not length of Java string.

How to launch PowerShell (not a script) from the command line

The color and window sizing are defined by the shortcut LNK file. I think I found a way that will do what you need, try this:

explorer.exe "Windows PowerShell.lnk"

The LNK file is in the all user start menu which is located in different places depending whether your on XP or Windows 7. In 7 the LNK file is here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Convert NaN to 0 in javascript

Methods that use isNaN do not work if you're trying to use parseInt, for example:

parseInt("abc"); // NaN
parseInt(""); // NaN
parseInt("14px"); // 14

But in the second case isNaN produces false (i.e. the null string is a number)

n="abc"; isNaN(n) ? 0 : parseInt(n); // 0
n=""; isNaN(n) ? 0: parseInt(n); // NaN
n="14px"; isNaN(n) ? 0 : parseInt(n); // 14

In summary, the null string is considered a valid number by isNaN but not by parseInt. Verified with Safari, Firefox and Chrome on OSX Mojave.

What is the difference between private and protected members of C++ classes?

Public members of a class A are accessible for all and everyone.

Protected members of a class A are not accessible outside of A's code, but is accessible from the code of any class derived from A.

Private members of a class A are not accessible outside of A's code, or from the code of any class derived from A.

So, in the end, choosing between protected or private is answering the following questions: How much trust are you willing to put into the programmer of the derived class?

By default, assume the derived class is not to be trusted, and make your members private. If you have a very good reason to give free access of the mother class' internals to its derived classes, then you can make them protected.

Convert number to month name in PHP

this is trivially easy, why are so many people making such bad suggestions? @Bora was the closest, but this is the most robust

/***
 * returns the month in words for a given month number
 */
date("F", strtotime(date("Y")."-".$month."-01"));

this is the way to do it

Update query using Subquery in Sql Server

Here in my sample I find out the solution of this, because I had the same problem with updates and subquerys:

UPDATE
    A
SET
    A.ValueToChange = B.NewValue
FROM
    (
        Select * From C
    ) B
Where 
    A.Id = B.Id

Keep overflow div scrolled to bottom unless user scrolls up

You can use something like this,

var element = document.getElementById("yourDivID");
window.scrollTo(0,element.offsetHeight);

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

I’ve created a convenient script for that; pg_grant_read_to_db.sh. This script grants read-only privileges to a specified role on all tables, views and sequences in a database schema and sets them as default.

Rename all files in a folder with a prefix in a single command

find -execdir rename

This renames files and directories with a regular expression affecting only basenames.

So for a prefix you could do:

PATH=/usr/bin find . -depth -execdir rename 's/^/Unix_/' '{}' \;

or to affect files only:

PATH=/usr/bin find . -type f -execdir rename 's/^/Unix_/' '{}' \;

-execdir first cds into the directory before executing only on the basename.

I have explained it in more detail at: Find multiple files and rename them in Linux

Why do we use Base64?

Base64 instead of escaping special characters

I'll give you a very different but real example: I write javascript code to be run in a browser. HTML tags have ID values, but there are constraints on what characters are valid in an ID.

But I want my ID to losslessly refer to files in my file system. Files in reality can have all manner of weird and wonderful characters in them from exclamation marks, accented characters, tilde, even emoji! I cannot do this:

<div id="/path/to/my_strangely_named_file!@().jpg">
    <img src="http://myserver.com/path/to/my_strangely_named_file!@().jpg">
    Here's a pic I took in Moscow.
</div>

Suppose I want to run some code like this:

# ERROR
document.getElementById("/path/to/my_strangely_named_file!@().jpg");

I think this code will fail when executed.

With Base64 I can refer to something complicated without worrying about which language allows what special characters and which need escaping:

document.getElementById("18GerPD8fY4iTbNpC9hHNXNHyrDMampPLA");

Unlike using an MD5 or some other hashing function, you can reverse the encoding to find out what exactly the data was that actually useful.

I wish I knew about Base64 years ago. I would have avoided tearing my hair out with ‘encodeURIComponent’ and str.replace(‘\n’,’\\n’)

SSH transfer of text:

If you're trying to pass complex data over ssh (e.g. a dotfile so you can get your shell personalizations), good luck doing it without Base 64. This is how you would do it with base 64 (I know you can use SCP, but that would take multiple commands - which complicates key bindings for sshing into a server):

How to build an android library with Android Studio and gradle?

I just had a very similar issues with gradle builds / adding .jar library. I got it working by a combination of :

  1. Moving the libs folder up to the root of the project (same directory as 'src'), and adding the library to this folder in finder (using Mac OS X)
  2. In Android Studio, Right-clicking on the folder to add as library
  3. Editing the dependencies in the build.gradle file, adding compile fileTree(dir: 'libs', include: '*.jar')}

BUT more importantly and annoyingly, only hours after I get it working, Android Studio have just released 0.3.7, which claims to have solved a lot of gradle issues such as adding .jar libraries

http://tools.android.com/recent

Hope this helps people!

How to read/write from/to file using Go?

The Read method takes a byte parameter because that is the buffer it will read into. It's a common Idiom in some circles and makes some sense when you think about it.

This way you can determine how many bytes will be read by the reader and inspect the return to see how many bytes actually were read and handle any errors appropriately.

As others have pointed in their answers bufio is probably what you want for reading from most files.

I'll add one other hint since it's really useful. Reading a line from a file is best accomplished not by the ReadLine method but the ReadBytes or ReadString method instead.

Foreign keys in mongo?

The purpose of ForeignKey is to prevent the creation of data if the field value does not match its ForeignKey. To accomplish this in MongoDB, we use Schema middlewares that ensure the data consistency.

Please have a look at the documentation. https://mongoosejs.com/docs/middleware.html#pre

How to display Woocommerce product price by ID number on a custom page?

If you have the product's ID you can use that to create a product object:

$_product = wc_get_product( $product_id );

Then from the object you can run any of WooCommerce's product methods.

$_product->get_regular_price();
$_product->get_sale_price();
$_product->get_price();

Update
Please review the Codex article on how to write your own shortcode.

Integrating the WooCommerce product data might look something like this:

function so_30165014_price_shortcode_callback( $atts ) {
    $atts = shortcode_atts( array(
        'id' => null,
    ), $atts, 'bartag' );

    $html = '';

    if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
         $_product = wc_get_product( $atts['id'] );
         $html = "price = " . $_product->get_price();
    }
    return $html;
}
add_shortcode( 'woocommerce_price', 'so_30165014_price_shortcode_callback' );

Your shortcode would then look like [woocommerce_price id="99"]

Select row and element in awk

Since awk and perl are closely related...


Perl equivalents of @Dennis's awk solutions:

To print the second line:
perl -ne 'print if $. == 2' file

To print the second field:
perl -lane 'print $F[1]' file

To print the third field of the fifth line:
perl -lane 'print $F[2] if $. == 5' file


Perl equivalent of @Glenn's solution:

Print the j'th field of the i'th line

perl -lanse 'print $F[$j-1] if $. == $i' -- -i=5 -j=3 file


Perl equivalents of @Hai's solutions:

if you are looking for second columns that contains abc:

perl -lane 'print if $F[1] =~ /abc/' foo

... and if you want to print only a particular column:

perl -lane 'print $F[2] if $F[1] =~ /abc/' foo

... and for a particular line number:

perl -lane 'print $F[2] if $F[1] =~ /abc/ && $. == 5' foo


-l removes newlines, and adds them back in when printing
-a autosplits the input line into array @F, using whitespace as the delimiter
-n loop over each line of the input file
-e execute the code within quotes
$F[1] is the second element of the array, since Perl starts at 0
$. is the line number

How to save password when using Subversion from the console

It depends on the protocol you're using. If you're using SVN + SSH, the SVN client can't save your password because it never touches it - the SSH client prompts you for it directly. In this case, you can use an SSH key and ssh-agent to avoid the constant prompts. If you're using the svnserve protocol or HTTP(S), then the SSH client is handling your password and can save it.

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

this worked for me

        JsonSerializerSettings json = new JsonSerializerSettings
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        };
        var result = JsonConvert.SerializeObject(list, Formatting.Indented, json);
        return new JsonResult { Data = result, MaxJsonLength = int.MaxValue };

A more useful statusline in vim?

This is the one I use:

set statusline=
set statusline+=%7*\[%n]                                  "buffernr
set statusline+=%1*\ %<%F\                                "File+path
set statusline+=%2*\ %y\                                  "FileType
set statusline+=%3*\ %{''.(&fenc!=''?&fenc:&enc).''}      "Encoding
set statusline+=%3*\ %{(&bomb?\",BOM\":\"\")}\            "Encoding2
set statusline+=%4*\ %{&ff}\                              "FileFormat (dos/unix..) 
set statusline+=%5*\ %{&spelllang}\%{HighlightSearch()}\  "Spellanguage & Highlight on?
set statusline+=%8*\ %=\ row:%l/%L\ (%03p%%)\             "Rownumber/total (%)
set statusline+=%9*\ col:%03c\                            "Colnr
set statusline+=%0*\ \ %m%r%w\ %P\ \                      "Modified? Readonly? Top/bot.

Highlight on? function:

function! HighlightSearch()
  if &hls
    return 'H'
  else
    return ''
  endif
endfunction

Colors (adapted from ligh2011.vim):

hi User1 guifg=#ffdad8  guibg=#880c0e
hi User2 guifg=#000000  guibg=#F4905C
hi User3 guifg=#292b00  guibg=#f4f597
hi User4 guifg=#112605  guibg=#aefe7B
hi User5 guifg=#051d00  guibg=#7dcc7d
hi User7 guifg=#ffffff  guibg=#880c0e gui=bold
hi User8 guifg=#ffffff  guibg=#5b7fbb
hi User9 guifg=#ffffff  guibg=#810085
hi User0 guifg=#ffffff  guibg=#094afe

My StatusLine

SQL Server find and replace specific word in all rows of specific column

UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
WHERE number like 'KIT%'

or simply this if you are sure that you have no values like this CKIT002

UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')

Rendering HTML inside textarea

This is not possible to do with a textarea. What you are looking for is an content editable div, which is very easily done:

<div contenteditable="true"></div>

jsFiddle

_x000D_
_x000D_
div.editable {_x000D_
    width: 300px;_x000D_
    height: 200px;_x000D_
    border: 1px solid #ccc;_x000D_
    padding: 5px;_x000D_
}_x000D_
_x000D_
strong {_x000D_
  font-weight: bold;_x000D_
}
_x000D_
<div contenteditable="true">This is the first line.<br>_x000D_
See, how the text fits here, also if<br>there is a <strong>linebreak</strong> at the end?_x000D_
<br>It works nicely._x000D_
<br>_x000D_
<br><span style="color: lightgreen">Great</span>._x000D_
</div>
_x000D_
_x000D_
_x000D_

What is a "slug" in Django?

Slug is a URL friendly short label for specific content. It only contain Letters, Numbers, Underscores or Hyphens. Slugs are commonly save with the respective content and it pass as a URL string.

Slug can create using SlugField

Ex:

class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100)

If you want to use title as slug, django has a simple function called slugify

from django.template.defaultfilters import slugify

class Article(models.Model):
    title = models.CharField(max_length=100)

    def slug(self):
        return slugify(self.title)

If it needs uniqueness, add unique=True in slug field.

for instance, from the previous example:

class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True)

Are you lazy to do slug process ? don't worry, this plugin will help you. django-autoslug

Troubleshooting BadImageFormatException

I had the same problem even though I have 64-bit Windows 7 and i was loading a 64bit DLL b/c in Project properties | Build I had "Prefer 32-bit" checked. (Don't know why that's set by default). Once I unchecked that, everything ran fine

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

Check if you are returning a @ResponseBody or a @ResponseStatus

I had a similar problem. My Controller looked like that:

@RequestMapping(value="/user", method = RequestMethod.POST)
public String updateUser(@RequestBody User user){
    return userService.updateUser(user).getId();
}

When calling with a POST request I always got the following error:

HTTP Status 405 - Request method 'POST' not supported

After a while I figured out that the method was actually called, but because there is no @ResponseBody and no @ResponseStatus Spring MVC raises the error.

To fix this simply add a @ResponseBody

@RequestMapping(value="/user", method = RequestMethod.POST)
public @ResponseBody String updateUser(@RequestBody User user){
    return userService.updateUser(user).getId();
}

or a @ResponseStatus to your method.

@RequestMapping(value="/user", method = RequestMethod.POST)
@ResponseStatus(value=HttpStatus.OK)
public String updateUser(@RequestBody User user){
    return userService.updateUser(user).getId();
}

How can foreign key constraints be temporarily disabled using T-SQL?

Your best option is to DROP and CREATE foreign key constraints.

I didn't find examples in this post that would work for me "as-is", one would not work if foreign keys reference different schemas, the other would not work if foreign key references multiple columns. This script considers both, multiple schemas and multiple columns per foreign key.

Here is the script that generates "ADD CONSTRAINT" statements, for multiple columns it will separate them by comma (be sure to save this output before executing DROP statements):

PRINT N'-- CREATE FOREIGN KEY CONSTRAINTS --';

SET NOCOUNT ON;
SELECT '
PRINT N''Creating '+ const.const_name +'...''
GO
ALTER TABLE ' + const.parent_obj + '
    ADD CONSTRAINT ' + const.const_name + ' FOREIGN KEY (
            ' + const.parent_col_csv + '
            ) REFERENCES ' + const.ref_obj + '(' + const.ref_col_csv + ')
GO'
FROM (
    SELECT QUOTENAME(fk.NAME) AS [const_name]
        ,QUOTENAME(schParent.NAME) + '.' + QUOTENAME(OBJECT_name(fkc.parent_object_id)) AS [parent_obj]
        ,STUFF((
                SELECT ',' + QUOTENAME(COL_NAME(fcP.parent_object_id, fcp.parent_column_id))
                FROM sys.foreign_key_columns AS fcP
                WHERE fcp.constraint_object_id = fk.object_id
                FOR XML path('')
                ), 1, 1, '') AS [parent_col_csv]
        ,QUOTENAME(schRef.NAME) + '.' + QUOTENAME(OBJECT_NAME(fkc.referenced_object_id)) AS [ref_obj]
        ,STUFF((
                SELECT ',' + QUOTENAME(COL_NAME(fcR.referenced_object_id, fcR.referenced_column_id))
                FROM sys.foreign_key_columns AS fcR
                WHERE fcR.constraint_object_id = fk.object_id
                FOR XML path('')
                ), 1, 1, '') AS [ref_col_csv]
    FROM sys.foreign_key_columns AS fkc
    INNER JOIN sys.foreign_keys AS fk ON fk.object_id = fkc.constraint_object_id
    INNER JOIN sys.objects AS oParent ON oParent.object_id = fkc.parent_object_id
    INNER JOIN sys.schemas AS schParent ON schParent.schema_id = oParent.schema_id
    INNER JOIN sys.objects AS oRef ON oRef.object_id = fkc.referenced_object_id
    INNER JOIN sys.schemas AS schRef ON schRef.schema_id = oRef.schema_id
    GROUP BY fkc.parent_object_id
        ,fkc.referenced_object_id
        ,fk.NAME
        ,fk.object_id
        ,schParent.NAME
        ,schRef.NAME
    ) AS const
ORDER BY const.const_name

Here is the script that generates "DROP CONSTRAINT" statements:

PRINT N'-- DROP FOREIGN KEY CONSTRAINTS --';

SET NOCOUNT ON;

SELECT '
PRINT N''Dropping ' + fk.NAME + '...''
GO
ALTER TABLE [' + sch.NAME + '].[' + OBJECT_NAME(fk.parent_object_id) + ']' + ' DROP  CONSTRAINT ' + '[' + fk.NAME + ']
GO'
FROM sys.foreign_keys AS fk
INNER JOIN sys.schemas AS sch ON sch.schema_id = fk.schema_id
ORDER BY fk.NAME

Copy multiple files from one directory to another from Linux shell

Try this simpler one,

cp /home/ankur/folder/file{1,2} /home/ankur/dest

If you want to copy all the 10 files then run this command,

 cp ~/Desktop/{xyz,file{1,2},next,files,which,are,not,similer} foo-bar

Plotting a python dict in order of key values

Simply pass the sorted items from the dictionary to the plot() function. concentration.items() returns a list of tuples where each tuple contains a key from the dictionary and its corresponding value.

You can take advantage of list unpacking (with *) to pass the sorted data directly to zip, and then again to pass it into plot():

import matplotlib.pyplot as plt

concentration = {
    0: 0.19849878712984576,
    5000: 0.093917341754771386,
    10000: 0.075060643507712022,
    20000: 0.06673074282575861,
    30000: 0.057119318961966224,
    50000: 0.046134834546203485,
    100000: 0.032495766396631424,
    200000: 0.018536317451599615,
    500000: 0.0059499290585381479}

plt.plot(*zip(*sorted(concentration.items())))
plt.show()

sorted() sorts tuples in the order of the tuple's items so you don't need to specify a key function because the tuples returned by dict.item() already begin with the key value.

How can I force users to access my page over HTTPS instead of HTTP?

I just created a .htaccess file and added :

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Simple !

WPF Data Binding and Validation Rules Best Practices

If your business class is directly used by your UI is preferrable to use IDataErrorInfo because it put logic closer to their owner.

If your business class is a stub class created by a reference to an WCF/XmlWeb service then you can not/must not use IDataErrorInfo nor throw Exception for use with ExceptionValidationRule. Instead you can:

  • Use custom ValidationRule.
  • Define a partial class in your WPF UI project and implements IDataErrorInfo.

How to export MySQL database with triggers and procedures?

May be it's obvious for expert users of MYSQL but I wasted some time while trying to figure out default value would not export functions. So I thought to mention here that --routines param needs to be set to true to make it work.

mysqldump --routines=true -u <user> my_database > my_database.sql

Android : How to read file in bytes?

Here is a solution that guarantees entire file will be read, that requires no libraries and is efficient:

byte[] fullyReadFileToBytes(File f) throws IOException {
    int size = (int) f.length();
    byte bytes[] = new byte[size];
    byte tmpBuff[] = new byte[size];
    FileInputStream fis= new FileInputStream(f);;
    try {

        int read = fis.read(bytes, 0, size);
        if (read < size) {
            int remain = size - read;
            while (remain > 0) {
                read = fis.read(tmpBuff, 0, remain);
                System.arraycopy(tmpBuff, 0, bytes, size - remain, read);
                remain -= read;
            }
        }
    }  catch (IOException e){
        throw e;
    } finally {
        fis.close();
    }

    return bytes;
}

NOTE: it assumes file size is less than MAX_INT bytes, you can add handling for that if you want.

How do I change the root directory of an Apache server?

Applies to Ubuntu 14.04 and later releases. Make sure to backup following files before making any changes.

1.Open /etc/apache2/apache2.conf and search for <Directory /var/www/> directive and replace path with /home/<USERNAME>/public_html. You can use * instead of .

2.Open /etc/apache2/sites-available/000-default.conf and replace DocumentRoot value property from /var/www/html to /home/<USERNAME>/public_html. Also <Directory /var/www/html> to <Directory /home/<USERNAME>/public_html.

3.Open /etc/mods-available/php7.1.conf. Find and comment following code

<IfModule mod_userdir.c>
    <Directory /home/*/public_html>
        php_admin_flag engine Off
    </Directory>
</IfModule>

Do not turn ON php_admin_flag engine OFF flag as reason is mentioned in comment above Directive code. Also php version can be 5.0, 7.0 or anything which you have installed.

Create public_html directory in home/<USERNAME>.

Restart apache service by executing command sudo service apache2 restart.

Test by running sample script on server.

How do I find out what License has been applied to my SQL Server installation?

This shows the licence type and number of licences:

SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')

How can prepared statements protect from SQL injection attacks?

When you create and send a prepared statement to the DBMS, it's stored as the SQL query for execution.

You later bind your data to the query such that the DBMS uses that data as the query parameters for execution (parameterization). The DBMS doesn't use the data you bind as a supplemental to the already compiled SQL query; it's simply the data.

This means it's fundamentally impossible to perform SQL injection using prepared statements. The very nature of prepared statements and their relationship with the DBMS prevents this.

Could not establish trust relationship for SSL/TLS secure channel -- SOAP

In my case I was trying to test SSL in my Visual Studio environment using IIS 7.

This is what I ended up doing to get it to work:

  • Under my site in the 'Bindings...' section on the right in IIS, I had to add the 'https' binding to port 443 and select "IIS Express Developement Certificate".

  • Under my site in the 'Advanced Settings...' section on the right I had to change the 'Enabled Protocols' from "http" to "https".

  • Under the 'SSL Settings' icon I selected 'Accept' for client certificates.

  • Then I had to recycle the app pool.

  • I also had to import the local host certificate into my personal store using mmc.exe.

My web.config file was already configured correctly, so after I got all the above sorted out, I was able to continue my testing.

socket programming multiple client to one server

This is the echo server handling multiple clients... Runs fine and good using Threads

// echo server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


public class Server_X_Client {
public static void main(String args[]){


    Socket s=null;
    ServerSocket ss2=null;
    System.out.println("Server Listening......");
    try{
        ss2 = new ServerSocket(4445); // can also use static final PORT_NUM , when defined

    }
    catch(IOException e){
    e.printStackTrace();
    System.out.println("Server error");

    }

    while(true){
        try{
            s= ss2.accept();
            System.out.println("connection Established");
            ServerThread st=new ServerThread(s);
            st.start();

        }

    catch(Exception e){
        e.printStackTrace();
        System.out.println("Connection Error");

    }
    }

}

}

class ServerThread extends Thread{  

    String line=null;
    BufferedReader  is = null;
    PrintWriter os=null;
    Socket s=null;

    public ServerThread(Socket s){
        this.s=s;
    }

    public void run() {
    try{
        is= new BufferedReader(new InputStreamReader(s.getInputStream()));
        os=new PrintWriter(s.getOutputStream());

    }catch(IOException e){
        System.out.println("IO error in server thread");
    }

    try {
        line=is.readLine();
        while(line.compareTo("QUIT")!=0){

            os.println(line);
            os.flush();
            System.out.println("Response to Client  :  "+line);
            line=is.readLine();
        }   
    } catch (IOException e) {

        line=this.getName(); //reused String line for getting thread name
        System.out.println("IO Error/ Client "+line+" terminated abruptly");
    }
    catch(NullPointerException e){
        line=this.getName(); //reused String line for getting thread name
        System.out.println("Client "+line+" Closed");
    }

    finally{    
    try{
        System.out.println("Connection Closing..");
        if (is!=null){
            is.close(); 
            System.out.println(" Socket Input Stream Closed");
        }

        if(os!=null){
            os.close();
            System.out.println("Socket Out Closed");
        }
        if (s!=null){
        s.close();
        System.out.println("Socket Closed");
        }

        }
    catch(IOException ie){
        System.out.println("Socket Close Error");
    }
    }//end finally
    }
}

Also here is the code for the client.. Just execute this code for as many times as you want to create multiple client..

// A simple Client Server Protocol .. Client for Echo Server

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class NetworkClient {

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


    InetAddress address=InetAddress.getLocalHost();
    Socket s1=null;
    String line=null;
    BufferedReader br=null;
    BufferedReader is=null;
    PrintWriter os=null;

    try {
        s1=new Socket(address, 4445); // You can use static final constant PORT_NUM
        br= new BufferedReader(new InputStreamReader(System.in));
        is=new BufferedReader(new InputStreamReader(s1.getInputStream()));
        os= new PrintWriter(s1.getOutputStream());
    }
    catch (IOException e){
        e.printStackTrace();
        System.err.print("IO Exception");
    }

    System.out.println("Client Address : "+address);
    System.out.println("Enter Data to echo Server ( Enter QUIT to end):");

    String response=null;
    try{
        line=br.readLine(); 
        while(line.compareTo("QUIT")!=0){
                os.println(line);
                os.flush();
                response=is.readLine();
                System.out.println("Server Response : "+response);
                line=br.readLine();

            }



    }
    catch(IOException e){
        e.printStackTrace();
    System.out.println("Socket read Error");
    }
    finally{

        is.close();os.close();br.close();s1.close();
                System.out.println("Connection Closed");

    }

}
}

jQuery 1.9 .live() is not a function

.live was removed in 1.9, please see the upgrade guide: http://jquery.com/upgrade-guide/1.9/#live-removed

Reporting (free || open source) Alternatives to Crystal Reports in Winforms

MS' free SQL Server 2008 Express (with Advanced Services) looks to include reporting services.

http://www.microsoft.com/express/sql/download/

Here how reporting features differ from the full version: http://msdn.microsoft.com/en-us/library/ms365166.aspx

EDIT: I don't know if this works in winforms but it still looks useful.

Spring Boot + JPA : Column name annotation ignored

In my case, the annotation was on the getter() method instead of the field itself (ported from a legacy application).

Spring ignores the annotation in this case as well but doesn't complain. The solution was to move it to the field instead of the getter.

POI setting Cell Background to a Custom Color

See http://poi.apache.org/spreadsheet/quick-guide.html#CustomColors.

Custom colors

HSSF:

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow((short) 0);
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("Default Palette");

//apply some colors from the standard palette,
// as in the previous examples.
//we'll use red text on a lime background

HSSFCellStyle style = wb.createCellStyle();
style.setFillForegroundColor(HSSFColor.LIME.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

HSSFFont font = wb.createFont();
font.setColor(HSSFColor.RED.index);
style.setFont(font);

cell.setCellStyle(style);

//save with the default palette
FileOutputStream out = new FileOutputStream("default_palette.xls");
wb.write(out);
out.close();

//now, let's replace RED and LIME in the palette
// with a more attractive combination
// (lovingly borrowed from freebsd.org)

cell.setCellValue("Modified Palette");

//creating a custom palette for the workbook
HSSFPalette palette = wb.getCustomPalette();

//replacing the standard red with freebsd.org red
palette.setColorAtIndex(HSSFColor.RED.index,
        (byte) 153,  //RGB red (0-255)
        (byte) 0,    //RGB green
        (byte) 0     //RGB blue
);
//replacing lime with freebsd.org gold
palette.setColorAtIndex(HSSFColor.LIME.index, (byte) 255, (byte) 204, (byte) 102);

//save with the modified palette
// note that wherever we have previously used RED or LIME, the
// new colors magically appear
out = new FileOutputStream("modified_palette.xls");
wb.write(out);
out.close();

XSSF:

XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell( 0);
cell.setCellValue("custom XSSF colors");

XSSFCellStyle style1 = wb.createCellStyle();
style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 0, 128)));
style1.setFillPattern(CellStyle.SOLID_FOREGROUND);

How to deserialize JS date using Jackson?

This works for me - i am using jackson 2.0.4

ObjectMapper objectMapper = new ObjectMapper();
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
objectMapper.setDateFormat(df);

Converting a year from 4 digit to 2 digit and back again in C#

1st solution (fastest) :

yourDateTime.Year % 100

2nd solution (more elegant in my opinion) :

yourDateTime.ToString("yy")

How to add a line to a multiline TextBox?

@Casperah pointed out that i'm thinking about it wrong:

  • A TextBox doesn't have lines
  • it has text
  • that text can be split on the CRLF into lines, if requested
  • but there is no notion of lines

The question then is how to accomplish what i want, rather than what WinForms lets me.

There are subtle bugs in the other given variants:

  • textBox1.AppendText("Hello" + Environment.NewLine);
  • textBox1.AppendText("Hello" + "\r\n");
  • textBox1.Text += "Hello\r\n"
  • textbox1.Text += System.Environment.NewLine + "brown";

They either append or prepend a newline when one (might) not be required.

So, extension helper:

public static class WinFormsExtensions
{
   public static void AppendLine(this TextBox source, string value)
   {
      if (source.Text.Length==0)
         source.Text = value;
      else
         source.AppendText("\r\n"+value);
   }
}

So now:

textBox1.Clear();
textBox1.AppendLine("red");
textBox1.AppendLine("green");
textBox1.AppendLine("blue");

and

textBox1.AppendLine(String.Format("Processing file {0}", filename));

Note: Any code is released into the public domain. No attribution required.

Variables within app.config/web.config

I would suggest you DslConfig. With DslConfig you can use hierarchical config files from Global Config, Config per server host to config per application on each server host (see the AppSpike).
If this is to complicated for you you can just use the global config Variables.var
Just configure in Varibales.var

baseDir = "C:\MyBase"
Var["MyBaseDir"] = baseDir
Var["Dir1"] = baseDir + "\Dir1"
Var["Dir2"] = baseDir + "\Dir2"

And get the config values with

Configuration config = new DslConfig.BooDslConfiguration()
config.GetVariable<string>("MyBaseDir")
config.GetVariable<string>("Dir1")
config.GetVariable<string>("Dir2")

How to remove specific value from array using jQuery

A working JSFIDDLE

You can do something like this:

var y = [1, 2, 2, 3, 2]
var removeItem = 2;

y = jQuery.grep(y, function(value) {
  return value != removeItem;
});

Result:

[1, 3]

http://snipplr.com/view/14381/remove-item-from-array-with-jquery/

how to make UITextView height dynamic according to text length?

this Works for me, all other solutions didn't.

func adjustUITextViewHeight(arg : UITextView)
{
    arg.translatesAutoresizingMaskIntoConstraints = true
    arg.sizeToFit()
    arg.scrollEnabled = false
}

In Swift 4 the syntax of arg.scrollEnabled = false has changed to arg.isScrollEnabled = false.

Is there any way to return HTML in a PHP function? (without building the return value as a string)

If you don't want to have to rely on a third party tool you can use this technique:

function TestBlockHTML($replStr){
  $template = 
   '<html>
     <body>
       <h1>$str</h1>
     </body>
   </html>';
 return strtr($template, array( '$str' => $replStr));
}

EventListener Enter Key

Are you trying to submit a form?

Listen to the submit event instead.

This will handle click and enter.

If you must use enter key...

document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
      // code for enter
    }
});

how to read System environment variable in Spring applicationContext

Using Spring EL you can eis example write as follows

<bean id="myBean" class="path.to.my.BeanClass">
    <!-- can be overridden with -Dtest.target.host=http://whatever.com -->
    <constructor-arg value="#{systemProperties['test.target.host'] ?: 'http://localhost:18888'}"/>
</bean>

Prevent flex items from overflowing a container

It's not suitable for every situation, because not all items can have a non-proportional maximum, but slapping a good ol' max-width on the offending element/container can put it back in line.

Do I really need to encode '&' as '&amp;'?

It depends on the likelihood of a semicolon ending up near your &, causing it to display something quite different.

For example, when dealing with input from users (say, if you include the user-provided subject of a forum post in your title tags), you never know where they might be putting random semicolons, and it might randomly display strange entities. So always escape in that situation.

For your own static html, sure, you could skip it, but it's so trivial to include proper escaping, that there's no good reason to avoid it.

Handling warning for possible multiple enumeration of IEnumerable

Using IReadOnlyCollection<T> or IReadOnlyList<T> in the method signature instead of IEnumerable<T>, has the advantage of making explicit that you might need to check the count before iterating, or to iterate multiple times for some other reason.

However they have a huge downside that will cause problems if you try to refactor your code to use interfaces, for instance to make it more testable and friendly to dynamic proxying. The key point is that IList<T> does not inherit from IReadOnlyList<T>, and similarly for other collections and their respective read-only interfaces. (In short, this is because .NET 4.5 wanted to keep ABI compatibility with earlier versions. But they didn't even take the opportunity to change that in .NET core.)

This means that if you get an IList<T> from some part of the program and want to pass it to another part that expects an IReadOnlyList<T>, you can't! You can however pass an IList<T> as an IEnumerable<T>.

In the end, IEnumerable<T> is the only read-only interface supported by all .NET collections including all collection interfaces. Any other alternative will come back to bite you as you realize that you locked yourself out from some architecture choices. So I think it's the proper type to use in function signatures to express that you just want a read-only collection.

(Note that you can always write a IReadOnlyList<T> ToReadOnly<T>(this IList<T> list) extension method that simple casts if the underlying type supports both interfaces, but you have to add it manually everywhere when refactoring, where as IEnumerable<T> is always compatible.)

As always this is not an absolute, if you're writing database-heavy code where accidental multiple enumeration would be a disaster, you might prefer a different trade-off.

String "true" and "false" to boolean

ActiveRecord::Type::Boolean.new.type_cast_from_user does this according to Rails' internal mappings ConnectionAdapters::Column::TRUE_VALUES and ConnectionAdapters::Column::FALSE_VALUES:

[3] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("true")
=> true
[4] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("false")
=> false
[5] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("T")
=> true
[6] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("F")
=> false
[7] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("yes")
DEPRECATION WARNING: You attempted to assign a value which is not explicitly `true` or `false` ("yes") to a boolean column. Currently this value casts to `false`. This will change to match Ruby's semantics, and will cast to `true` in Rails 5. If you would like to maintain the current behavior, you should explicitly handle the values you would like cast to `false`. (called from <main> at (pry):7)
=> false
[8] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("no")
DEPRECATION WARNING: You attempted to assign a value which is not explicitly `true` or `false` ("no") to a boolean column. Currently this value casts to `false`. This will change to match Ruby's semantics, and will cast to `true` in Rails 5. If you would like to maintain the current behavior, you should explicitly handle the values you would like cast to `false`. (called from <main> at (pry):8)
=> false

So you could make your own to_b (or to_bool or to_boolean) method in an initializer like this:

class String
  def to_b
    ActiveRecord::Type::Boolean.new.type_cast_from_user(self)
  end
end

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

Even though your JDK in eclipse is 1.7, you need to make sure eclipse compilance level also set to 1.7. You can check compilance level--> Window-->Preferences--> Java--Compiler--compilance level.

Unsupported major minor error happens in cases where compilance level doesn't match with runtime.

Injecting @Autowired private field during testing

The accepted answer (use MockitoJUnitRunner and @InjectMocks) is great. But if you want something a little more lightweight (no special JUnit runner), and less "magical" (more transparent) especially for occasional use, you could just set the private fields directly using introspection.

If you use Spring, you already have a utility class for this : org.springframework.test.util.ReflectionTestUtils

The use is quite straightforward :

ReflectionTestUtils.setField(myLauncher, "myService", myService);

The first argument is your target bean, the second is the name of the (usually private) field, and the last is the value to inject.

If you don't use Spring, it is quite trivial to implement such a utility method. Here is the code I used before I found this Spring class :

public static void setPrivateField(Object target, String fieldName, Object value){
        try{
            Field privateField = target.getClass().getDeclaredField(fieldName);
            privateField.setAccessible(true);
            privateField.set(target, value);
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }

calculating execution time in c++

I have used the technique said above, still I found that the time given in the Code:Blocks IDE was more or less similar to the result obtained-(may be it will differ by little micro seconds)..

How to disable anchor "jump" when loading a page?

None of answers do not work good enough for me, I see page jumping to anchor and then to top for some solutions, some answers do not work at all, may be things changed for years. Hope my function will help to someone.

/**
 * Prevent automatic scrolling of page to anchor by browser after loading of page.
 * Do not call this function in $(...) or $(window).on('load', ...),
 * it should be called earlier, as soon as possible.
 */
function preventAnchorScroll() {
    var scrollToTop = function () {
        $(window).scrollTop(0);
    };
    if (window.location.hash) {
        // handler is executed at most once
        $(window).one('scroll', scrollToTop);
    }

    // make sure to release scroll 1 second after document readiness
    // to avoid negative UX
    $(function () {
        setTimeout(
            function () {
                $(window).off('scroll', scrollToTop);
            },
            1000
        );
    });
}

How can I pass parameters to a partial view in mvc 4

Your question is hard to understand, but if I'm getting the gist, you simply have some value in your main view that you want to access in a partial being rendered in that view.

If you just render a partial with just the partial name:

@Html.Partial("_SomePartial")

It will actually pass your model as an implicit parameter, the same as if you were to call:

@Html.Partial("_SomePartial", Model)

Now, in order for your partial to actually be able to use this, though, it too needs to have a defined model, for example:

@model Namespace.To.Your.Model

@Html.Action("MemberProfile", "Member", new { id = Model.Id })

Alternatively, if you're dealing with a value that's not on your view's model (it's in the ViewBag or a value generated in the view itself somehow, then you can pass a ViewDataDictionary

@Html.Partial("_SomePartial", new ViewDataDictionary { { "id", someInteger } });

And then:

@Html.Action("MemberProfile", "Member", new { id = ViewData["id"] })

As with the model, Razor will implicitly pass your partial the view's ViewData by default, so if you had ViewBag.Id in your view, then you can reference the same thing in your partial.

How can I turn a JSONArray into a JSONObject?

Can't you originally get the data as a JSONObject?

Perhaps parse the string as both a JSONObject and a JSONArray in the first place? Where is the JSON string coming from?

I'm not sure that it is possible to convert a JsonArray into a JsonObject.

I presume you are using the following from json.org

  • JSONObject.java
    A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

  • JSONArray.java
    A JSONArray is an ordered sequence of values. Its external form is a string wrapped in square brackets with commas between the values. The internal form is an object having get() and opt() methods for accessing the values by index, and put() methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

How to Git stash pop specific stash in 1.8.3?

As Robert pointed out, quotation marks might do the trick for you:

git stash pop stash@"{1}"

How to get size of mysql database?

To get a result in MB:

SELECT
SUM(ROUND(((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024), 2)) AS "SIZE IN MB"
FROM INFORMATION_SCHEMA.TABLES
WHERE
TABLE_SCHEMA = "SCHEMA-NAME";

To get a result in GB:

SELECT
SUM(ROUND(((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024 / 1024), 2)) AS "SIZE IN GB"
FROM INFORMATION_SCHEMA.TABLES
WHERE
TABLE_SCHEMA = "SCHEMA-NAME";

simple vba code gives me run time error 91 object variable or with block not set

You need Set with objects:

 Set rng = Sheet8.Range("A12")

Sheet8 is fine.

 Sheet1.[a1]

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

With

com.android.tools.build:gradle:3.2.0

You have to use:

classpath 'com.google.gms:google-services:4.1.0'

This fixed my problem

Redirect to new Page in AngularJS using $location

If you want to change ng-view you'll have to use the '#'

$window.location.href= "#operation";

What good technology podcasts are out there?

It's worth subscribing to the Google Tech Talk YouTube channel. It's a video podcast with a bunch of really interesting, wide-ranging talks given to Google but (usually) outside speakers.

Past presenters include Linus Torvals, Guido van Rossum, Merlin Mann and Larry Wall. The video is usually just the slides so (depending on the speaker) you might not need to watch.

SSRS chart does not show all labels on Horizontal axis

Go to Horizontal axis properties,choose 'Category' in AXIS type,choose "Disabled" in SIDE Margin option

How to force IE to reload javascript?

Add a string at the end of your URL to break the cache. I usually do (with PHP):

<script src="/my/js/file.js?<?=time()?>"></script>

So that it reloads every time while I'm working on it, and then take it off when it goes into production. In reality I abstract this out a little more but the idea remains the same.

If you check out the source of this website, they append the revision number at the end of the URL in a similar fashion to force the changes upon us whenever they update the javascript files.

Load local javascript file in chrome for testing?

Look at where your html file is, the path you provided is relative not absolute. Are you sure it's placed correctly. According to the path you gave in the example above: "src="../js/moment.js" " the JS file is one level higher in hierarchy. So it should be placed as following:

Parent folder sub-folder html file js (this is a folder) moment.js

The double dots means the parent folder from current directory, in your case, the current directory is the location of html file.

But to make your life easier using a server will safe you troubles of doing this manually since the server directory is same all time so it's much easier.

Add common prefix to all cells in Excel

Select the cell you want,

Go To Format Cells (or CTRL+1),

Select the "custom" Tab, enter your required format like : "X"#

use a space if needed.

for example, I needed to insert the word "Hours" beside my numbers and used this format : # "hours"

What is the MySQL JDBC driver connection string?

String url = "jdbc:mysql://localhost:3306/dbname";
String user = "user";
String pass = "pass";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Connection conn = DriverManager.getConnection (url, user, pass);

3306 is the default port for mysql.

If you are using Java 7 then there is no need to even add the Class.forName("com.mysql.jdbc.Driver").newInstance (); statement.Automatic Resource Management (ARM) is added in JDBC 4.1 which comes by default in Java 7.

The general format for a JDBC URL for connecting to a MySQL server is as follows, with items in square brackets ([ ]) being optional:

jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]] »
[?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]

Uncaught TypeError: Cannot read property 'length' of undefined

console.log(typeof json_data !== 'undefined'
    ? json_data.length : 'There is no spoon.');

...or more simply...

console.log(json_data ? json_data.length : 'json_data is null or undefined');

How to execute a JavaScript function when I have its name as a string

Don't use eval unless you absolutely, positively have no other choice.

As has been mentioned, using something like this would be the best way to do it:

window["functionName"](arguments);

That, however, will not work with a namespace'd function:

window["My.Namespace.functionName"](arguments); // fail

This is how you would do that:

window["My"]["Namespace"]["functionName"](arguments); // succeeds

In order to make that easier and provide some flexibility, here is a convenience function:

function executeFunctionByName(functionName, context /*, args */) {
  var args = Array.prototype.slice.call(arguments, 2);
  var namespaces = functionName.split(".");
  var func = namespaces.pop();
  for(var i = 0; i < namespaces.length; i++) {
    context = context[namespaces[i]];
  }
  return context[func].apply(context, args);
}

You would call it like so:

executeFunctionByName("My.Namespace.functionName", window, arguments);

Note, you can pass in whatever context you want, so this would do the same as above:

executeFunctionByName("Namespace.functionName", My, arguments);

Adding 1 hour to time variable

Beware of adding 3600!! may be a problem on day change because of unix timestamp format uses moth before day.

e.g. 2012-03-02 23:33:33 would become 2014-01-13 13:00:00 by adding 3600 better use mktime and date functions they can handle this and things like adding 25 hours etc.

ReactJS - .JS vs .JSX

There is none when it comes to file extensions. Your bundler/transpiler/whatever takes care of resolving what type of file contents there is.

There are however some other considerations when deciding what to put into a .js or a .jsx file type. Since JSX isn't standard JavaScript one could argue that anything that is not "plain" JavaScript should go into its own extensions ie., .jsx for JSX and .ts for TypeScript for example.

There's a good discussion here available for read

keycode 13 is for which key

That would be the Enter key.

How do I return clean JSON from a WCF Service?

Change the return type of your GetResults to be List<Person>.
Eliminate the code that you use to serialize the List to a json string - WCF does this for you automatically.

Using your definition for the Person class, this code works for me:

public List<Person> GetPlayers()
{
    List<Person> players = new List<Person>();
    players.Add(new  Person { FirstName="Peyton", LastName="Manning", Age=35 } );
    players.Add(new  Person { FirstName="Drew", LastName="Brees", Age=31 } );
    players.Add(new  Person { FirstName="Brett", LastName="Favre", Age=58 } );

    return players;
}

results:

[{"Age":35,"FirstName":"Peyton","LastName":"Manning"},  
 {"Age":31,"FirstName":"Drew","LastName":"Brees"},  
 {"Age":58,"FirstName":"Brett","LastName":"Favre"}]

(All on one line)

I also used this attribute on the method:

[WebInvoke(Method = "GET",
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           UriTemplate = "players")]

WebInvoke with Method= "GET" is the same as WebGet, but since some of my methods are POST, I use all WebInvoke for consistency.

The UriTemplate sets the URL at which the method is available. So I can do a GET on http://myserver/myvdir/JsonService.svc/players and it just works.

Also check out IIRF or another URL rewriter to get rid of the .svc in the URI.

Android Bluetooth Example

I have also used following link as others have suggested you for bluetooth communication.

http://developer.android.com/guide/topics/connectivity/bluetooth.html

The thing is all you need is a class BluetoothChatService.java

this class has following threads:

  1. Accept
  2. Connecting
  3. Connected

Now when you call start function of the BluetoothChatService like:

mChatService.start();

It starts accept thread which means it will start looking for connection.

Now when you call

mChatService.connect(<deviceObject>,false/true);

Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.

connect function will start connecting thread which will look for any device which is running accept thread.

When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:

connected(mmSocket, mmDevice, mSocketType);

this method starts connected thread in both the devices: Using this socket object connected thread obtains the input and output stream to the other device. And calls read function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.

BluetoothChatService also has a write method which takes byte[] as input and calls write method on connected thread.

mChatService.write("your message".getByte());

write method in connected thread just write this byte data to outputsream of the other device.

public void write(byte[] buffer) {
   try {
       mmOutStream.write(buffer);
    // Share the sent message back to the UI Activity
    // mHandler.obtainMessage(
    // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
    // buffer).sendToTarget();
    } catch (IOException e) {
    Log.e(TAG, "Exception during write", e);
     }
}

Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.

What's the use of session.flush() in Hibernate

With this method you evoke the flush process. This process synchronizes the state of your database with state of your session by detecting state changes and executing the respective SQL statements.

SSH Key - Still asking for password and passphrase

If you used for your GIT the password authentication before, but now are using SSH authentication, you need to switch remote URLs from HTTPS to SSH:

git remote set-url origin [email protected]:USERNAME/REPOSITORY.git

When should I use cross apply over inner join?

It seems to me that CROSS APPLY can fill a certain gap when working with calculated fields in complex/nested queries, and make them simpler and more readable.

Simple example: you have a DoB and you want to present multiple age-related fields that will also rely on other data sources (such as employment), like Age, AgeGroup, AgeAtHiring, MinimumRetirementDate, etc. for use in your end-user application (Excel PivotTables, for example).

Options are limited and rarely elegant:

  • JOIN subqueries cannot introduce new values in the dataset based on data in the parent query (it must stand on its own).

  • UDFs are neat, but slow as they tend to prevent parallel operations. And being a separate entity can be a good (less code) or a bad (where is the code) thing.

  • Junction tables. Sometimes they can work, but soon enough you're joining subqueries with tons of UNIONs. Big mess.

  • Create yet another single-purpose view, assuming your calculations don't require data obtained mid-way through your main query.

  • Intermediary tables. Yes... that usually works, and often a good option as they can be indexed and fast, but performance can also drop due to to UPDATE statements not being parallel and not allowing to cascade formulas (reuse results) to update several fields within the same statement. And sometimes you'd just prefer to do things in one pass.

  • Nesting queries. Yes at any point you can put parenthesis on your entire query and use it as a subquery upon which you can manipulate source data and calculated fields alike. But you can only do this so much before it gets ugly. Very ugly.

  • Repeating code. What is the greatest value of 3 long (CASE...ELSE...END) statements? That's gonna be readable!

    • Tell your clients to calculate the damn things themselves.

Did I miss something? Probably, so feel free to comment. But hey, CROSS APPLY is like a godsend in such situations: you just add a simple CROSS APPLY (select tbl.value + 1 as someFormula) as crossTbl and voilà! Your new field is now ready for use practically like it had always been there in your source data.

Values introduced through CROSS APPLY can...

  • be used to create one or multiple calculated fields without adding performance, complexity or readability issues to the mix
  • like with JOINs, several subsequent CROSS APPLY statements can refer to themselves: CROSS APPLY (select crossTbl.someFormula + 1 as someMoreFormula) as crossTbl2
  • you can use values introduced by a CROSS APPLY in subsequent JOIN conditions
  • As a bonus, there's the Table-valued function aspect

Dang, there's nothing they can't do!

How to turn off the Eclipse code formatter for certain sections of Java code?

The phantom comments, adding // where you want new lines, are great!

  1. The @formatter: off adds a reference from the code to the editor. The code should, in my opinion, never have such references.

  2. The phantom comments (//) will work regardless of the formatting tool used. Regardless of Eclipse or InteliJ or whatever editor you use. This even works with the very nice Google Java Format

  3. The phantom comments (//) will work all over your application. If you also have Javascript and perhaps use something like JSBeautifier. You can have similar code style also in the Javascript.

  4. Actually, you probably DO want formatting right? You want to remove mixed tab/space and trailing spaces. You want to indent the lines according to the code standard. What you DONT want is a long line. That, and only that, is what the phantom comment gives you!

How / can I display a console window in Intellij IDEA?

I use Shift + F12 to show the Console again (or Window > Restore Default Layout).

To enable that, I have previously saved the layout WITH the console open as default (Window > Store Current Layout as Default).

Go back button in a page

There's a few ways, this is one:

window.history.go(-1);

Add/delete row from a table

Here's the code JS Bin using jQuery. Tested on all the browsers. Here, we have to click the rows in order to delete it with beautiful effect. Hope it helps.

ASP.Net which user account running Web Service on IIS 7?

Look at the Identity of the Application Pool that's running your application. By default it will be the Network Service account, but you can change this.

At least that's how it works on 2003 server, don't know if some details have changed for 2008 server.

How can I add private key to the distribution certificate?

Since the existing answers were written, Xcode's interface has been updated and they're no longer correct (notably the Click on Window, Organiser // Expand the Teams section step). Now the instructions for importing an existing certificate are as follows:

To export selected certificates

  1. Choose Xcode > Preferences.
  2. Click Accounts at the top of the window.
  3. Select the team you want to view, and click View Details.
  4. Control-click the certificate you want to export in the Signing Identities table and choose Export from the pop-up menu.

Export certificate demo

  1. Enter a filename in the Save As field and a password in both the Password and Verify fields. The file is encrypted and password protected.
  2. Click Save. The file is saved to the location you specified with a .p12 extension.

Source (Apple's documentation)

To import it, I found that Xcode's let-me-help-you menu didn't recognise the .p12 file. Instead, I simply imported it manually into Keychain, then Xcode built and archived without complaining.

MySQL wait_timeout Variable - GLOBAL vs SESSION

SHOW SESSION VARIABLES LIKE "wait_timeout"; -- 28800
SHOW GLOBAL VARIABLES LIKE "wait_timeout"; -- 28800

At first, wait_timeout = 28800 which is the default value. To change the session value, you need to set the global variable because the session variable is read-only.

SET @@GLOBAL.wait_timeout=300

After you set the global variable, the session variable automatically grabs the value.

SHOW SESSION VARIABLES LIKE "wait_timeout"; -- 300
SHOW GLOBAL VARIABLES LIKE "wait_timeout"; -- 300

Next time when the server restarts, the session variables will be set to the default value i.e. 28800.

P.S. I m using MySQL 5.6.16

Should operator<< be implemented as a friend or as a member function?

You can not do it as a member function, because the implicit this parameter is the left hand side of the <<-operator. (Hence, you would need to add it as a member function to the ostream-class. Not good :)

Could you do it as a free function without friending it? That's what I prefer, because it makes it clear that this is an integration with ostream, and not a core functionality of your class.

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

If you have control over your server, you can use PHP:

<?PHP
header('Access-Control-Allow-Origin: *');
?>

html form - make inputs appear on the same line

You can make a class for each label and inside it put:

display: inline-block;

And width the value that you need.

numpy max vs amax vs maximum

np.max is just an alias for np.amax. This function only works on a single input array and finds the value of maximum element in that entire array (returning a scalar). Alternatively, it takes an axis argument and will find the maximum value along an axis of the input array (returning a new array).

>>> a = np.array([[0, 1, 6],
                  [2, 4, 1]])
>>> np.max(a)
6
>>> np.max(a, axis=0) # max of each column
array([2, 4, 6])

The default behaviour of np.maximum is to take two arrays and compute their element-wise maximum. Here, 'compatible' means that one array can be broadcast to the other. For example:

>>> b = np.array([3, 6, 1])
>>> c = np.array([4, 2, 9])
>>> np.maximum(b, c)
array([4, 6, 9])

But np.maximum is also a universal function which means that it has other features and methods which come in useful when working with multidimensional arrays. For example you can compute the cumulative maximum over an array (or a particular axis of the array):

>>> d = np.array([2, 0, 3, -4, -2, 7, 9])
>>> np.maximum.accumulate(d)
array([2, 2, 3, 3, 3, 7, 9])

This is not possible with np.max.

You can make np.maximum imitate np.max to a certain extent when using np.maximum.reduce:

>>> np.maximum.reduce(d)
9
>>> np.max(d)
9

Basic testing suggests the two approaches are comparable in performance; and they should be, as np.max() actually calls np.maximum.reduce to do the computation.

printf with std::string?

use myString.c_str() if you want a c-like string (const char*) to use with printf

thanks

How to validate an OAuth 2.0 access token for a resource server?

OAuth v2 specs indicates:

Access token attributes and the methods used to access protected resources are beyond the scope of this specification and are defined by companion specifications.

My Authorisation Server has a webservice (SOAP) endpoint that allows the Resource Server to know whether the access_token is valid.

Is it possible to remove the focus from a text input when a page loads?

use document.activeElement.blur();

example at http://jsfiddle.net/vGGdV/5/ that shows the currently focused element as well.

Keep a note though that calling blur() on the body element in IE will make the IE lose focus

mySQL select IN range

You can't, but you can use BETWEEN

SELECT job FROM mytable WHERE id BETWEEN 10 AND 15

Note that BETWEEN is inclusive, and will include items with both id 10 and 15.

If you do not want inclusion, you'll have to fall back to using the > and < operators.

SELECT job FROM mytable WHERE id > 10 AND id < 15

Java equivalent to JavaScript's encodeURIComponent that produces identical output?

I have successfully used the java.net.URI class like so:

public static String uriEncode(String string) {
    String result = string;
    if (null != string) {
        try {
            String scheme = null;
            String ssp = string;
            int es = string.indexOf(':');
            if (es > 0) {
                scheme = string.substring(0, es);
                ssp = string.substring(es + 1);
            }
            result = (new URI(scheme, ssp, null)).toString();
        } catch (URISyntaxException usex) {
            // ignore and use string that has syntax error
        }
    }
    return result;
}

Stopping Excel Macro executution when pressing Esc won't work

I also like to use MsgBox for debugging, and I've run into this same issue more than once. Now I always add a Cancel button to the popup, and exit the macro if Cancel is pressed. Example code:

    If MsgBox("Debug message", vbOKCancel, "Debugging") = vbCancel Then Exit Sub

Laravel Eloquent - Get one Row

Laravel 5.2

$sql = "SELECT * FROM users WHERE email = $email";

$user = collect(\User::select($sql))->first();

or

$user = User::table('users')->where('email', $email)->pluck();

Can't concatenate 2 arrays in PHP

Use array_merge()
See the documentation here:
http://php.net/manual/en/function.array-merge.php

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

problem with php mail 'From' header

In order to prevent phishing, some mail servers prevent the From from being rewritten.

Handling a timeout error in python sockets

from foo import * 

adds all the names without leading underscores (or only the names defined in the modules __all__ attribute) in foo into your current module.

In the above code with from socket import * you just want to catch timeout as you've pulled timeout into your current namespace.

from socket import * pulls in the definitions of everything inside of socket but doesn't add socket itself.

try:
    # socketstuff
except timeout:
    print 'caught a timeout'

Many people consider import * problematic and try to avoid it. This is because common variable names in 2 or more modules that are imported in this way will clobber one another.

For example, consider the following three python files:

# a.py
def foo():
    print "this is a's foo function"

# b.py
def foo():
    print "this is b's foo function"

# yourcode.py
from a import *
from b import *
foo()

If you run yourcode.py you'll see just the output "this is b's foo function".

For this reason I'd suggest either importing the module and using it or importing specific names from the module:

For example, your code would look like this with explicit imports:

import socket
from socket import AF_INET, SOCK_DGRAM

def main():
    client_socket = socket.socket(AF_INET, SOCK_DGRAM)
    client_socket.settimeout(1)
    server_host = 'localhost'
    server_port = 1234
    while(True):
        client_socket.sendto('Message', (server_host, server_port))
        try:
            reply, server_address_info = client_socket.recvfrom(1024)
            print reply
        except socket.timeout:
            #more code

Just a tiny bit more typing but everything's explicit and it's pretty obvious to the reader where everything comes from.

Python requests - print entire http request (raw)?

An even better idea is to use the requests_toolbelt library, which can dump out both requests and responses as strings for you to print to the console. It handles all the tricky cases with files and encodings which the above solution does not handle well.

It's as easy as this:

import requests
from requests_toolbelt.utils import dump

resp = requests.get('https://httpbin.org/redirect/5')
data = dump.dump_all(resp)
print(data.decode('utf-8'))

Source: https://toolbelt.readthedocs.org/en/latest/dumputils.html

You can simply install it by typing:

pip install requests_toolbelt

Remove header and footer from window.print()

@page { margin: 0; } works fine in Chrome and Firefox. I haven't found a way to fix IE through css. But you can go into Page Setup in IE on your own machine at and set the margins to 0. Press alt and then the file menu in the top left corner and you'll find Page Setup. This only works for the one machine at a time...

When to use static methods

Use a static method when you want to be able to access the method without an instance of the class.

What is the difference between server side cookie and client side cookie?

You probably mean the difference between Http Only cookies and their counter part?

Http Only cookies cannot be accessed (read from or written to) in client side JavaScript, only server side. If the Http Only flag is not set, or the cookie is created in (client side) JavaScript, the cookie can be read from and written to in (client side) JavaScript as well as server side.