Programs & Examples On #Sorteddictionary

Represents a collection of key/value pairs that are sorted on the key.

What's the difference between SortedList and SortedDictionary?

I cracked open Reflector to have a look at this as there seems to be a bit of confusion about SortedList. It is in fact not a binary search tree, it is a sorted (by key) array of key-value pairs. There is also a TKey[] keys variable which is sorted in sync with the key-value pairs and used to binary search.

Here is some source (targeting .NET 4.5) to backup my claims.

Private members

// Fields
private const int _defaultCapacity = 4;
private int _size;
[NonSerialized]
private object _syncRoot;
private IComparer<TKey> comparer;
private static TKey[] emptyKeys;
private static TValue[] emptyValues;
private KeyList<TKey, TValue> keyList;
private TKey[] keys;
private const int MaxArrayLength = 0x7fefffff;
private ValueList<TKey, TValue> valueList;
private TValue[] values;
private int version;

SortedList.ctor(IDictionary, IComparer)

public SortedList(IDictionary<TKey, TValue> dictionary, IComparer<TKey> comparer) : this((dictionary != null) ? dictionary.Count : 0, comparer)
{
    if (dictionary == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
    }
    dictionary.Keys.CopyTo(this.keys, 0);
    dictionary.Values.CopyTo(this.values, 0);
    Array.Sort<TKey, TValue>(this.keys, this.values, comparer);
    this._size = dictionary.Count;
}

SortedList.Add(TKey, TValue) : void

public void Add(TKey key, TValue value)
{
    if (key == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
    }
    int num = Array.BinarySearch<TKey>(this.keys, 0, this._size, key, this.comparer);
    if (num >= 0)
    {
        ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
    }
    this.Insert(~num, key, value);
}

SortedList.RemoveAt(int) : void

public void RemoveAt(int index)
{
    if ((index < 0) || (index >= this._size))
    {
        ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);
    }
    this._size--;
    if (index < this._size)
    {
        Array.Copy(this.keys, index + 1, this.keys, index, this._size - index);
        Array.Copy(this.values, index + 1, this.values, index, this._size - index);
    }
    this.keys[this._size] = default(TKey);
    this.values[this._size] = default(TValue);
    this.version++;
}

Get a random item from a JavaScript array

var item = items[Math.floor(Math.random() * items.length)];

Java BigDecimal: Round to the nearest whole value

You want

round(new MathContext(0));  // or perhaps another math context with rounding mode HALF_UP

How to center a "position: absolute" element

You can try this way :

_x000D_
_x000D_
* { margin: 0px; padding: 0px; }_x000D_
#body { height: 100vh; width: 100vw; position: relative; _x000D_
        text-align: center; _x000D_
        background-image: url('https://s-media-cache-ak0.pinimg.com/originals/96/2d/ff/962dff2247ad680c542622e20f44a645.jpg'); _x000D_
         background-size: cover; background-repeat: no-repeat; }_x000D_
.text { position: absolute; top: 0; bottom: 0; left: 0; right: 0; height:100px; _x000D_
        display: inline-block; margin: auto; z-index: 999999; }
_x000D_
<html>_x000D_
<body>_x000D_
 <div id="body" class="container-fluid">_x000D_
   <!--Background-->_x000D_
     <!--Text-->_x000D_
    <div class="text">_x000D_
      <p>Random</p>_x000D_
    </div>   _x000D_
 </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

GenyMotion Unable to start the Genymotion virtual device

it worked for me when I start Gennymotion in Admin mode

Limit length of characters in a regular expression?

Is there a way to limit a regex to 100 characters WITH regex?

Your example suggests that you'd like to grab a number from inside the regex and then use this number to place a maximum length on another part that is matched later in the regex. This usually isn't possible in a single pass. Your best bet is to have two separate regular expressions:

  • one to match the maximum length you'd like to use
  • one which uses the previously extracted value to verify that its own match does not exceed the specified length

If you just want to limit the number of characters matched by an expression, most regular expressions support bounds by using braces. For instance,

\d{3}-\d{3}-\d{4}

will match (US) phone numbers: exactly three digits, then a hyphen, then exactly three digits, then another hyphen, then exactly four digits.

Likewise, you can set upper or lower limits:

\d{5,10}

means "at least 5, but not more than 10 digits".


Update: The OP clarified that he's trying to limit the value, not the length. My new answer is don't use regular expressions for that. Extract the value, then compare it against the maximum you extracted from the size parameter. It's much less error-prone.

Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?

I use that construction whenever I don't want to add complexity to the problem. It's just a list, no need to say what kind of List it is, as it doesn't matter to the problem. I often use Collection for most of my solutions, as, in the end, most of the times, for the rest of the software, what really matters is the content it holds, and I don't want to add new objects to the Collection.

Futhermore, you use that construction when you think that you may want to change the implemenation of list you are using. Let's say you were using the construction with an ArrayList, and your problem wasn't thread safe. Now, you want to make it thread safe, and for part of your solution, you change to use a Vector, for example. As for the other uses of that list won't matter if it's a AraryList or a Vector, just a List, no new modifications will be needed.

Hide axis and gridlines Highcharts

Just add

xAxis: {
   ...  
   lineWidth: 0,
   minorGridLineWidth: 0,
   lineColor: 'transparent',
   ...          
   labels: {
       enabled: false
   },
   minorTickLength: 0,
   tickLength: 0
}

to the xAxis definition.

Since Version 4.1.9 you can simply use the axis attribute visible:

xAxis: {
    visible: false,
}

How do I create a table based on another table

There is no such syntax in SQL Server, though CREATE TABLE AS ... SELECT does exist in PDW. In SQL Server you can use this query to create an empty table:

SELECT * INTO schema.newtable FROM schema.oldtable WHERE 1 = 0;

(If you want to make a copy of the table including all of the data, then leave out the WHERE clause.)

Note that this creates the same column structure (including an IDENTITY column if one exists) but it does not copy any indexes, constraints, triggers, etc.

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are synonyms, no difference at all.Decimal and Numeric data types are numeric data types with fixed precision and scale.

-- Initialize a variable, give it a data type and an initial value

declare @myvar as decimal(18,8) or numeric(18,8)----- 9 bytes needed

-- Increse that the vaue by 1

set @myvar = 123456.7

--Retrieve that value

select @myvar as myVariable

Change navbar text color Bootstrap

For changing the text color in navbar you can use inline css as;

<a style="color: #3c6afc" href="#">

Why can't I do <img src="C:/localfile.jpg">?

IE 9 : If you want that the user takes a look at image before he posts it to the server : The user should ADD the website to "trusted Website list".

Running script upon login mac

  1. Create your shell script as login.sh in your $HOME folder.

  2. Paste the following one-line script into Script Editor:

    do shell script "$HOME/login.sh"

  3. Then save it as an application.

  4. Finally add the application to your login items.

If you want to make the script output visual, you can swap step 2 for this:

tell application "Terminal"
  activate
  do script "$HOME/login.sh"
end tell

If multiple commands are needed something like this can be used:

tell application "Terminal"
  activate
  do script "cd $HOME"
  do script "./login.sh" in window 1
end tell

Failed to load ApplicationContext (with annotation)

Your test requires a ServletContext: add @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT

...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

UPDATE In Spring Boot 1.4.x and above @WebIntegrationTest is no longer preferred. @SpringBootTest or @WebMvcTest

Passing parameter via url to sql server reporting service

Try changing "Reports" to "ReportServer" in your url. For that just access this http://host/ReportServer/ and from there you can go to the report pages. There append your parmaters like this &<parameter>=<value>

For more detailed information:

http://dobrzanski.net/2008/08/11/reporting-services-problem-with-passing-parameters-directly-in-the-url/

https://www.mssqltips.com/sqlservertip/1336/pass-parameters-and-options-with-a-url-in-sql-reporting-services/

How to get first 5 characters from string

Use substr():

$result = substr($myStr, 0, 5);

Launch Bootstrap Modal on page load

Update 2020 - Bootstrap 5

Building on the excellent responses from previous answers, in Bootstrap 5 with no jQuery, this has worked;

document.querySelector('[data-target="#exampleModal"]').click();

Full snippet:

_x000D_
_x000D_
window.onload = () => {
  document.querySelector('[data-target="#exampleModal"]').click();
}
_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" rel="stylesheet" />


<div class="container py-3">

  <!-- Button trigger modal -->
  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
    Launch demo modal
  </button>

  <!-- Modal -->
  <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          ...
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>

</div>
_x000D_
_x000D_
_x000D_

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

While integrating material dialog is possible, I found that the complexity for such a trivial feature is pretty high. The code gets more complex if you are trying to achieve a non-trivial features.

For that reason, I ended up using PrimeNG Dialog, which I found pretty straightforward to use:

m-dialog.component.html:

<p-dialog header="Title">
  Content
</p-dialog>

m-dialog.component.ts:

@Component({
  selector: 'm-dialog',
  templateUrl: 'm-dialog.component.html',
  styleUrls: ['./m-dialog.component.css']
})
export class MDialogComponent {
  // dialog logic here
}

m-dialog.module.ts:

import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { DialogModule } from "primeng/primeng";
import { FormsModule } from "@angular/forms";

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    DialogModule
  ], 
  exports: [
    MDialogComponent,
  ], 
  declarations: [
    MDialogComponent
  ]
})
export class MDialogModule {}

Simply add your dialog into your component's html:

<m-dialog [isVisible]="true"> </m-dialog>

PrimeNG PrimeFaces documentation is easy to follow and very precise.

How do I get the current date in JavaScript?

What's the big deal with this.. The cleanest way to do this is

var currentDate=new Date().toLocaleString().slice(0,10);

Access files stored on Amazon S3 through web browser

Filestash is the perfect tool for that:

  1. login to your bucket from https://www.filestash.app/s3-browser.html:

enter image description here

  1. create a shared link:

enter image description here

  1. Share it with the world

Also Filestash is open source. (Disclaimer: I am the author)

HTML CSS Invisible Button

HTML

<input type="button">

CSS

input[type=button]{
 background:transparent;
 border:0;
}

A connection was successfully established with the server, but then an error occurred during the pre-login handshake

Same problem here and no answers listed here worked, nor any solutions I could find online. The issue started shortly after Windows 10 anniversary update got applied on my dev PC and only affected my old SQL Server 2005 instance. I was not able to connect to the instance via my Web Applications or even using Sql Management Studio.

For what it's worth, this is what resolved it for me:

  1. Open SQL Server Configuration Manager (depending on what version of SQL Server you're running):

    • C:\Windows\SysWOW64\SQLServerManager.msc
    • C:\Windows\SysWOW64\SQLServerManager10.msc OR
    • C:\Windows\SysWOW64\SQLServerManager12.msc OR
    • etc
  2. Select SQL Server Services

  3. Locate the troubled service and view Properties

    • eg SQL Server (SQL2005) in my case
  4. In the Log On tab, change the "Built-in account" to "Network Service"

Which is almost what this random solution said: http://www.kutayzorlu.com/operating-systems/linux-unix-redhat-debian-ubuntu-opensuse-centos/general-server-administrating/error-fixed-a-connection-was-successfully-established-with-the-server-but-then-an-error-occurred-during-the-pre-login-handshake-12405.html

I chose Network Service for no reason at all. Mine was already configured to use Local System. This security doesn't matter to me as it was only problematic on my Local development machine, only accessed locally. I can't advise why this works, but it did.

How to trim leading and trailing white spaces of a string?

Just as @Kabeer has mentioned, you can use TrimSpace and here is an example from golang documentation:

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.TrimSpace(" \t\n Hello, Gophers \n\t\r\n"))
}

Unable to show a Git tree in terminal

Keeping your commands short will make them easier to remember:

git log --graph --oneline

SQL query, if value is null then return 1

try like below...

CASE 
WHEN currate.currentrate is null THEN 1
ELSE currate.currentrate
END as currentrate

System.MissingMethodException: Method not found?

For posterity, I ran into this with an azure function, using the azure durable function / durable tasks framework. It turns out I had an outdated version of the azure functions runtime installed locally. updating it fixed it.

Defining a percentage width for a LinearLayout?

I think Emiam's approach is right. But also agree with Simon Veloper (one of commentators of Emiam's answer) : When we need the buttons in 70% of width, we should use horizontal orientation for Linearlayout and set width of each Relativelayout to 0dip and their weight as specified So I suggest this version :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:id="@+id/layoutContainer" android:orientation="horizontal">
    <RelativeLayout
            android:layout_width="0dip"
            android:layout_height="fill_parent"
            android:layout_weight="3">
    </RelativeLayout>
    <RelativeLayout
            android:layout_width="0dip"
            android:layout_height="fill_parent"
            android:layout_weight="14">

            //This is where you add buttons. You can make them "fill_parent".
    </RelativeLayout>
    <RelativeLayout
            android:layout_width="0dip"
            android:layout_height="fill_parent"
            android:layout_weight="3">
    </RelativeLayout>
</LinearLayout>

How to Replace Multiple Characters in SQL?

Here are the steps

  1. Create a CLR function

See following code:

public partial class UserDefinedFunctions 
{

[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString Replace2(SqlString inputtext, SqlString filter,SqlString      replacewith)
{

    string str = inputtext.ToString();
    try
    {
        string pattern = (string)filter;
        string replacement = (string)replacewith;
        Regex rgx = new Regex(pattern);
        string result = rgx.Replace(str, replacement);
        return (SqlString)result;

    }
    catch (Exception s)
    {
        return (SqlString)s.Message;
    }
}
}
  1. Deploy your CLR function

  2. Now Test it

See following code:

create table dbo.test(dummydata varchar(255))
Go
INSERT INTO dbo.test values('P@ssw1rd'),('This 12is @test')
Go
Update dbo.test
set dummydata=dbo.Replace2(dummydata,'[0-9@]','')

select * from dbo.test
dummydata, Psswrd, This is test booom!!!!!!!!!!!!!

ImportError: No module named 'MySQL'

May be simple install from cli?

pip3 install mysql-connector-python-rf

Package name differs from import library name

Or my universal variant in code:

import pip
pip.main(['install','mysql-connector-python-rf'])

For new version of pip:

from pip._internal import main
main(['install','mysql-connector-python-rf'])

It's better - install needed modules in running python installation (if many)

Set cookie and get cookie with JavaScript

These are much much better references than w3schools (the most awful web reference ever made):

Examples derived from these references:

// sets the cookie cookie1
document.cookie = 'cookie1=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

// sets the cookie cookie2 (cookie1 is *not* overwritten)
document.cookie = 'cookie2=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

// remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'

The Mozilla reference even has a nice cookie library you can use.

Python conversion from binary string to hexadecimal

>>> import string
>>> s="0000 0100 1000 1101"
>>> ''.join([ "%x"%string.atoi(bin,2) for bin in s.split() ]  )
'048d'
>>>

or

>>> s="0000 0100 1000 1101"
>>> hex(string.atoi(s.replace(" ",""),2))
'0x48d'

TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

This worked for me like a magic.

I logged into database and registered the listener.

alter system set local_listener='(...)';
alter system register;

Embedding Windows Media Player for all browsers

May I suggest the jQuery Media Plugin? Provides embed code for all kinds of video, not just WMV and does browser detection, keeping all that messy switch/case statements out of your templates.

ImportError: No Module named simplejson

@noskio is correct... it just means that simplejson isn't found on your system and you need to install it for Python older than 2.6. one way is to use the setuptools easy_install tool. with it, you can install it as easily as: easy_install simplejson

UPDATE (Feb 2014): this is probably old news to many of you, but pip is a more modern tool that works in a similar way (i.e., pip install simplejson), only it can also uninstall apps.

Is there a way to create xxhdpi, xhdpi, hdpi, mdpi and ldpi drawables from a large scale image?

I had using solution all this way in this thread, and it's easy working with plugin Android Drawable Importer

If u using Android Studio on MacOS, just try this step to get in:

  • Click bar menu Android Studio then choose Preferences or tap button Command + ,
  • Then choose Plugins
  • Click Browse repositories
  • Write in the search coloumn Android Drawable Importer
  • Click Install button
  • And then dialog Restart is showing, just restart it Android Studio

After ur success installing the plugin, to work it this plugin just click create New menu and then choose Batch Drawable Import. Then click plus button a.k.a Add button, and go choose your file to make drawable. And then just click ok and ok the drawable has make it all of them.

If u confused with my word, just see the image tutorial from learningmechine.

Disable button after click in JQuery

*Updated

jQuery version would be something like below:

function load(recieving_id){
    $('#roommate_but').prop('disabled', true);
    $.get('include.inc.php?i=' + recieving_id, function(data) {
        $("#roommate_but").html(data);
    });
}

How to use apply a custom drawable to RadioButton?

You should set android:button="@null" instead of "null".

You were soo close!

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

From the Errata: ModelState.AddRuleViolations(dinner.GetRuleViolations());

Should be:

ModelState.AddModelErrors(dinner.GetRuleViolations());

Reference: http://www.wrox.com/WileyCDA/WroxTitle/Professional-ASP-NET-MVC-1-0.productCd-0470384611,descCd-ERRATA.html

C# Clear Session

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Session.Abandon() destroys the session and the Session_OnEnd event is triggered.

Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.

So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.

Use Session.Clear(), if you want that the user remaining in the same session (if you don't want him to relogin for example) and reset all his session specific data.

What is the difference between Session.Abandon() and Session.Clear()

Clear - Removes all keys and values from the session-state collection.

Abandon - removes all the objects stored in a Session. If you do not call the Abandon method explicitly, the server removes these objects and destroys the session when the session times out. It also raises events like Session_End.

Session.Clear can be compared to removing all books from the shelf, while Session.Abandon is more like throwing away the whole shelf.

...

Generally, in most cases you need to use Session.Clear. You can use Session.Abandon if you are sure the user is going to leave your site.

So back to the differences:

  • Abandon raises Session_End request.
  • Clear removes items immediately, Abandon does not.
  • Abandon releases the SessionState object and its items so it can garbage collected.
  • Clear keeps SessionState and resources associated with it.

Session.Clear() or Session.Abandon() ?

You use Session.Clear() when you don't want to end the session but rather just clear all the keys in the session and reinitialize the session.

Session.Clear() will not cause the Session_End eventhandler in your Global.asax file to execute.

But on the other hand Session.Abandon() will remove the session altogether and will execute Session_End eventhandler.

Session.Clear() is like removing books from the bookshelf

Session.Abandon() is like throwing the bookshelf itself.

Question

I check on some sessions if not equal null in the page load. if one of them equal null i wanna to clear all the sessions and redirect to the login page?

Answer

If you want the user to login again, use Session.Abandon.

Resource u'tokenizers/punkt/english.pickle' not found

You need to rearrange your folders Move your tokenizers folder into nltk_data folder. This doesn't work if you have nltk_data folder containing corpora folder containing tokenizers folder

How to flip background image using CSS?

I found I way to flip only the background not whole element after seeing a clue to flip in Alex's answer. Thanks alex for your answer

HTML

<div class="prev"><a href="">Previous</a></div>
<div class="next"><a href="">Next</a></div>

CSS

.next a, .prev a {
    width:200px;
    background:#fff
}
 .next {
    float:left
}
 .prev {
    float:right
}
 .prev a:before, .next a:before {
    content:"";
    width:16px;
    height:16px;
    margin:0 5px 0 0;
    background:url(http://i.stack.imgur.com/ah0iN.png) no-repeat 0 0;
    display:inline-block 
}
 .next a:before {
    margin:0 0 0 5px;
    transform:scaleX(-1);
}

See example here http://jsfiddle.net/qngrf/807/

How to advance to the next form input when the current input has a value?

Needed to emulate the tab functionality a while ago, and now I've released it as a library that uses .

EmulateTab: A jQuery plugin to emulate tabbing between elements on a page.

You can see how it works in the demo.

if (myTextHasBeenFilledWithText) {
  // Tab to the next input after #my-text-input
  $("#my-text-input").emulateTab();
}

HTTP vs HTTPS performance

There isn't a single answer for this.

Encryption will always consume more CPU. This can be offloaded to dedicated hardware in many cases, and the cost will vary by algorithm selected. 3des is more expensive than AES, for example. Some algorithms are more expensive for the encrypter than the decryptor. Some have the opposite cost.

More expensive than the bulk crypto is handshake cost. New connections will consume much more CPU. This can be reduced with session resumption, at the cost of keeping old session secrets around until they expire. This means that small requests from a client that doesn't come back for more are the most expensive.

For cross internet traffic you may not notice this cost in your data rate, because the bandwidth available is too low. But you will certainly notice it in CPU usage on a busy server.

Split comma-separated input box values into array in jquery, and loop through it

use js split() method to create an array

var keywords = $('#searchKeywords').val().split(",");

then loop through the array using jQuery.each() function. as the documentation says:

In the case of an array, the callback is passed an array index and a corresponding array value each time

$.each(keywords, function(i, keyword){
   console.log(keyword);
});

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

git-diff to ignore ^M

Developing on Windows, I ran into this problem when using git tfs. I solved it this way:

git config --global core.whitespace cr-at-eol

This basically tells Git that an end-of-line CR is not an error. As a result, those annoying ^M characters no longer appear at the end of lines in git diff, git show, etc.

It appears to leave other settings as-is; for instance, extra spaces at the end of a line still show as errors (highlighted in red) in the diff.

(Other answers have alluded to this, but the above is exactly how to set the setting. To set the setting for only one project, omit the --global.)

EDIT:

After many line-ending travails, I've had the best luck, when working on a .NET team, with these settings:

  • NO core.eol setting
  • NO core.whitespace setting
  • NO core.autocrlf setting
  • When running the Git installer for Windows, you'll get these three options:
    • Checkout Windows-style, commit Unix-style line endings <-- choose this one
    • Checkout as-is, commit Unix-style line endings
    • Checkout as-is, commit as-is

If you need to use the whitespace setting, you should probably enable it only on a per-project basis if you need to interact with TFS. Just omit the --global:

git config core.whitespace cr-at-eol

If you need to remove some core.* settings, the easiest way is to run this command:

git config --global -e

This opens your global .gitconfig file in a text editor, and you can easily delete the lines you want to remove. (Or you can put '#' in front of them to comment them out.)

How do I perform a GROUP BY on an aliased column in MS-SQL Server?

In the old FoxPro (I haven't used it since version 2.5), you could write something like this:

SELECT       LastName + ', ' + FirstName AS 'FullName', Birthday, Title
FROM         customers
GROUP BY     1,3,2

I really liked that syntax. Why isn't it implemented anywhere else? It's a nice shortcut, but I assume it causes other problems?

Using PropertyInfo.GetValue()

In your example propertyInfo.GetValue(this, null) should work. Consider altering GetNamesAndTypesAndValues() as follows:

public void GetNamesAndTypesAndValues()
{
  foreach (PropertyInfo propertyInfo in allClassProperties)
  {
    Console.WriteLine("{0} [type = {1}] [value = {2}]",
      propertyInfo.Name,
      propertyInfo.PropertyType,
      propertyInfo.GetValue(this, null));
  }
}

What is the correct way to represent null XML elements?

The documentation in the w3 link

http://www.w3.org/TR/REC-xml/#sec-starttags

says that this are the recomended forms.

<test></test>
<test/>

The attribute mentioned in the other answer is validation mechanism and not a representation of state. Please refer to the http://www.w3.org/TR/xmlschema-1/#xsi_nil

XML Schema: Structures introduces a mechanism for signaling that an element should be accepted as ·valid· when it has no content despite a content type which does not require or even necessarily allow empty content. An element may be ·valid· without content if it has the attribute xsi:nil with the value true. An element so labeled must be empty, but can carry attributes if permitted by the corresponding complex type.

To clarify this answer: Content

  <Book>
    <!--Invalid construct since the element attribute xsi:nil="true" signal that the element must be empty-->
    <BuildAttributes HardCover="true" Glued="true" xsi:nil="true">
      <anotherAttribute name="Color">Blue</anotherAttribute>
    </BuildAttributes>
    <Index></Index>
    <pages>
      <page pageNumber="1">Content</page>            
    </pages>
    <!--Missing ISBN number could be confusing and misguiding since its not present-->
  </Book>
</Books>

Visual Studio: How to show Overloads in IntelliSense?

Try the keyboard shortcut Ctrl-Shift-Space. This corresponds to Edit.ParameterInfo, in case you've changed the default.

Example:

descriptive screenshot, by jp2code

Windows batch: sleep

timeout /t 10 /nobreak > NUL

/t specifies the time to wait in seconds

/nobreak won't interrupt the timeout if you press a key (except CTRL-C)

> NUL will suppress the output of the command

how to sort pandas dataframe from one column

Use sort_values to sort the df by a specific column's values:

In [18]:
df.sort_values('2')

Out[18]:
        0          1     2
4    85.6    January   1.0
3    95.5   February   2.0
7   104.8      March   3.0
0   354.7      April   4.0
8   283.5        May   5.0
6   238.7       June   6.0
5   152.0       July   7.0
1    55.4     August   8.0
11  212.7  September   9.0
10  249.6    October  10.0
9   278.8   November  11.0
2   176.5   December  12.0

If you want to sort by two columns, pass a list of column labels to sort_values with the column labels ordered according to sort priority. If you use df.sort_values(['2', '0']), the result would be sorted by column 2 then column 0. Granted, this does not really make sense for this example because each value in df['2'] is unique.

Activate a virtualenv with a Python script

Just a simple solution that works for me. I don't know why you need the Bash script which basically does a useless step (am I wrong ?)

import os
os.system('/bin/bash  --rcfile flask/bin/activate')

Which basically does what you need:

[hellsing@silence Foundation]$ python2.7 pythonvenv.py
(flask)[hellsing@silence Foundation]$

Then instead of deactivating the virtual environment, just Ctrl + D or exit. Is that a possible solution or isn't that what you wanted?

How to disable GCC warnings for a few lines of code

TL;DR: If it works, avoid, or use specifiers like __attribute__, otherwise _Pragma.

This is a short version of my blog article Suppressing Warnings in GCC and Clang.

Consider the following Makefile

CPPFLAGS:=-std=c11 -W -Wall -pedantic -Werror

.PHONY: all
all: puts

for building the following puts.c source code

#include <stdio.h>

int main(int argc, const char *argv[])
{
    while (*++argv) puts(*argv);
    return 0;
}

It will not compile because argc is unused, and the settings are hardcore (-W -Wall -pedantic -Werror).

There are 5 things you could do:

  • Improve the source code, if possible
  • Use a declaration specifier, like __attribute__
  • Use _Pragma
  • Use #pragma
  • Use a command line option.

Improving the source

The first attempt should be checking if the source code can be improved to get rid of the warning. In this case we don't want to change the algorithm just because of that, as argc is redundant with !*argv (NULL after last element).

Using a declaration specifier, like __attribute__

#include <stdio.h>

int main(__attribute__((unused)) int argc, const char *argv[])
{
    while (*++argv) puts(*argv);
    return 0;
}

If you're lucky, the standard provides a specifier for your situation, like _Noreturn.

__attribute__ is proprietary GCC extension (supported by Clang and some other compilers like armcc as well) and will not be understood by many other compilers. Put __attribute__((unused)) inside a macro if you want portable code.

_Pragma operator

_Pragma can be used as an alternative to #pragma.

#include <stdio.h>

_Pragma("GCC diagnostic push")
_Pragma("GCC diagnostic ignored \"-Wunused-parameter\"")

int main(int argc, const char *argv[])
{
    while (*++argv) puts(*argv);
    return 0;
}
_Pragma("GCC diagnostic pop")

The main advantage of the _Pragma operator is that you could put it inside macros, which is not possible with the #pragma directive.

Downside: It's almost a tactical nuke, as it works line-based instead of declaration-based.

The _Pragma operator was introduced in C99.

#pragma directive.

We could change the source code to suppress the warning for a region of code, typically an entire function:

#include <stdio.h>

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
int main(int argc, const char *argv[])
{
    while (*++argc) puts(*argv);
    return 0;
}
#pragma GCC diagnostic pop

Downside: It's almost a tactical nuke, as it works line-based instead of declaration-based.

Note that a similar syntax exists in clang.

Suppressing the warning on the command line for a single file

We could add the following line to the Makefile to suppress the warning specifically for puts:

CPPFLAGS:=-std=c11 -W -Wall -pedantic -Werror

.PHONY: all
all: puts

puts.o: CPPFLAGS+=-Wno-unused-parameter

This is probably not want you want in your particular case, but it may help other reads who are in similar situations.

How may I reference the script tag that loaded the currently-executing script?

I've got this, which is working in FF3, IE6 & 7. The methods in the on-demand loaded scripts aren't available until page load is complete, but this is still very useful.

//handle on-demand loading of javascripts
makescript = function(url){
    var v = document.createElement('script');
    v.src=url;
    v.type='text/javascript';

    //insertAfter. Get last <script> tag in DOM
    d=document.getElementsByTagName('script')[(document.getElementsByTagName('script').length-1)];
    d.parentNode.insertBefore( v, d.nextSibling );
}

laravel compact() and ->with()

You can pass array of variables to the compact as an arguement eg:

return view('yourView', compact(['var1','var2',....'varN']));

in view: if var1 is an object you can use it something like this

@foreach($var1 as $singleVar1)
    {{$singleVar1->property}}
@endforeach

incase of single variable you can simply

{{$var2}}

i have done this several times without any issues

How to get label of select option with jQuery?

Try this:

$('select option:selected').text();

How to prompt for user input and read command-line arguments

To read user input you can try the cmd module for easily creating a mini-command line interpreter (with help texts and autocompletion) and raw_input (input for Python 3+) for reading a line of text from the user.

text = raw_input("prompt")  # Python 2
text = input("prompt")  # Python 3

Command line inputs are in sys.argv. Try this in your script:

import sys
print (sys.argv)

There are two modules for parsing command line options: optparse (deprecated since Python 2.7, use argparse instead) and getopt. If you just want to input files to your script, behold the power of fileinput.

The Python library reference is your friend.

How to retrieve all keys (or values) from a std::map and put them into a vector?

With the structured binding (“destructuring”) declaration syntax of C++17,

you can do this, which is easier to understand.

// To get the keys
std::map<int, double> map;
std::vector<int> keys;
keys.reserve(map.size());
for(const auto& [key, value] : map) {
    keys.push_back(key);
}
// To get the values
std::map<int, double> map;
std::vector<double> values;
values.reserve(map.size());
for(const auto& [key, value] : map) {
    values.push_back(value);
}

Spring: How to inject a value to static field?

This is my sample code for load static variable

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class OnelinkConfig {
    public static int MODULE_CODE;
    public static int DEFAULT_PAGE;
    public static int DEFAULT_SIZE;

    @Autowired
    public void loadOnelinkConfig(@Value("${onelink.config.exception.module.code}") int code,
            @Value("${onelink.config.default.page}") int page, @Value("${onelink.config.default.size}") int size) {
        MODULE_CODE = code;
        DEFAULT_PAGE = page;
        DEFAULT_SIZE = size;
    }
}

Test iOS app on device without apple developer program or jailbreak

Go to Build Settings, under Code Signing, set Code Signing Identity as iOS Developer & Provisioning Profile as Automatic.

Select your device (now visible) from drop down list and run your app.

enter image description here

Show Current Location and Nearby Places and Route between two places using Google Maps API in Android

You can use google map Obtaining User Location here!

After obtaining your location(longitude and latitude), you can use google place api

This code can help you get your location easily but not the best way.

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);  

TypeError: 'undefined' is not a function (evaluating '$(document)')

You can use both jQuery and $ in below snippet. it worked for me

jQuery( document ).ready(function( $ ) {
  // jQuery(document)
  // $(document)
});

Can I set text box to readonly when using Html.TextBoxFor?

To make it read only

@Html.TextBoxFor(m=> m.Total, new {@class ="form-control", @readonly="true"})

To diable

@Html.TextBoxFor(m=> m.Total, new {@class ="form-control", @disabled="true"})

How to correctly write async method?

You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task or Task<T>, if you return nothing and you want your method will be run asyncronously you should define your method like this:

private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } 

And in Main method you can't await for DoDownloadAsync, because you can't use await keyword in non-async function, and you can't make Main async. So consider this:

var result = DoDownloadAsync();  Debug.WriteLine("DoDownload done"); result.Wait(); 

Pure CSS multi-level drop-down menu

<div class="example" align="center">
    <div class="menuholder">
        <ul class="menu slide">
            <li><a href="index.php?id=1" class="blue">Home</a></li>
        <li><a href="index.php?id=14" class="blue">About Us</a></li>
            <li><a href="index.php?id=4" class="blue">Mens</a>
                <div class="subs">
                    <dl>
                        <dd><a href="index.php?id=15">Coats & Jackets</a></dd>
                        <dd><a href="index.php?id=22">Chinos</a></dd>
                        <dd><a href="index.php?id=23">Jeans</a></dd>
                        <dd><a href="index.php?id=24">Jumpers & Cardigans</a></dd>
                        <dd><a href="index.php?id=25">Linen</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=26">Polo Shirts</a></dd>
                        <dd><a href="index.php?id=16">Shirts Casual</a></dd>
                        <dd><a href="index.php?id=27">Shirts Formal</a></dd>
                        <dd><a href="index.php?id=28">Shorts</a></dd>
                        <dd><a href="index.php?id=18">Sportswear</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=19">Tops & T-Shirts</a></dd>
                        <dd><a href="index.php?id=20">Trousers Casual</a></dd>
                        <dd><a href="index.php?id=29">Trousers Formal</a></dd>
                        <dd><a href="index.php?id=30">Nightwear</a></dd>
                        <dd><a href="index.php?id=17">Socks</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=21">Underwear</a></dd>
                        <dd><a href="index.php?id=31">Swimwear</a></dd>
                    </dl>
                </div>
            </li>
            <!--menu-->
                        <li><a href="index.php?id=5" class="blue">Ladie's</a>
                <div class="subs">
                    <dl>
                          <dd><a href="index.php?id=32">Coats & Jackets</a></dd>
                          <dd><a href="index.php?id=33">Dresses</a></dd>
                          <dd><a href="index.php?id=34">Jeans</a></dd>
                          <dd><a href="index.php?id=35">Jumpers & Cardigans</a></dd>
                          <dd><a href="index.php?id=36">Jumpsuits</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=37">Leggings & Jeggings</a></dd>
                          <dd><a href="index.php?id=38">Linen</a></dd>
                          <dd><a href="index.php?id=39">Lingerie & Underwear</a></dd>
                          <dd><a href="index.php?id=40">Maternity Wear</a></dd>
                          <dd><a href="index.php?id=41">Nightwear</a></dd>
                    </dl>
                    <dl>
                     <dd><a href="index.php?id=42">Shorts</a></dd>
                          <dd><a href="index.php?id=43">Skirts</a></dd>
                          <dd><a href="index.php?id=44">Sportswear</a></dd>
                          <dd><a href="index.php?id=45">Suits & Tailoring</a></dd>
                          <dd><a href="index.php?id=46">Swimwear & Beachwear</a></dd>
                    </dl>
                    <dl>
                          <dd><a href="index.php?id=47">Thermals</a></dd>
                          <dd><a href="index.php?id=48">Tops & T-Shirts</a></dd>
                          <dd><a href="index.php?id=49">Trousers & Chinos</a></dd>
                          <dd><a href="index.php?id=50">Socks</a></dd>
                    </dl>
                </div>
            </li><!--menu end-->
                        <!--menu-->
                        <li><a href="index.php?id=7" class="blue">Girls</a>
                <div class="subs">
                    <dl>
                            <dd><a href="index.php?id=51">Coats & Jackets</a></dd>
                          <dd><a href="index.php?id=52">Dresses</a></dd>
                          <dd><a href="index.php?id=53">Jeans</a></dd>
                          <dd><a href="index.php?id=54">Joggers & Sweatshirts</a></dd>
                          <dd><a href="index.php?id=55">Jumpers & Cardigans</a></dd>
                    </dl>
                    <dl>
                                <dd><a href="index.php?id=56">Jumpsuits & Playsuits</a></dd>
                              <dd><a href="index.php?id=57">Leggings</a></dd>
                              <dd><a href="index.php?id=58">Nightwear</a></dd>
                              <dd><a href="index.php?id=59">Shorts</a></dd>
                              <dd><a href="index.php?id=60">Skirts</a></dd>
                    </dl>
                    <dl>
                              <dd><a href="index.php?id=61">Swimwear</a></dd>
                              <dd><a href="index.php?id=62">Tops & T-Shirts</a></dd>
                              <dd><a href="index.php?id=63">Trousers & Jeans</a></dd>
                              <dd><a href="index.php?id=64">Socks</a></dd>
                              <dd><a href="index.php?id=65">Underwear</a></dd>
                    </dl>
                    <dl>

                    </dl>
                </div>
            </li><!--menu end-->
                            <!--menu-->
                        <li><a href="index.php?id=8" class="blue">Boys</a>
                <div class="subs">
                    <dl>
                        <dd><a href="index.php?id=66">Coats & Jackets</a></dd>
                          <dd><a href="index.php?id=67">Jeans</a></dd>
                          <dd><a href="index.php?id=68">Joggers & Sweatshirts</a></dd>
                          <dd><a href="index.php?id=69">Jumpers & Cardigans</a></dd>
                          <dd><a href="index.php?id=70">Nightwear</a></dd>
                    </dl>
                    <dl>
                            <dd><a href="index.php?id=71">Shirts</a></dd>
                          <dd><a href="index.php?id=72">Shorts</a></dd>
                          <dd><a href="index.php?id=73">Sportswear</a></dd>
                          <dd><a href="index.php?id=74">Swimwear</a></dd>
                          <dd><a href="index.php?id=75">T-Shirts & Polo Shirts</a></dd>
                    </dl>
                    <dl>
                          <dd><a href="index.php?id=76">Trousers & Jeans</a></dd>
                          <dd><a href="index.php?id=77">Socks</a></dd>
                          <dd><a href="index.php?id=78">Underwear</a></dd>
                    </dl>
                    <dl>

                    </dl>
                </div>
            </li><!--menu end-->
            <!--menu-->
             <li><a href="index.php?id=9" class="blue">Toddlers</a>
                <div class="subs">
                    <dl>
                      <dd><a href="index.php?id=79">Newborn</a></dd>
                      <dd><a href="index.php?id=80">0-2 Years</a></dd>
                    </dl>                 
                </div>
            </li><!--menu end-->
            <!--menu-->
             <li><a href="index.php?id=10" class="blue">Accessories</a>
                <div class="subs">
                    <dl>
                          <dd><a href="index.php?id=81">Shoes</a></dd>
                          <dd><a href="index.php?id=82">Ties</a></dd>
                          <dd><a href="index.php?id=83">Caps</a></dd>
                          <dd><a href="index.php?id=84">Belts</a></dd>
                    </dl>                 
                </div>
            </li><!--menu end-->
            <li><a href="index.php?id=13" class="blue">Contact Us</a></li>
        </ul>
        <div class="back"></div>
        <div class="shadow"></div>
    </div>
    <div style="clear:both"></div>
</div>

CSS 3 Coding- Copy and Paste

<style>

body{margin:0px;}
.example {
    width:980px;
    height:40px;
    margin:0px auto;
 position:absolute;
 margin-bottom:60px;
 top:95px;
}

.menuholder {
    float:left;
    font:normal bold 11px/35px verdana, sans-serif;
    overflow:hidden;
    position:relative;
}
.menuholder .shadow {
    -moz-box-shadow:0 0 20px rgba(0, 0, 0, 1);
    -o-box-shadow:0 0 20px rgba(0, 0, 0, 1);
    -webkit-box-shadow:0 0 20px rgba(0, 0, 0, 1);
    background:#888;
    box-shadow:0 0 20px rgba(0, 0, 0, 1);
    height:10px;
    left:5%;
    position:absolute;
    top:-9px;
    width:100%;
    z-index:100;
}
.menuholder .back {
    -moz-transition-duration:.4s;
    -o-transition-duration:.4s;
    -webkit-transition-duration:.4s;
    background-color:rgba(0, 0, 0, 0.88);
    height:0;
    width:980px; /*100%*/
}
.menuholder:hover div.back {
    height:280px;
}
ul.menu {
    display:block;
    float:left;
    list-style:none;
    margin:0;
    padding:0 125px;
    position:relative;
}
ul.menu li {
    float:left;
    margin:0 10px 0 0;
}
ul.menu li > a {
    -moz-border-radius:0 0 10px 10px;
    -moz-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    -moz-transition:all 0.3s ease-in-out;
    -o-border-radius:0 0 10px 10px;
    -o-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    -o-transition:all 0.3s ease-in-out;
    -webkit-border-bottom-left-radius:10px;
    -webkit-border-bottom-right-radius:10px;
    -webkit-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    -webkit-transition:all 0.3s ease-in-out;
    border-radius:0 0 10px 10px;
    box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    color:#eee;
    display:block;
    padding:0 10px;
    text-decoration:none;
    transition:all 0.3s ease-in-out;
}
ul.menu li a.red {
    background:#a00;
}
ul.menu li a.orange {
    background:#da0;
}
ul.menu li a.yellow {
    background:#aa0;
}
ul.menu li a.green {
    background:#060;
}
ul.menu li a.blue {
    background:#073263;
}
ul.menu li a.violet {
    background:#682bc2;
}
.menu li div.subs {
    left:0;
    overflow:hidden;
    position:absolute;
    top:35px;
    width:0;
}
.menu li div.subs dl {
    -moz-transition-duration:.2s;
    -o-transition-duration:.2s;
    -webkit-transition-duration:.2s;
    float:left;
    margin:0 130px 0 0;
    overflow:hidden;
    padding:40px 0 5% 2%;
    width:0;
}
.menu dt {
    color:#fc0;
    font-family:arial, sans-serif;
    font-size:12px;
    font-weight:700;
    height:20px;
    line-height:20px;
    margin:0;
    padding:0 0 0 10px;
    white-space:nowrap;
}
.menu dd {
    margin:0;
    padding:0;
    text-align:left;
}
.menu dd a {
    background:transparent;
    color:#fff;
    font-size:12px;
    height:20px;
    line-height:20px;
    padding:0 0 0 10px;
    text-align:left;
    white-space:nowrap;
    width:80px;
}
.menu dd a:hover {
    color:#fc0;
}
.menu li:hover div.subs dl {
    -moz-transition-delay:0.2s;
    -o-transition-delay:0.2s;
    -webkit-transition-delay:0.2s;
    margin-right:2%;
    width:21%;
}
ul.menu li:hover > a,ul.menu li > a:hover {
    background:#aaa;
    color:#fff;
    padding:10px 10px 0;
}
ul.menu li a.red:hover,ul.menu li:hover a.red {
    background:#c00;
}
ul.menu li a.orange:hover,ul.menu li:hover a.orange {
    background:#fc0;
}
ul.menu li a.yellow:hover,ul.menu li:hover a.yellow {
    background:#cc0;
}
ul.menu li a.green:hover,ul.menu li:hover a.green {
    background:#080;
}
ul.menu li a.blue:hover,ul.menu li:hover a.blue {
    background:#00c;
}
ul.menu li a.violet:hover,ul.menu li:hover a.violet {
background:#8a2be2;
}
.menu li:hover div.subs,.menu li a:hover div.subs {
    width:100%;
}

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

I haven't worked much with Appcelerator Titanium, but I'll put my understanding of it at the end.

I can speak a bit more to the differences between PhoneGap and Xamarin, as I work with these two 5 (or more) days a week.

If you are already familiar with C# and JavaScript, then the question I guess is, does the business logic lie in an area more suited to JavaScript or C#?

PhoneGap

PhoneGap is designed to allow you to write your applications using JavaScript and HTML, and much of the functionality that they do provide is designed to mimic the current proposed specifications for the functionality that will eventually be available with HTML5. The big benefit of PhoneGap in my opinion is that since you are doing the UI with HTML, it can easily be ported between platforms. The downside is, because you are porting the same UI between platforms, it won't feel quite as at home in any of them. Meaning that, without further tweaking, you can't have an application that feels fully at home in iOS and Android, meaning that it has the iOS and Android styling. The majority of your logic can be written using JavaScript, which means it too can be ported between platforms. If the current PhoneGap API does most of what you want, then it's pretty easy to get up and running. If however, there are things you need from the device that are not in the API, then you get into the fun of Plugin Development, which will be in the native device's development language of choice (with one caveat, but I'll get to that), which means you would likely need to get up to speed quickly in Objective-C, Java, etc. The good thing about this model, is you can usually adapt many different native libraries to serve your purpose, and many libraries already have PhoneGap Plugins. Although you might not have much experience with these languages, there will at least be a plethora of examples to work from.

Xamarin

Xamarin.iOS and Xamarin.Android (also known as MonoTouch and MonoDroid), are designed to allow you to have one library of business logic, and use this within your application, and hook it into your UI. Because it's based on .NET 4.5, you get some awesome lambda notations, LINQ, and a whole bunch of other C# awesomeness, which can make writing your business logic less painful. The downside here is that Xamarin expects that you want to make your applications truly feel native on the device, which means that you will likely end up rewriting your UI for each platform, before hooking it together with the business logic. I have heard about MvvmCross, which is designed to make this easier for you, but I haven't really had an opportunity to look into it yet. If you are familiar with the MVVM system in C#, you may want to have a look at this. When it comes to native libraries, MonoTouch becomes interesting. MonoTouch requires a Binding library to tell your C# code how to link into the underlying Objective-C and Java code. Some of these libraries will already have bindings, but if yours doesn't, creating one can be, interesting. Xamarin has made a tool called Objective Sharpie to help with this process, and for the most part, it will get you 95% of the way there. The remaining 5% will probably take 80% of your time attempting to bind a library.

Update

As noted in the comments below, Xamarin has released Xamarin Forms which is a cross platform abstraction around the platform specific UI components. Definitely worth the look.

PhoneGap / Xamarin Hybrid

Now because I said I would get to it, the caveat mentioned in PhoneGap above, is a Hybrid approach, where you can use PhoneGap for part, and Xamarin for part. I have quite a bit of experience with this, and I would caution you against it. Highly. The problem with this, is it is such a no mans' land that if you ever run into issues, almost no one will have come close to what you're doing, and will question what you're trying to do greatly. It is doable, but it's definitely not fun.

Appcelerator Titanium

As I mentioned before, I haven't worked much with Appcelerator Titanium, So for the differences between them, I will suggest you look at Comparing Titanium and Phonegap or Comparison between Corona, Phonegap, Titanium as it has a very thorough description of the differences. Basically, it appears that though they both use JavaScript, how that JavaScript is interpreted is slightly different. With Titanium, you will be writing your JavaScript to the Titanium SDK, whereas with PhoneGap, you will write your application using the PhoneGap API. As PhoneGap is very HTML5 and JavaScript standards compliant, you can use pretty much any JavaScript libraries you want, such as JQuery. With PhoneGap your user interface will be composed of HTML and CSS. With Titanium, you will benefit from their Cross-platform XML which appears to generate Native components. This means it will definitely have a better native look and feel.

How to check whether a Storage item is set?

localStorage['root2']=null;

localStorage.getItem("root2") === null //false

Maybe better to do a scan of the plan ?

localStorage['root1']=187;
187
'root1' in localStorage
true

Converting bool to text in C++

I use a ternary in a printf like this:

printf("%s\n", b?"true":"false");

If you macro it :

B2S(b) ((b)?"true":"false")

then you need to make sure whatever you pass in as 'b' doesn't have any side effects. And don't forget the brackets around the 'b' as you could get compile errors.

Remove item from list based on condition

Here is a solution for those, who want to remove it from the database with Entity Framework:

prods.RemoveWhere(s => s.ID == 1);

And the extension method itself:

using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;

namespace LivaNova.NGPDM.Client.Services.Data.Extensions
{
    public static class DbSetExtensions
    {
        public static void RemoveWhere<TEntity>(this DbSet<TEntity> entities, Expression<Func<TEntity, bool>> predicate) where TEntity : class
        {
            var records = entities
                .Where(predicate)
                .ToList();
            if (records.Count > 0)
                entities.RemoveRange(records);
        }
    }
}

P.S. This simulates the method RemoveAll() that's not available for DB sets of the entity framework.

How to update maven repository in Eclipse?

You can right-click on your project then Maven > Update Project..., then select Force Update of Snapshots/Releases checkbox then click OK.

Minimal web server using netcat

mkfifo pipe;
while true ; 
do 
   #use read line from pipe to make it blocks before request comes in,
   #this is the key.
   { read line<pipe;echo -e "HTTP/1.1 200 OK\r\n";echo $(date);
   }  | nc -l -q 0 -p 8080 > pipe;  

done

Setting the height of a DIV dynamically

What should happen in the case of overflow? If you want it to just get to the bottom of the window, use absolute positioning:

div {
  position: absolute;
  top: 300px;
  bottom: 0px;
  left: 30px;
  right: 30px;
}

This will put the DIV 30px in from each side, 300px from the top of the screen, and flush with the bottom. Add an overflow:auto; to handle cases where the content is larger than the div.


Edit: @Whoever marked this down, an explanation would be nice... Is something wrong with the answer?

Opening A Specific File With A Batch File?

@echo off
start %1

or if needed to escape the characters -

@echo off
start %%1

How to set ID using javascript?

Do you mean like this?

var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);

To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll() to accomplish this:

HTML

<div class="abc"></div>
<div class="abc"></div>

JS

var abcElements = document.querySelectorAll('.abc');

// Set their ids
for (var i = 0; i < abcElements.length; i++)
    abcElements[i].id = 'abc-' + i;

This will assign the ID 'abc-<index number>' to each element. So it would come out like this:

<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>

To create an element and assign an id we can use document.createElement() and then appendChild().

var div = document.createElement('div');
div.id = 'hello1';

var body = document.querySelector('body');
body.appendChild(div);

Update

You can set the id on your element like this if your script is in your HTML file.

<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">

<script type="text/javascript">
    var s = document.getElementsByClassName('assign-me')[0];
    s.id = btoa({{str(produit["avt"]["fto"])}});
</script>

Your requirements still aren't 100% clear though.

How to make an unaware datetime timezone aware in python

I use this statement in Django to convert an unaware time to an aware:

from django.utils import timezone

dt_aware = timezone.make_aware(dt_unaware, timezone.get_current_timezone())

Infinite Recursion with Jackson JSON and Hibernate JPA issue

You Should use @JsonBackReference with @ManyToOne entity and @JsonManagedReference with @onetomany containing entity classes.

@OneToMany(
            mappedBy = "queue_group",fetch = FetchType.LAZY,
            cascade = CascadeType.ALL
        )
    @JsonManagedReference
    private Set<Queue> queues;



@ManyToOne(cascade=CascadeType.ALL)
        @JoinColumn(name = "qid")
       // @JsonIgnore
        @JsonBackReference
        private Queue_group queue_group;

How to convert a string with Unicode encoding to a string of letters

Solution for Kotlin:

val sourceContent = File("test.txt").readText(Charset.forName("windows-1251"))
val result = String(sourceContent.toByteArray())

Kotlin uses UTF-8 everywhere as default encoding.

Method toByteArray() has default argument - Charsets.UTF_8.

How can I know if a process is running?

It depends on how reliable you want this function to be. If you want to know if the particular process instance you have is still running and available with 100% accuracy then you are out of luck. The reason being that from the managed process object there are only 2 ways to identify the process.

The first is the Process Id. Unfortunately, process ids are not unique and can be recycled. Searching the process list for a matching Id will only tell you that there is a process with the same id running, but it's not necessarily your process.

The second item is the Process Handle. It has the same problem though as the Id and it's more awkward to work with.

If you're looking for medium level reliability then checking the current process list for a process of the same ID is sufficient.

Why doesn't os.path.join() work in this case?

The latter strings shouldn't start with a slash. If they start with a slash, then they're considered an "absolute path" and everything before them is discarded.

Quoting the Python docs for os.path.join:

If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.

Note on Windows, the behaviour in relation to drive letters, which seems to have changed compared to earlier Python versions:

On Windows, the drive letter is not reset when an absolute path component (e.g., r'\foo') is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

Why is Tkinter Entry's get function returning nothing?

you need to put a textvariable in it, so you can use set() and get() method :

var=StringVar()
x= Entry (root,textvariable=var)

ImportError: No module named pythoncom

$ pip3 install pypiwin32

Sometimes using pip3 also works if just pip by itself is not working.

How to add a 'or' condition in #ifdef

May use this-

#if defined CONDITION1 || defined CONDITION2
//your code here
#endif

This also does the same-

#if defined(CONDITION1) || defined(CONDITION2)
//your code here
#endif

Further-

  • AND: #if defined CONDITION1 && defined CONDITION2
  • XOR: #if defined CONDITION1 ^ defined CONDITION2
  • AND NOT: #if defined CONDITION1 && !defined CONDITION2

Change user-agent for Selenium web-driver

To build on JJC's helpful answer that builds on Louis's helpful answer...

With PhantomJS 2.1.1-windows this line works:

driver.execute_script("return navigator.userAgent")

If it doesn't work, you can still get the user agent via the log (to build on Mma's answer):

from selenium import webdriver
import json
from fake_useragent import UserAgent

dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (UserAgent().random)
driver = webdriver.PhantomJS(executable_path=r"your_path", desired_capabilities=dcap)
har = json.loads(driver.get_log('har')[0]['message']) # get the log
print('user agent: ', har['log']['entries'][0]['request']['headers'][1]['value'])

Python: import module from another directory at the same level in project hierarchy

From Python 2.5 onwards, you can use

from ..Modules import LDAPManager

The leading period takes you "up" a level in your heirarchy.

See the Python docs on intra-package references for imports.

Android splash screen image sizes to fit all devices

Some time ago i created an excel file with supported dimensions
Hope this will be helpful for somebody

To be honest i lost the idea, but it refers another screen feature as size (not only density)
https://developer.android.com/guide/practices/screens_support.html
Please inform me if there are some mistakes

Link1: dimensions.xlsx

Link2: dimensions.xlsx

AngularJS access parent scope from child controller

Some times you may need to update parent properties directly within child scope. e.g. need to save a date and time of parent control after changes by a child controller. e.g Code in JSFiddle

HTML

<div ng-app>
<div ng-controller="Parent">
    event.date = {{event.date}} <br/>
    event.time = {{event.time}} <br/>
    <div ng-controller="Child">
        event.date = {{event.date}}<br/>
        event.time = {{event.time}}<br/>
        <br>
        event.date: <input ng-model='event.date'><br>
        event.time: <input ng-model='event.time'><br>
    </div>
</div>

JS

    function Parent($scope) {
       $scope.event = {
        date: '2014/01/1',
        time: '10:01 AM'
       }
    }

    function Child($scope) {

    }

Java Error opening registry key

Uninstall Java (via Control Panel / Programs and Features)

Install Java JRE 7 --> OFFLINE <-- Configure JAVA_HOME and Path = %JAVA_HOME%/bin;%PATH%

Set View Width Programmatically

hsThumbList.setLayoutParams(new LayoutParams(100, 400));

Find the differences between 2 Excel worksheets?

excel overlay will put both spreadsheets on top of each other (overlay them) and highlight the differences.

http://download.cnet.com/Excel-Overlay/3000-2077_4-10963782.html?tag=mncol

Reading in double values with scanf in c

Format specifier in printf should be %f for doubl datatypes since float datatyles eventually convert to double datatypes inside printf.

There is no provision to print float data. Please find the discussion here : Correct format specifier for double in printf

jQuery Change event on an <input> element - any way to retain previous value?

I found a dirty trick but it works, you could use the hover function to get the value before change!

Get the element with the highest occurrence in an array

There have been some developments in javascript since 2009 - I thought I'd add another option. I'm less concerned with efficiency until it's actually a problem so my definition of "elegant" code (as stipulated by the OP) favours readability - which is of course subjective...

function mode(arr){
    return arr.sort((a,b) =>
          arr.filter(v => v===a).length
        - arr.filter(v => v===b).length
    ).pop();
}

mode(['pear', 'apple', 'orange', 'apple']); // apple

In this particular example, should two or more elements of the set have equal occurrences then the one that appears latest in the array will be returned. It's also worth pointing out that it will modify your original array - which can be prevented if you wish with an Array.slice call beforehand.


Edit: updated the example with some ES6 fat arrows because 2015 happened and I think they look pretty... If you are concerned with backwards compatibility you can find this in the revision history.

Combine multiple JavaScript files into one JS file

Copy this script to notepad and save as .vbs file. Drag&Drop .js files on this script.

ps. This will work only on windows.

set objArgs = Wscript.Arguments
set objFso = CreateObject("Scripting.FileSystemObject")
content = ""

'Iterate through all the arguments passed
for i = 0 to objArgs.count  
    on error resume next
    'Try and treat the argument like a folder
    Set folder = objFso.GetFolder(objArgs(i))
    'If we get an error, we know it is a file
    if err.number <> 0 then
        'This is not a folder, treat as file
        content = content & ReadFile(objArgs(i))
    else
        'No error? This is a folder, process accordingly
        for each file in folder.Files
            content = content & ReadFile(file.path)
        next
    end if
    on error goto 0
next

'Get system Temp folder path
set tempFolderPath = objFso.GetSpecialFolder(2)
'Generate a random filename to use for a temporary file
strTempFileName = objFso.GetTempName
'Create temporary file in Temp folder
set objTempFile = tempFolderPath.CreateTextFile(strTempFileName)
'Write content from JavaScript files to temporary file
objTempFile.WriteLine(content)
objTempFile.Close

'Open temporary file in Notepad
set objShell = CreateObject("WScript.Shell")
objShell.Run("Notepad.exe " & tempFolderPath & "\" & strTempFileName)


function ReadFile(strFilePath)
    'If file path ends with ".js", we know it is JavaScript file
    if Right(strFilePath, 3) = ".js" then       
        set objFile = objFso.OpenTextFile(strFilePath, 1, false)
        'Read entire contents of a JavaScript file and returns it as a string
        ReadFile = objFile.ReadAll & vbNewLine
        objFile.Close
    else
        'Return empty string
        ReadFile = ""
    end if  
end function

Divide a number by 3 without using *, /, +, -, % operators

Here's my solution:

public static int div_by_3(long a) {
    a <<= 30;
    for(int i = 2; i <= 32 ; i <<= 1) {
        a = add(a, a >> i);
    }
    return (int) (a >> 32);
}

public static long add(long a, long b) {
    long carry = (a & b) << 1;
    long sum = (a ^ b);
    return carry == 0 ? sum : add(carry, sum);
}

First, note that

1/3 = 1/4 + 1/16 + 1/64 + ...

Now, the rest is simple!

a/3 = a * 1/3  
a/3 = a * (1/4 + 1/16 + 1/64 + ...)
a/3 = a/4 + a/16 + 1/64 + ...
a/3 = a >> 2 + a >> 4 + a >> 6 + ...

Now all we have to do is add together these bit shifted values of a! Oops! We can't add though, so instead, we'll have to write an add function using bit-wise operators! If you're familiar with bit-wise operators, my solution should look fairly simple... but just in-case you aren't, I'll walk through an example at the end.

Another thing to note is that first I shift left by 30! This is to make sure that the fractions don't get rounded off.

11 + 6

1011 + 0110  
sum = 1011 ^ 0110 = 1101  
carry = (1011 & 0110) << 1 = 0010 << 1 = 0100  
Now you recurse!

1101 + 0100  
sum = 1101 ^ 0100 = 1001  
carry = (1101 & 0100) << 1 = 0100 << 1 = 1000  
Again!

1001 + 1000  
sum = 1001 ^ 1000 = 0001  
carry = (1001 & 1000) << 1 = 1000 << 1 = 10000  
One last time!

0001 + 10000
sum = 0001 ^ 10000 = 10001 = 17  
carry = (0001 & 10000) << 1 = 0

Done!

It's simply carry addition that you learned as a child!

111
 1011
+0110
-----
10001

This implementation failed because we can not add all terms of the equation:

a / 3 = a/4 + a/4^2 + a/4^3 + ... + a/4^i + ... = f(a, i) + a * 1/3 * 1/4^i
f(a, i) = a/4 + a/4^2 + ... + a/4^i

Suppose the reslut of div_by_3(a) = x, then x <= floor(f(a, i)) < a / 3. When a = 3k, we get wrong answer.

How to add property to a class dynamically?

Something that works for me is this:

class C:
    def __init__(self):
        self._x=None

    def g(self):
        return self._x

    def s(self, x):
        self._x = x

    def d(self):
        del self._x

    def s2(self,x):
        self._x=x+x

    x=property(g,s,d)


c = C()
c.x="a"
print(c.x)

C.x=property(C.g, C.s2)
C.x=C.x.deleter(C.d)
c2 = C()
c2.x="a"
print(c2.x)

Output

a
aa

How to set HTML Auto Indent format on Sublime Text 3?

Create a Keybinding

To auto indent on Sublime text 3 with a key bind try going to

Preferences > Key Bindings - users

And adding this code between the square brackets

{"keys": ["alt+shift+f"], "command": "reindent", "args": {"single_line": false}}

it sets shift + alt + f to be your full page auto indent.

Source here

Note: if this doesn't work correctly then you should convert your indentation to tabs. Also comments in your code can push your code to the wrong indentation level and may have to be moved manually.

Determine distance from the top of a div to top of window with javascript

This can be achieved purely with JavaScript.

I see the answer I wanted to write has been answered by lynx in comments to the question.

But I'm going to write answer anyway because just like me, people sometimes forget to read the comments.

So, if you just want to get an element's distance (in Pixels) from the top of your screen window, here is what you need to do:

// Fetch the element
var el = document.getElementById("someElement");  

use getBoundingClientRect()

// Use the 'top' property of 'getBoundingClientRect()' to get the distance from top
var distanceFromTop = el.getBoundingClientRect().top; 

Thats it!

Hope this helps someone :)

How do I find out my root MySQL password?

There is a simple solution.

MySql 5.7 comes with anonymous user so you need to reconfigure MySQL server.

You can do that with this command

try to find temp pass:

grep 'temporary password' /var/log/mysqld.log

then:

sudo mysql_secure_installation

On this link is more info about mysql 5.7

https://dev.mysql.com/doc/refman/5.7/en/linux-installation-yum-repo.html

how to clear the screen in python

If you mean the screen where you have that interpreter prompt >>> you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do

import os
os.system('cls')  # on windows

or

os.system('clear')  # on linux / os x

How to echo shell commands as they are executed

shuckc's answer for echoing select lines has a few downsides: you end up with the following set +x command being echoed as well, and you lose the ability to test the exit code with $? since it gets overwritten by the set +x.

Another option is to run the command in a subshell:

echo "getting URL..."
( set -x ; curl -s --fail $URL -o $OUTFILE )

if [ $? -eq 0 ] ; then
    echo "curl failed"
    exit 1
fi

which will give you output like:

getting URL...
+ curl -s --fail http://example.com/missing -o /tmp/example
curl failed

This does incur the overhead of creating a new subshell for the command, though.

What is DOM element?

DOM is a logical model that can be implemented in any convenient manner.It is based on an object structure that closely resembles the structure of the documents it models.

For More Information on DOM : Click Here

jQuery Event : Detect changes to the html/text of a div

You are looking for MutationObserver or Mutation Events. Neither are supported everywhere nor are looked upon too fondly by the developer world.

If you know (and can make sure that) the div's size will change, you may be able to use the crossbrowser resize event.

How to handle floats and decimal separators with html5 input type number

uses a text type but forces the appearance of the numeric keyboard

<input value="12,4" type="text" inputmode="numeric" pattern="[-+]?[0-9]*[.,]?[0-9]+">

the inputmode tag is the solution

How do I get NuGet to install/update all the packages in the packages.config?

After 3 hours of searching and investigation.

I had problems with it because we have two members in team (using GitHub source control), because we didn't restrict files for packages for sending to remote repository, one of team members was send packages to server and i have pull that changes to my local.

After that i had same problem as PO, also i wasn't be able to publish my API project to server.

At the and I have just used

Update-Package -Reinstall - run this command on Package Manager Console

This command will reinstall all your packages that you have used in your solution. (For every project)

Reinstall all packages in ALL PROJECTS of the current solution:

Update-Package -ProjectName 'NameOfProject' -Reinstall - run this command on Package Manager Console

This command will reinstall all your packages that are in relation with project that you specified after "-ProjectName". And i think that this is better because i had wait for half a hour to reinstall all packages in solution.

For this many thanks to Rodolpho Brock.

Also, I would recommend you that when you pull changes from remote server, to press "Restore packages" button that will be shown by Visual studio.

var functionName = function() {} vs function functionName() {}

A function declaration and a function expression assigned to a variable behave the same once the binding is established.

There is a difference however at how and when the function object is actually associated with its variable. This difference is due to the mechanism called variable hoisting in JavaScript.

Basically, all function declarations and variable declarations are hoisted to the top of the function in which the declaration occurs (this is why we say that JavaScript has function scope).

  • When a function declaration is hoisted, the function body "follows" so when the function body is evaluated, the variable will immediately be bound to a function object.

  • When a variable declaration is hoisted, the initialization does not follow, but is "left behind". The variable is initialized to undefined at the start of the function body, and will be assigned a value at its original location in the code. (Actually, it will be assigned a value at every location where a declaration of a variable with the same name occurs.)

The order of hoisting is also important: function declarations take precedence over variable declarations with the same name, and the last function declaration takes precedence over previous function declarations with the same name.

Some examples...

var foo = 1;
function bar() {
  if (!foo) {
    var foo = 10 }
  return foo; }
bar() // 10

Variable foo is hoisted to the top of the function, initialized to undefined, so that !foo is true, so foo is assigned 10. The foo outside of bar's scope plays no role and is untouched.

function f() {
  return a; 
  function a() {return 1}; 
  var a = 4;
  function a() {return 2}}
f()() // 2

function f() {
  return a;
  var a = 4;
  function a() {return 1};
  function a() {return 2}}
f()() // 2

Function declarations take precedence over variable declarations, and the last function declaration "sticks".

function f() {
  var a = 4;
  function a() {return 1}; 
  function a() {return 2}; 
  return a; }
f() // 4

In this example a is initialized with the function object resulting from evaluating the second function declaration, and then is assigned 4.

var a = 1;
function b() {
  a = 10;
  return;
  function a() {}}
b();
a // 1

Here the function declaration is hoisted first, declaring and initializing variable a. Next, this variable is assigned 10. In other words: the assignment does not assign to outer variable a.

Get nodes where child node contains an attribute

Try

//book[title/@lang = 'it']

This reads:

  • get all book elements
    • that have at least one title
      • which has an attribute lang
        • with a value of "it"

You may find this helpful — it's an article entitled "XPath in Five Paragraphs" by Ronald Bourret.

But in all honesty, //book[title[@lang='it']] and the above should be equivalent, unless your XPath engine has "issues." So it could be something in the code or sample XML that you're not showing us -- for example, your sample is an XML fragment. Could it be that the root element has a namespace, and you aren't counting for that in your query? And you only told us that it didn't work, but you didn't tell us what results you did get.

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How can you get the first digit in an int (C#)?

int start = curr;
while (start >= 10)
  start /= 10;

This is more efficient than a ToString() approach which internally must implement a similar loop and has to construct (and parse) a string object on the way ...

Remove last item from array

Simply arr.splice(-1) will do.

JavaScript and Threads

Another possible method is using an javascript interpreter in the javascript environment.

By creating multiple interpreters and controlling their execution from the main thread, you can simulate multi-threading with each thread running in its own environment.

The approach is somewhat similar to web workers, but you give the interpreter access to the browser global environment.

I made a small project to demonstrate this.

A more detailed explanation in this blog post.

Empty or Null value display in SSRS text boxes

I couldn't get IsNothing() to behave and I didn't want to create dummy rows in my dataset (e.g. for a given list of customers create a dummy order per month displayed) and noticed that null values were displaying as -247192.

Lo and behold using that worked to suppress it (at least until MSFT changes SSRS for the better from 08R2) so forgive me but:

=iif(Fields!Sales_Diff.Value = -247192,"",Fields!Sales_Diff.Value)

How to concatenate items in a list to a single string?

This will help for sure -

arr=['a','b','h','i']     # let this be the list
s=""                      # creating a empty string
for i in arr:
   s+=i                   # to form string without using any function
print(s) 


       

$date + 1 year?

In my case (i want to add 3 years to current date) the solution was:

$future_date = date('Y-m-d', strtotime("now + 3 years"));

To Gardenee, Treby and Daniel Lima: what will happen with 29th February? Sometimes February has only 28 days :)

Close Android Application

You could finish your Activity by calling Activity.finish(). However take care of the Android Activity life-cycle.

How to dynamically change header based on AngularJS partial view?

The module angularjs-viewhead shows a mechanism to set the title on a per-view basis using only a custom directive.

It can either be applied to an existing view element whose content is already the view title:

<h2 view-title>About This Site</h2>

...or it can be used as a standalone element, in which case the element will be invisible in the rendered document and will only be used to set the view title:

<view-title>About This Site</view-title>

The content of this directive is made available in the root scope as viewTitle, so it can be used on the title element just like any other variable:

<title ng-bind-template="{{viewTitle}} - My Site">My Site</title>

It can also be used in any other spot that can "see" the root scope. For example:

<h1>{{viewTitle}}</h1>

This solution allows the title to be set via the same mechanism that is used to control the rest of the presentation: AngularJS templates. This avoids the need to clutter controllers with this presentational logic. The controller needs to make available any data that will be used to inform the title, but the template makes the final determination on how to present it, and can use expression interpolation and filters to bind to scope data as normal.

(Disclaimer: I am the author of this module, but I'm referencing it here only in the hope that it will help someone else to solve this problem.)

Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

You can only use - on the numeric entries, so you can use decreasing and negate the ones you want in increasing order:

DT[order(x,-v,decreasing=TRUE),]
      x y v
 [1,] c 1 7
 [2,] c 3 8
 [3,] c 6 9
 [4,] b 1 1
 [5,] b 3 2
 [6,] b 6 3
 [7,] a 1 4
 [8,] a 3 5
 [9,] a 6 6

Creating multiline strings in JavaScript

ES6 allows you to use a backtick to specify a string on multiple lines. It's called a Template Literal. Like this:

var multilineString = `One line of text
    second line of text
    third line of text
    fourth line of text`;

Using the backtick works in NodeJS, and it's supported by Chrome, Firefox, Edge, Safari, and Opera.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

python xlrd unsupported format, or corrupt file.

Worked on the same issue , finally done this is top for the question so just putting what i did.

Observation - 1 -The file was not actually XLS i renamed to txt and noticed HTML text in file.

2 - Renamed the file to html and tried reading pd.read_html, Failed.

3- Added as it was not there in txt file, removed style to ensure that table is displaying in browser from local, and WORKED.

Below is the code may help someone..

import pandas as pd
import os
import shutil
import html5lib
import requests
from bs4 import BeautifulSoup
import re
import time

shutil.copy('your.xls','file.html')
shutil.copy('file.html','file.txt')
time.sleep(2)

txt = open('file.txt','r').read()

# Modify the text to ensure the data display in html page, delete style

txt = str(txt).replace('<style> .text { mso-number-format:\@; } </script>','')

# Add head and body if it is not there in HTML text

txt_with_head = '<html><head></head><body>'+txt+'</body></html>'

# Save the file as HTML

html_file = open('output.html','w')
html_file.write(txt_with_head)

# Use beautiful soup to read

url = r"C:\Users\hitesh kumar\PycharmProjects\OEM ML\output.html"
page = open(url)
soup = BeautifulSoup(page.read(), features="lxml")
my_table = soup.find("table",attrs={'border': '1'})

frame = pd.read_html(str(my_table))[0]
print(frame.head())
frame.to_excel('testoutput.xlsx',sheet_name='sheet1', index=False)

How to change owner of PostgreSql database?

Frank Heikens answer will only update database ownership. Often, you also want to update ownership of contained objects (including tables). Starting with Postgres 8.2, REASSIGN OWNED is available to simplify this task.

IMPORTANT EDIT!

Never use REASSIGN OWNED when the original role is postgres, this could damage your entire DB instance. The command will update all objects with a new owner, including system resources (postgres0, postgres1, etc.)


First, connect to admin database and update DB ownership:

psql
postgres=# REASSIGN OWNED BY old_name TO new_name;

This is a global equivalent of ALTER DATABASE command provided in Frank's answer, but instead of updating a particular DB, it change ownership of all DBs owned by 'old_name'.

The next step is to update tables ownership for each database:

psql old_name_db
old_name_db=# REASSIGN OWNED BY old_name TO new_name;

This must be performed on each DB owned by 'old_name'. The command will update ownership of all tables in the DB.

No resource identifier found for attribute '...' in package 'com.app....'

I solved is by using android:background instead of app:srcCompact.

This is caused by xmlns:app="http://schemas.android.com/apk/res-auto". As people have suggested above, you could use /lib-auto or /lib/your-package but I got suspicious namespace error when I tried using /lib-auto and unexpected namespace prefix error with /lib/my-package .

Classes vs. Modules in VB.NET

When one of my VB.NET classes has all shared members I either convert it to a Module with a matching (or otherwise appropriate) namespace or I make the class not inheritable and not constructable:

Public NotInheritable Class MyClass1

   Private Sub New()
      'Contains only shared members.
      'Private constructor means the class cannot be instantiated.
   End Sub

End Class

What killed my process and why?

Try:

dmesg -T| grep -E -i -B100 'killed process'

Where -B100 signifies the number of lines before the kill happened.

Omit -T on Mac OS.

Can't choose class as main class in IntelliJ

The documentation you linked actually has the answer in the link associated with the "Java class located out of the source root." Configure your source and test roots and it should work.

https://www.jetbrains.com/idea/webhelp/configuring-content-roots.html

Since you stated that these are tests you should probably go with them marked as Test Source Root instead of Source Root.

Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

I use Windows Server 2012 for hosting for a long time and it just stop working after a more than years without any problem. My solution was to add public IP address of the server to list of relays and enabled Windows Integrated Authentication.

I just made two changes and I don't which help.

Go to IIS 6 Manager

Go to IIS 6 Manager

Select properties of SMTP server

Select properties of SMTP server

On tab Access, select Relays

On tab Access, select Relays

Add your public IP address

Add your public IP address

Close the dialog and on the same tab click to Authentication button.

Add Integrated Windows Authentication

Add Integrated Windows Authentication

Maybe some step is not needed, but it works.

How do I execute multiple SQL Statements in Access' Query Editor?

create a macro like this

Option Compare Database

Sub a()

DoCmd.RunSQL "DELETE * from TABLENAME where CONDITIONS"

DoCmd.RunSQL "DELETE * from TABLENAME where CONDITIONS"

End Sub

Static class initializer in PHP

Actually, I use a public static method __init__() on my static classes that require initialization (or at least need to execute some code). Then, in my autoloader, when it loads a class it checks is_callable($class, '__init__'). If it is, it calls that method. Quick, simple and effective...

Number of lines in a file in Java

I tested the above methods for counting lines and here are my observations for Different methods as tested on my system

File Size : 1.6 Gb Methods:

  1. Using Scanner : 35s approx
  2. Using BufferedReader : 5s approx
  3. Using Java 8 : 5s approx
  4. Using LineNumberReader : 5s approx

Moreover Java8 Approach seems quite handy :

Files.lines(Paths.get(filePath), Charset.defaultCharset()).count()
[Return type : long]

Root password inside a Docker container

Eventually, I decided to rebuild my Docker images, so that I change the root password by something I will know.

RUN echo 'root:Docker!' | chpasswd

or

RUN echo 'Docker!' | passwd --stdin root 

How to align this span to the right of the div?

If you can modify the HTML: http://jsfiddle.net/8JwhZ/3/

<div class="title">
  <span class="name">Cumulative performance</span>
  <span class="date">20/02/2011</span>
</div>

.title .date { float:right }
.title .name { float:left }

Stretch image to fit full container width bootstrap

Here's what worked for me. Note: Adding the image within a row introduces some space so I've intentionally used only a div to encapsulate the image.

<div class="container-fluid w-100 h-auto m-0 p-0">  

    <img src="someimg.jpg" class="img-fluid w-100 h-auto p-0 m-0" alt="Patience">           

</div>

INSERT and UPDATE a record using cursors in oracle

This is a highly inefficient way of doing it. You can use the merge statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.

MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
  UPDATE SET l.studName = s.studName
   WHERE l.studName != s.studName
WHEN NOT MATCHED THEN 
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)

Make sure you commit, once completed, in order to be able to see this in the database.


To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.

It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.

However, as I say this will not be as efficient as merge.

declare

   cursor c_data is
    select b.rowid as rid, a.studId, a.studName
      from student a
      left outer join studLoad b
        on a.studId = b.studId
       and a.studName <> b.studName
           ;

   type t__data is table of c_data%rowtype index by binary_integer;
   t_data t__data;

begin

   open c_data;
   loop
      fetch c_data bulk collect into t_data limit 10000;

      exit when t_data.count = 0;

      for idx in t_data.first .. t_data.last loop
         if t_data(idx).rid is null then
            insert into studLoad (studId, studName)
            values (t_data(idx).studId, t_data(idx).studName);
         else
            update studLoad
               set studName = t_data(idx).studName
             where rowid = t_data(idx).rid
                   ;
         end if;
      end loop;

   end loop;
   close c_data;

end;
/

Htaccess: add/remove trailing slash from URL

To complement Jon Lin's answer, here is a no-trailing-slash technique that also works if the website is located in a directory (like example.org/blog/):

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]


For the sake of completeness, here is an alternative emphasizing that REQUEST_URI starts with a slash (at least in .htaccess files):

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /(.*)/$
RewriteRule ^ /%1 [R=301,L] <-- added slash here too, don't forget it

Just don't use %{REQUEST_URI} (.*)/$. Because in the root directory REQUEST_URI equals /, the leading slash, and it would be misinterpreted as a trailing slash.


If you are interested in more reading:

(update: this technique is now implemented in Laravel 5.5)

List all of the possible goals in Maven 2?

The goal you indicate in the command line is linked to the lifecycle of Maven. For example, the build lifecycle (you also have the clean and site lifecycles which are different) is composed of the following phases:

  • validate: validate the project is correct and all necessary information is available.
  • compile: compile the source code of the project.
  • test: test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed.
  • package: take the compiled code and package it in its distributable format, such as a JAR.
  • integration-test: process and deploy the package if necessary into an environment where integration tests can be run.
  • verify: run any checks to verify the package is valid and meets quality criteria
  • install: install the package into the local repository, for use as a dependency in other projects locally.
  • deploy: done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

You can find the list of "core" plugins here, but there are plenty of others plugins, such as the codehaus ones, here.

how to get the selected index of a drop down

You can also use :checked for <select> elements

e.g.,

document.querySelector('select option:checked')
document.querySelector('select option:checked').getAttribute('value')

You don't even have to get the index and then reference the element by its sibling index.

What does --net=host option in Docker command really do?

  1. you can create your own new network like --net="anyname"
  2. this is done to isolate the services from different container.
  3. suppose the same service are running in different containers, but the port mapping remains same, the first container starts well , but the same service from second container will fail. so to avoid this, either change the port mappings or create a network.

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

Generating a WSDL from an XSD file

Personally (and given what I know, i.e., Java and axis), I'd generate a Java data model from the .xsd files (Axis 2 can do this), and then add an interface to describe my web service that uses that model, and then generate a WSDL from that interface.

Because .NET has all these features as well, it must be possible to do all this in that ecosystem as well.

Laravel Eloquent - Get one Row

You can do this too

Before you use this you must declare the DB facade in the controller Simply put this line for that

use Illuminate\Support\Facades\DB;

Now you can get a row using this

$getUserByEmail = DB::table('users')->where('email', $email)->first();

or by this too

$getUserByEmail = DB::select('SELECT * FROM users WHERE email = ?' , ['[email protected]']);

This one returns an array with only one item in it and while the first one returns an object. Keep that in mind.

Hope this helps.

Passing capturing lambda as function pointer

Shafik Yaghmour's answer correctly explains why the lambda cannot be passed as a function pointer if it has a capture. I'd like to show two simple fixes for the problem.

  1. Use std::function instead of raw function pointers.

    This is a very clean solution. Note however that it includes some additional overhead for the type erasure (probably a virtual function call).

    #include <functional>
    #include <utility>
    
    struct Decide
    {
      using DecisionFn = std::function<bool()>;
      Decide(DecisionFn dec) : dec_ {std::move(dec)} {}
      DecisionFn dec_;
    };
    
    int
    main()
    {
      int x = 5;
      Decide greaterThanThree { [x](){ return x > 3; } };
    }
    
  2. Use a lambda expression that doesn't capture anything.

    Since your predicate is really just a boolean constant, the following would quickly work around the current issue. See this answer for a good explanation why and how this is working.

    // Your 'Decide' class as in your post.
    
    int
    main()
    {
      int x = 5;
      Decide greaterThanThree {
        (x > 3) ? [](){ return true; } : [](){ return false; }
      };
    }
    

git push to specific branch

The answers in question you linked-to are all about configuring git so that you can enter very short git push commands and have them do whatever you want. Which is great, if you know what you want and how to spell that in Git-Ese, but you're new to git! :-)

In your case, Petr Mensik's answer is the (well, "a") right one. Here's why:

The command git push remote roots around in your .git/config file to find the named "remote" (e.g., origin). The config file lists:

  • where (URL-wise) that remote "lives" (e.g., ssh://hostname/path)
  • where pushes go, if different
  • what gets pushed, if you didn't say what branch(es) to push
  • what gets fetched when you run git fetch remote

When you first cloned the repo—whenever that was—git set up default values for some of these. The URL is whatever you cloned from and the rest, if set or unset, are all "reasonable" defaults ... or, hmm, are they?

The issue with these is that people have changed their minds, over time, as to what is "reasonable". So now (depending on your version of git and whether you've configured things in detail), git may print a lot of warnings about defaults changing in the future. Adding the name of the "branch to push"—amd_qlp_tester—(1) shuts it up, and (2) pushes just that one branch.

If you want to push more conveniently, you could do that with:

git push origin

or even:

git push

but whether that does what you want, depends on whether you agree with "early git authors" that the original defaults are reasonable, or "later git authors" that the original defaults aren't reasonable. So, when you want to do all the configuration stuff (eventually), see the question (and answers) you linked-to.

As for the name origin/amd_qlp_tester in the first place: that's actually a local entity (a name kept inside your repo), even though it's called a "remote branch". It's git's best guess at "where amd_qlp_tester is over there". Git updates it when it can.

Node - how to run app.js?

The code downloaded may require you to install dependencies first. Try commands(in app.js directory): npm install then node app.js. This should install dependencies and then start the app.

How do I use cx_freeze?

I ran into a similar issue. I solved it by setting the Executable options in a variable and then simply calling the variable. Below is a sample setup.py that I use:

from cx_Freeze import setup, Executable
import sys

productName = "ProductName"
if 'bdist_msi' in sys.argv:
    sys.argv += ['--initial-target-dir', 'C:\InstallDir\\' + productName]
    sys.argv += ['--install-script', 'install.py']

exe = Executable(
      script="main.py",
      base="Win32GUI",
      targetName="Product.exe"
     )
setup(
      name="Product.exe",
      version="1.0",
      author="Me",
      description="Copyright 2012",
      executables=[exe],
      scripts=[
               'install.py'
               ]
      ) 

if statement in ng-click

This maybe irrelevant and of no use, but as it's javascript, you don't have to use the ternary as suggested above in the ng-click statement. You should also be able to use the lazy evaluation ("or die") syntax as well. So for your example above:

<input  ng-click="{{if(profileForm.$valid) updateMyProfile()}}" name="submit" id="submit" value="Save" class="submit" type="submit">

would become:

<input  ng-click="profileForm.$valid && updateMyProfile()" name="submit" id="submit" value="Save" class="submit" type="submit">

In this case, if the profile is not valid then nothing happens, otherwise, updateMyProfile() is called. Like in the link @falinsky provides above.

What tools do you use to test your public REST API?

There is a free tool from theRightAPI that lets you test any HTTP based API. It also lets you save and share your test scenarios.

www.theRightAPI.com/test

How to use support FileProvider for sharing content to other apps?

If you get an image from camera none of these solutions work for Android 4.4. In this case it's better to check versions.

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getContext().getPackageManager()) != null) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        uri = Uri.fromFile(file);
    } else {
        uri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider", file);
    }
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    startActivityForResult(intent, CAMERA_REQUEST);
}

SQL Call Stored Procedure for each Row without using a cursor

A better solution for this is to

  1. Copy/past code of Stored Procedure
  2. Join that code with the table for which you want to run it again (for each row)

This was you get a clean table-formatted output. While if you run SP for every row, you get a separate query result for each iteration which is ugly.

Difference between .keystore file and .jks file

You are confused on this.

A keystore is a container of certificates, private keys etc.

There are specifications of what should be the format of this keystore and the predominant is the #PKCS12

JKS is Java's keystore implementation. There is also BKS etc.

These are all keystore types.

So to answer your question:

difference between .keystore files and .jks files

There is none. JKS are keystore files. There is difference though between keystore types. E.g. JKS vs #PKCS12

Why do we need to install gulp globally and locally?

The question "Why do we need to install gulp globally and locally?" can be broken down into the following two questions:

  1. Why do I need to install gulp locally if I've already installed it globally?

  2. Why do I need to install gulp globally if I've already installed it locally?

Several others have provided excellent answers to theses questions in isolation, but I thought it would be beneficial to consolidate the information in a unified answer.

Why do I need to install gulp locally if I've already installed it globally?

The rationale for installing gulp locally is comprised of several reasons:

  1. Including the dependencies of your project locally ensures the version of gulp (or other dependencies) used is the originally intended version.
  2. Node doesn't consider global modules by default when using require() (which you need to include gulp within your script). Ultimately, this is because the path to the global modules isn't added to NODE_PATH by default.
  3. According to the Node development team, local modules load faster. I can't say why this is, but this would seem to be more relevant to node's use in production (i.e. run-time dependencies) than in development (i.e. dev dependencies). I suppose this is a legitimate reason as some may care about whatever minor speed advantage is gained loading local vs. global modules, but feel free to raise your eyebrow at this reason.

Why do I need to install gulp globally if I've already installed it locally?

  1. The rationale for installing gulp globally is really just the convenience of having the gulp executable automatically found within your system path.

To avoid installing locally you can use npm link [package], but the link command as well as the install --global command doesn't seem to support the --save-dev option which means there doesn't appear to be an easy way to install gulp globally and then easily add whatever version that is to your local package.json file.

Ultimately, I believe it makes more sense to have the option of using global modules to avoid having to duplicate the installation of common tools across all your projects, especially in the case of development tools such as grunt, gulp, jshint, etc. Unfortunately it seems you end up fighting the tools a bit when you go against the grain.

How to clear Flutter's Build cache?

You can run flutter clean.

But that's most likely a problem with your IDE or similar, as flutter run creates a brand new apk. And hot reload push only modifications.

Try running your app using the command line flutter run and then press r or R for respectively hot-reload and full-reload.

Can a table have two foreign keys?

The foreign keys in your schema (on Account_Name and Account_Type) do not require any special treatment or syntax. Just declare two separate foreign keys on the Customer table. They certainly don't constitute a composite key in any meaningful sense of the word.

There are numerous other problems with this schema, but I'll just point out that it isn't generally a good idea to build a primary key out of multiple unique columns, or columns in which one is functionally dependent on another. It appears that at least one of these cases applies to the ID and Name columns in the Customer table. This allows you to create two rows with the same ID (different name), which I'm guessing you don't want to allow.

What is the purpose of the HTML "no-js" class?

The no-js class is used by the Modernizr feature detection library. When Modernizr loads, it replaces no-js with js. If JavaScript is disabled, the class remains. This allows you to write CSS which easily targets either condition.

From Modernizrs' Anotated Source (no longer maintained):

Remove "no-js" class from element, if it exists: docElement.className=docElement.className.replace(/\bno-js\b/,'') + ' js';

Here is a blog post by Paul Irish describing this approach: http://www.paulirish.com/2009/avoiding-the-fouc-v3/


I like to do this same thing, but without Modernizr. I put the following <script> in the <head> to change the class to js if JavaScript is enabled. I prefer to use .replace("no-js","js") over the regex version because its a bit less cryptic and suits my needs.

<script>
    document.documentElement.className = 
       document.documentElement.className.replace("no-js","js");
</script>

Prior to this technique, I would generally just apply js-dependant styles directly with JavaScript. For example:

$('#someSelector').hide();
$('.otherStuff').css({'color' : 'blue'});

With the no-js trick, this can Now be done with css:

.js #someSelector {display: none;}
.otherStuff { color: blue; }
.no-js .otherStuff { color: green }

This is preferable because:

  • It loads faster with no FOUC (flash of unstyled content)
  • Separation of concerns, etc...

MIPS: Integer Multiplication and Division

To multiply, use mult for signed multiplication and multu for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0 that means that you assume the result will fit in 32 bits.

The 32 most significant bits will be held in the HI special register (accessible by mfhi instruction) and the 32 least significant bits will be held in the LO special register (accessible by the mflo instruction):

E.g.:

li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0

To divide, use div for signed division and divu for unsigned division. In this case, the HI special register will hold the remainder and the LO special register will hold the quotient of the division.

E.g.:

div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0

Sqlite convert string to date

One thing you should look into is the SQLite date and time functions, especially if you're going to have to manipulate a lot of dates. It's the sane way to use dates, at the cost of changing the internal format (has to be ISO, i.e. yyyy-MM-dd).

Embed Google Map code in HTML with marker

Learning Google's JavaScript library is a good option. If you don't feel like getting into coding you might find Maps Engine Lite useful.

It is a tool recently published by Google where you can create your personal maps (create markers, draw geometries and adapt the colors and styles).

Here is an useful tutorial I found: Quick Tip: Embedding New Google Maps

What is uintptr_t data type

First thing, at the time the question was asked, uintptr_t was not in C++. It's in C99, in <stdint.h>, as an optional type. Many C++03 compilers do provide that file. It's also in C++11, in <cstdint>, where again it is optional, and which refers to C99 for the definition.

In C99, it is defined as "an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer".

Take this to mean what it says. It doesn't say anything about size.

uintptr_t might be the same size as a void*. It might be larger. It could conceivably be smaller, although such a C++ implementation approaches perverse. For example on some hypothetical platform where void* is 32 bits, but only 24 bits of virtual address space are used, you could have a 24-bit uintptr_t which satisfies the requirement. I don't know why an implementation would do that, but the standard permits it.

Elevating process privilege programmatically?

According to the article Chris Corio: Teach Your Apps To Play Nicely With Windows Vista User Account Control, MSDN Magazine, Jan. 2007, only ShellExecute checks the embedded manifest and prompts the user for elevation if needed, while CreateProcess and other APIs don't. Hope it helps.

See also: same article as .chm.

Why is this jQuery click function not working?

You can use $(function(){ // code }); which is executed when the document is ready to execute the code inside that block.

$(function(){
    $('#clicker').click(function(){
        alert('hey');
        $('.hide_div').hide();
    });
});

How to create JSON string in JavaScript?

json strings can't have line breaks in them. You'd have to make it all one line: {"key":"val","key2":"val2",etc....}.

But don't generate JSON strings yourself. There's plenty of libraries that do it for you, the biggest of which is jquery.

How to test if a file is a directory in a batch script?

Here's a script that uses FOR to build a fully qualified path, and then pushd to test whether the path is a directory. Notice how it works for paths with spaces, as well as network paths.

@echo off
if [%1]==[] goto usage

for /f "delims=" %%i in ("%~1") do set MYPATH="%%~fi"
pushd %MYPATH% 2>nul
if errorlevel 1 goto notdir
goto isdir

:notdir
echo not a directory
goto exit

:isdir
popd
echo is a directory
goto exit

:usage
echo Usage:  %0 DIRECTORY_TO_TEST

:exit

Sample output with the above saved as "isdir.bat":

C:\>isdir c:\Windows\system32
is a directory

C:\>isdir c:\Windows\system32\wow32.dll
not a directory

C:\>isdir c:\notadir
not a directory

C:\>isdir "C:\Documents and Settings"
is a directory

C:\>isdir \
is a directory

C:\>isdir \\ninja\SharedDocs\cpu-z
is a directory

C:\>isdir \\ninja\SharedDocs\cpu-z\cpuz.ini
not a directory

The Use of Multiple JFrames: Good or Bad Practice?

I'd like to counter the "not user friendly" argument with an example that I have just been involved with.

In our application we have a main window where the users run various 'programs' as separate tabs. As much as possible we have tried to keep our application to this single window.

One of the 'programs' they run presents a list of reports that have been generated by the system, and the user can click on an icon on each line to pop open a report viewer dialog. This viewer is showing the equivalent of the portrait/landscape A4 page(s) of the report, so the users like this window to be quite big, almost filling their screens.

A few months ago we started getting requests from our customers to make these report viewer windows modeless, so that they could have multiple reports open at the same time.

For some time I resisted this request as I did not think this was a good solution. However, my mind was changed when I found out how the users were getting around this 'deficiency' of our system.

They were opening a viewer, using the 'Save As' facility to save the report as a PDF to a specific directory, using Acrobat Reader to open the PDF file, and then they would do the same with the next report. They would have multiple Acrobat Readers running with the various report outputs that they wanted to look at.

So I relented and made the viewer modeless. This means that each viewer has a task-bar icon.

When the latest version was released to them last week, the overwhelming response from them is that they LOVE it. It's been one of our most popular recent enhancements to the system.

So you go ahead and tell your users that what they want is bad, but ultimately it won't do you any favours.

SOME NOTES:

  • It seems to be best practice to use JDialog's for these modeless windows
  • Use the constructors that use the new ModalityType rather than the boolean modal argument. This is what gives these dialogs the task-bar icon.
  • For modeless dialogs, pass a null parent to the constructor, but locate them relative to their 'parent' window.
  • Version 6 of Java on Windows has a bug which means that your main window can become 'always on top' without you telling it. Upgrade to version 7 to fix this

Create a file from a ByteArrayOutputStream

You can use a FileOutputStream for this.

FileOutputStream fos = null;
try {
    fos = new FileOutputStream(new File("myFile")); 
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // Put data in your baos

    baos.writeTo(fos);
} catch(IOException ioe) {
    // Handle exception here
    ioe.printStackTrace();
} finally {
    fos.close();
}

How to merge a list of lists with same type of items to a single list of items?

For List<List<List<x>>> and so on, use

list.SelectMany(x => x.SelectMany(y => y)).ToList();

This has been posted in a comment, but it does deserves a separate reply in my opinion.

Select first empty cell in column F starting from row 1. (without using offset )

I just wrote this one-liner to select the first empty cell found in a column based on a selected cell. Only works on first column of selected cells. Modify as necessary

Selection.End(xlDown).Range("A2").Select

TypeError: unhashable type: 'dict', when dict used as a key for another dict

From the error, I infer that referenceElement is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).

>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'

You probably meant either for element in referenceElement.keys() or for element in json['referenceElement'].keys(). With more context on what types json and referenceElement are and what they contain, we will be able to better help you if neither solution works.

How to Import .bson file format on mongodb

If your access remotely you can do it

for bson:

mongorestore --host m2.mongodb.net --port 27016 --ssl --username $user --password $password --authenticationDatabase $authdb -d test -c people "/home/${USER}/people.bson"

for bson compressed in .gz (gzip) format:

mongorestore --host m2.mongodb.net --port 27016 --ssl --username $user --password $password --authenticationDatabase $authdb -d test -c people --gzip --dir "/home/${USER}/people.bson.gz"

How to do if-else in Thymeleaf?

In simpler case (when html tags is the same):

<h2 th:text="${potentially_complex_expression} ? 'Hello' : 'Something else'">/h2>

Div width 100% minus fixed amount of pixels

You can make use of Flexbox layout. You need to set flex: 1 on the element that needs to have dynamic width or height for flex-direction: row and column respectively.

Dynamic width:

HTML

<div class="container">
  <div class="fixed-width">
    1
  </div>
  <div class="flexible-width">
    2
  </div>
  <div class="fixed-width">
    3
  </div>
</div>

CSS

.container {
  display: flex;
}
.fixed-width {
  width: 200px; /* Fixed width or flex-basis: 200px */
}
.flexible-width {
  flex: 1; /* Stretch to occupy remaining width i.e. flex-grow: 1 and flex-shrink: 1*/
}

Output:

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  width: 100%;_x000D_
  color: #fff;_x000D_
  font-family: Roboto;_x000D_
}_x000D_
.fixed-width {_x000D_
  background: #9BCB3C;_x000D_
  width: 200px; /* Fixed width */_x000D_
  text-align: center;_x000D_
}_x000D_
.flexible-width {_x000D_
  background: #88BEF5;_x000D_
  flex: 1; /* Stretch to occupy remaining width */_x000D_
  text-align: center;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="fixed-width">_x000D_
    1_x000D_
  </div>_x000D_
  <div class="flexible-width">_x000D_
    2_x000D_
  </div>_x000D_
  <div class="fixed-width">_x000D_
    3_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_


Dynamic height:

HTML

<div class="container">
  <div class="fixed-height">
    1
  </div>
  <div class="flexible-height">
    2
  </div>
  <div class="fixed-height">
    3
  </div>
</div>

CSS

.container {
  display: flex;
}
.fixed-height {
  height: 200px; /* Fixed height or flex-basis: 200px */
}
.flexible-height {
  flex: 1; /* Stretch to occupy remaining height i.e. flex-grow: 1 and flex-shrink: 1*/
}

Output:

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 100vh;_x000D_
  color: #fff;_x000D_
  font-family: Roboto;_x000D_
}_x000D_
.fixed-height {_x000D_
  background: #9BCB3C;_x000D_
  height: 50px; /* Fixed height or flex-basis: 100px */_x000D_
  text-align: center;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
}_x000D_
.flexible-height {_x000D_
  background: #88BEF5;_x000D_
  flex: 1; /* Stretch to occupy remaining width */_x000D_
  text-align: center;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="fixed-height">_x000D_
    1_x000D_
  </div>_x000D_
  <div class="flexible-height">_x000D_
    2_x000D_
  </div>_x000D_
  <div class="fixed-height">_x000D_
    3_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Set value for particular cell in pandas DataFrame with iloc

For mixed position and index, use .ix. BUT you need to make sure that your index is not of integer, otherwise it will cause confusions.

df.ix[0, 'COL_NAME'] = x

Update:

Alternatively, try

df.iloc[0, df.columns.get_loc('COL_NAME')] = x

Example:

import pandas as pd
import numpy as np

# your data
# ========================
np.random.seed(0)
df = pd.DataFrame(np.random.randn(10, 2), columns=['col1', 'col2'], index=np.random.randint(1,100,10)).sort_index()

print(df)


      col1    col2
10  1.7641  0.4002
24  0.1440  1.4543
29  0.3131 -0.8541
32  0.9501 -0.1514
33  1.8676 -0.9773
36  0.7610  0.1217
56  1.4941 -0.2052
58  0.9787  2.2409
75 -0.1032  0.4106
76  0.4439  0.3337

# .iloc with get_loc
# ===================================
df.iloc[0, df.columns.get_loc('col2')] = 100

df

      col1      col2
10  1.7641  100.0000
24  0.1440    1.4543
29  0.3131   -0.8541
32  0.9501   -0.1514
33  1.8676   -0.9773
36  0.7610    0.1217
56  1.4941   -0.2052
58  0.9787    2.2409
75 -0.1032    0.4106
76  0.4439    0.3337

Mask for an Input to allow phone numbers?

Angular5 and 6:

angular 5 and 6 recommended way is to use @HostBindings and @HostListeners instead of the host property

remove host and add @HostListener

 @HostListener('ngModelChange', ['$event'])
  onModelChange(event) {
    this.onInputChange(event, false);
  }

  @HostListener('keydown.backspace', ['$event'])
  keydownBackspace(event) {
    this.onInputChange(event.target.value, true);
  }

Working Online stackblitz Link: https://angular6-phone-mask.stackblitz.io

Stackblitz Code example: https://stackblitz.com/edit/angular6-phone-mask

Official documentation link https://angular.io/guide/attribute-directives#respond-to-user-initiated-events

Angular2 and 4:

Plunker >= RC.5

original

One way you could do it is using a directive that injects NgControl and manipulates the value

(for details see inline comments)

@Directive({
  selector: '[ngModel][phone]',
  host: {
    '(ngModelChange)': 'onInputChange($event)',
    '(keydown.backspace)': 'onInputChange($event.target.value, true)'
  }
})
export class PhoneMask {
  constructor(public model: NgControl) {}

  onInputChange(event, backspace) {
    // remove all mask characters (keep only numeric)
    var newVal = event.replace(/\D/g, '');
    // special handling of backspace necessary otherwise
    // deleting of non-numeric characters is not recognized
    // this laves room for improvement for example if you delete in the 
    // middle of the string
    if (backspace) {
      newVal = newVal.substring(0, newVal.length - 1);
    } 

    // don't show braces for empty value
    if (newVal.length == 0) {
      newVal = '';
    } 
    // don't show braces for empty groups at the end
    else if (newVal.length <= 3) {
      newVal = newVal.replace(/^(\d{0,3})/, '($1)');
    } else if (newVal.length <= 6) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) ($2)');
    } else {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(.*)/, '($1) ($2)-$3');
    }
    // set the new value
    this.model.valueAccessor.writeValue(newVal);       
  }
}
@Component({
  selector: 'my-app',
  providers: [],
  template: `
  <form [ngFormModel]="form">
    <input type="text" phone [(ngModel)]="data" ngControl="phone"> 
  </form>
  `,
  directives: [PhoneMask]
})
export class App {
  constructor(fb: FormBuilder) {
    this.form = fb.group({
      phone: ['']
    })
  }
}

Plunker example <= RC.5

Find PHP version on windows command line

For Beginners to anything php, it is usually stored in the C:/ path folder of your PC (My Computer).

==On Windows==
1.Click Start Menu button
2.Type cmd and press enter to select the first program/application that responds to your search result.
A black window terminal will appear, this is known as a Command Line Interpreter
3.In the Terminal Window (Application) Type cd c: and press enter
4.Now type php -v and press enter

and viola there you'll have the current php version that is installed in your machine

What is a simple command line program or script to backup SQL server databases?

I found this on a Microsoft Support page http://support.microsoft.com/kb/2019698.

It works great! And since it came from Microsoft, I feel like it's pretty legit.

Basically there are two steps.

  1. Create a stored procedure in your master db. See msft link or if it's broken try here: http://pastebin.com/svRLkqnq
  2. Schedule the backup from your task scheduler. You might want to put into a .bat or .cmd file first and then schedule that file.

    sqlcmd -S YOUR_SERVER_NAME\SQLEXPRESS -E -Q "EXEC sp_BackupDatabases @backupLocation='C:\SQL_Backup\', @backupType='F'"  1>c:\SQL_Backup\backup.log            
    

Obviously replace YOUR_SERVER_NAME with your computer name or optionally try .\SQLEXPRESS and make sure the backup folder exists. In this case it's trying to put it into c:\SQL_Backup

convert string date to java.sql.Date

This works for me without throwing an exception:

package com.sandbox;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Sandbox {

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date parsed = format.parse("20110210");
        java.sql.Date sql = new java.sql.Date(parsed.getTime());
    }


}

React.js: Identifying different inputs with one onChange handler

You can use the .bind method to pre-build the parameters to the handleChange method. It would be something like:

  var Hello = React.createClass({
    getInitialState: function() {
        return {input1:0, 
                input2:0};
    },
    render: function() {
      var total = this.state.input1 + this.state.input2;
      return (
        <div>{total}<br/>
          <input type="text" value={this.state.input1} 
                             onChange={this.handleChange.bind(this, 'input1')} />
          <input type="text" value={this.state.input2} 
                             onChange={this.handleChange.bind(this, 'input2')} />
        </div>
      );
    },
    handleChange: function (name, e) {
      var change = {};
      change[name] = e.target.value;
      this.setState(change);
    }
  });

  React.renderComponent(<Hello />, document.getElementById('content'));

(I also made total be computed at render time, as it is the recommended thing to do.)

How can I export data to an Excel file

Have you ever hear NPOI, a .NET library that can read/write Office formats without Microsoft Office installed. No COM+, no interop. Github Page

This is my Excel Export class

/*
 * User: TMPCSigit [email protected]
 * Date: 25/11/2019
 * Time: 11:28
 * 
 */
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace Employee_Manager
{
    public static class ExportHelper
    {       
        public static void WriteCell( ISheet sheet, int columnIndex, int rowIndex, string value )
        {
            var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
            var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );

            cell.SetCellValue( value );
        }
        public static void WriteCell( ISheet sheet, int columnIndex, int rowIndex, double value )
        {
            var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
            var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );

            cell.SetCellValue( value );
        }
        public static void WriteCell( ISheet sheet, int columnIndex, int rowIndex, DateTime value )
        {
            var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
            var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );

            cell.SetCellValue( value );
        }
        public static void WriteStyle( ISheet sheet, int columnIndex, int rowIndex, ICellStyle style )
        {
            var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
            var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );

            cell.CellStyle = style;
        }

        public static IWorkbook CreateNewBook( string filePath )
        {
            IWorkbook book;
            var extension = Path.GetExtension( filePath );

            // HSSF => Microsoft Excel(xls??)(excel 97-2003)
            // XSSF => Office Open XML Workbook??(xlsx??)(excel 2007??)
            if( extension == ".xls" ) {
                book = new HSSFWorkbook();
            }
            else if( extension == ".xlsx" ) {
                book = new XSSFWorkbook();
            }
            else {
                throw new ApplicationException( "CreateNewBook: invalid extension" );
            }

            return book;
        }
        public static void createXls(DataGridView dg){
            try {
                string filePath = "";
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "Excel XLS (*.xls)|*.xls";
                sfd.FileName = "Export.xls";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    filePath = sfd.FileName;
                    var book = CreateNewBook( filePath );
                    book.CreateSheet( "Employee" );
                    var sheet = book.GetSheet( "Employee" );
                    int columnCount = dg.ColumnCount;
                    string columnNames = "";
                    string[] output = new string[dg.RowCount + 1];
                    for (int i = 0; i < columnCount; i++)
                    {
                        WriteCell( sheet, i, 0, SplitCamelCase(dg.Columns[i].Name.ToString()) );
                    }
                    for (int i = 0; i < dg.RowCount; i++)
                    {
                        for (int j = 0; j < columnCount; j++)
                        {
                            var celData =  dg.Rows[i].Cells[j].Value;
                            if(celData == "" || celData == null){
                                celData = "-";
                            }
                            if(celData.ToString() == "System.Drawing.Bitmap"){
                                celData = "Ada";
                            }
                            WriteCell( sheet, j, i+1, celData.ToString() );
                        }
                    }
                    var style = book.CreateCellStyle();
                    style.DataFormat = book.CreateDataFormat().GetFormat( "yyyy/mm/dd" );
                    WriteStyle( sheet, 0, 4, style );
                    using( var fs = new FileStream( filePath, FileMode.Create ) ) {
                        book.Write( fs );
                    }
                }
            }
            catch( Exception ex ) {
                Console.WriteLine( ex );
            }
        }
        public static string SplitCamelCase(string input)
        {
            return Regex.Replace(input, "(?<=[a-z])([A-Z])", " $1", RegexOptions.Compiled);
        }
    }
}

How to define a default value for "input type=text" without using attribute 'value'?

The value is there. The source is not updated as the values on the form change. The source is from when the page initially loaded.

how to change namespace of entire project?

Just right click the solution, go to properties, change "default namespace" under 'Application' section.

enter image description here

Convert/cast an stdClass object to another class

Convert it to an array, return the first element of that array, and set the return param to that class. Now you should get the autocomplete for that class as it will regconize it as that class instead of stdclass.

/**
 * @return Order
 */
    public function test(){
    $db = new Database();

    $order = array();
    $result = $db->getConnection()->query("select * from `order` where productId in (select id from product where name = 'RTX 2070')");
    $data = $result->fetch_object("Order"); //returns stdClass
    array_push($order, $data);

    $db->close();
    return $order[0];
}

HTML: how to force links to open in a new tab, not new window

Since I fell into this old question and then found that it is now possible (maybe this css option wasn't available then), I just want to add an update on how it can be done:

<a href="[yourlink]" target="_blank" style="target-new: tab;">Google</a>

Here are the options for the target-new style:

target-new: window | tab | none 

Didn't test the none option, maybe it uses the default browser setting.

I confirmed this for Firefox and IE7-9.

Using Mockito to mock classes with generic parameters

I agree that one shouldn't suppress warnings in classes or methods as one could overlook other, accidentally suppressed warnings. But IMHO it's absolutely reasonable to suppress a warning that affects only a single line of code.

@SuppressWarnings("unchecked")
Foo<Bar> mockFoo = mock(Foo.class);

jQuery OR Selector?

Using a comma may not be sufficient if you have multiple jQuery objects that need to be joined.

The .add() method adds the selected elements to the result set:

// classA OR classB
jQuery('.classA').add('.classB');

It's more verbose than '.classA, .classB', but lets you build more complex selectors like the following:

// (classA which has <p> descendant) OR (<div> ancestors of classB)
jQuery('.classA').has('p').add(jQuery('.classB').parents('div'));

How to Automatically Start a Download in PHP?

my code works for txt,doc,docx,pdf,ppt,pptx,jpg,png,zip extensions and I think its better to use the actual MIME types explicitly.

$file_name = "a.txt";

// extracting the extension:
$ext = substr($file_name, strpos($file_name,'.')+1);

header('Content-disposition: attachment; filename='.$file_name);

if(strtolower($ext) == "txt")
{
    header('Content-type: text/plain'); // works for txt only
}
else
{
    header('Content-type: application/'.$ext); // works for all extensions except txt
}
readfile($decrypted_file_path);

Good MapReduce examples

One set of familiar operations that you can do in MapReduce is the set of normal SQL operations: SELECT, SELECT WHERE, GROUP BY, ect.

Another good example is matrix multiply, where you pass one row of M and the entire vector x and compute one element of M * x.

TortoiseSVN icons not showing up under Windows 7

Sometimes you just need to go to TortoiseSVN "settings", turn the icons off, click "apply", turn them back on.

Windows Start->All Programs->TortoiseSVN->Settings

enter image description here

How to execute .sql script file using JDBC

You should be able to parse the SQL file into statements. And run a single statement a time. If you know that your file consists of simple insert/update/delete statements you can use a semicolon as statement delimiter. In common case you have a task to create your specific SQL-dialect parser.

When should I use GC.SuppressFinalize()?

SupressFinalize tells the system that whatever work would have been done in the finalizer has already been done, so the finalizer doesn't need to be called. From the .NET docs:

Objects that implement the IDisposable interface can call this method from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it.

In general, most any Dispose() method should be able to call GC.SupressFinalize(), because it should clean up everything that would be cleaned up in the finalizer.

SupressFinalize is just something that provides an optimization that allows the system to not bother queuing the object to the finalizer thread. A properly written Dispose()/finalizer should work properly with or without a call to GC.SupressFinalize().

How can I set the aspect ratio in matplotlib?

Third times the charm. My guess is that this is a bug and Zhenya's answer suggests it's fixed in the latest version. I have version 0.99.1.1 and I've created the following solution:

import matplotlib.pyplot as plt
import numpy as np

def forceAspect(ax,aspect=1):
    im = ax.get_images()
    extent =  im[0].get_extent()
    ax.set_aspect(abs((extent[1]-extent[0])/(extent[3]-extent[2]))/aspect)

data = np.random.rand(10,20)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(data)
ax.set_xlabel('xlabel')
ax.set_aspect(2)
fig.savefig('equal.png')
ax.set_aspect('auto')
fig.savefig('auto.png')
forceAspect(ax,aspect=1)
fig.savefig('force.png')

This is 'force.png': enter image description here

Below are my unsuccessful, yet hopefully informative attempts.

Second Answer:

My 'original answer' below is overkill, as it does something similar to axes.set_aspect(). I think you want to use axes.set_aspect('auto'). I don't understand why this is the case, but it produces a square image plot for me, for example this script:

import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(10,20)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(data)
ax.set_aspect('equal')
fig.savefig('equal.png')
ax.set_aspect('auto')
fig.savefig('auto.png')

Produces an image plot with 'equal' aspect ratio: enter image description here and one with 'auto' aspect ratio: enter image description here

The code provided below in the 'original answer' provides a starting off point for an explicitly controlled aspect ratio, but it seems to be ignored once an imshow is called.

Original Answer:

Here's an example of a routine that will adjust the subplot parameters so that you get the desired aspect ratio:

import matplotlib.pyplot as plt

def adjustFigAspect(fig,aspect=1):
    '''
    Adjust the subplot parameters so that the figure has the correct
    aspect ratio.
    '''
    xsize,ysize = fig.get_size_inches()
    minsize = min(xsize,ysize)
    xlim = .4*minsize/xsize
    ylim = .4*minsize/ysize
    if aspect < 1:
        xlim *= aspect
    else:
        ylim /= aspect
    fig.subplots_adjust(left=.5-xlim,
                        right=.5+xlim,
                        bottom=.5-ylim,
                        top=.5+ylim)

fig = plt.figure()
adjustFigAspect(fig,aspect=.5)
ax = fig.add_subplot(111)
ax.plot(range(10),range(10))

fig.savefig('axAspect.png')

This produces a figure like so: enter image description here

I can imagine if your having multiple subplots within the figure, you would want to include the number of y and x subplots as keyword parameters (defaulting to 1 each) to the routine provided. Then using those numbers and the hspace and wspace keywords, you can make all the subplots have the correct aspect ratio.

Error CS2001: Source file '.cs' could not be found

I open the project,.csproj, using a notepad and delete that missing file reference.

Organizing a multiple-file Go project

I would recommend reviewing this page on How to Write Go Code

It documents both how to structure your project in a go build friendly way, and also how to write tests. Tests do not need to be a cmd using the main package. They can simply be TestX named functions as part of each package, and then go test will discover them.

The structure suggested in that link in your question is a bit outdated, now with the release of Go 1. You no longer would need to place a pkg directory under src. The only 3 spec-related directories are the 3 in the root of your GOPATH: bin, pkg, src . Underneath src, you can simply place your project mypack, and underneath that is all of your .go files including the mypack_test.go

go build will then build into the root level pkg and bin.

So your GOPATH might look like this:

~/projects/
    bin/
    pkg/
    src/
      mypack/
        foo.go
        bar.go
        mypack_test.go

export GOPATH=$HOME/projects

$ go build mypack
$ go test mypack

Update: as of >= Go 1.11, the Module system is now a standard part of the tooling and the GOPATH concept is close to becoming obsolete.

Remove blank attributes from an Object in Javascript

You can also use ...spread syntax using forEach something like this:

let obj = { a: 1, b: "b", c: undefined, d: null };
let cleanObj = {};

Object.keys(obj).forEach(val => {
  const newVal = obj[val];
  cleanObj = newVal ? { ...cleanObj, [val]: newVal } : cleanObj;
});

console.info(cleanObj);

How to change Hash values?

I do something like this:

new_hash = Hash[*original_hash.collect{|key,value| [key,value + 1]}.flatten]

This provides you with the facilities to transform the key or value via any expression also (and it's non-destructive, of course).

Why do I have ORA-00904 even when the column is present?

Have you compared the table definitions in Prod and Dev?

And when you are running it in SQL Developer, are you running the query in Prod (same database as the application) and with the same user?

If there are some additional columns that you are adding (using an alter command) and these changes are not yet promoted to prod, this issue is possible.

Can you post the definition of the table and your actual Query?

Bootstrap 3 navbar active li not changing background-color

Well, I had a similar challenge. Using the inspect element tool in Firefox, I was able to trace the markup and the CSS used to style the link when clicked. On click, the list item (li) is given a class of .open and it's the anchor tag in the class that is formatted with the grey color background.

To fix this, just add this to your stylesheet.

.nav .open > a
{
    background:#759ad6;
    // Put in styling
}

Get the current displaying UIViewController on the screen in AppDelegate.m

zirinisp's Answer in Swift:

extension UIWindow {

    func visibleViewController() -> UIViewController? {
        if let rootViewController: UIViewController  = self.rootViewController {
            return UIWindow.getVisibleViewControllerFrom(rootViewController)
        }
        return nil
    }

    class func getVisibleViewControllerFrom(vc:UIViewController) -> UIViewController {

        if vc.isKindOfClass(UINavigationController.self) {

            let navigationController = vc as UINavigationController
            return UIWindow.getVisibleViewControllerFrom( navigationController.visibleViewController)

        } else if vc.isKindOfClass(UITabBarController.self) {

            let tabBarController = vc as UITabBarController
            return UIWindow.getVisibleViewControllerFrom(tabBarController.selectedViewController!)

        } else {

            if let presentedViewController = vc.presentedViewController {

                return UIWindow.getVisibleViewControllerFrom(presentedViewController.presentedViewController!)

            } else {

                return vc;
            }
        }
    }
}

Usage:

 if let topController = window.visibleViewController() {
            println(topController)
        }

bash script read all the files in directory

A simple loop should be working:

for file in /var/*
do
    #whatever you need with "$file"
done

See bash filename expansion

"column not allowed here" error in INSERT statement

INSERT INTO LOCATION VALUES(PQ95VM,'HAPPY_STREET','FRANCE');

the above mentioned code is not correct because your first parameter POSTCODE is of type VARCHAR(10). you should have used ' '.

try INSERT INTO LOCATION VALUES('PQ95VM','HAPPY_STREET','FRANCE');

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

adding this worked for me.

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

Where is Android Studio layout preview?

File>>setting>>Compiler>>JavaCompiler At "Project bytecode version(leave blank for jdk default):" choose your jdk.

enter image description here