Programs & Examples On #Z notation

How to pass values across the pages in ASP.net without using Session

You can pass values from one page to another by followings..

Response.Redirect
Cookies
Application Variables
HttpContext

Response.Redirect

SET :

Response.Redirect("Defaultaspx?Name=Pandian");

GET :

string Name = Request.QueryString["Name"];

Cookies

SET :

HttpCookie cookName = new HttpCookie("Name");
cookName.Value = "Pandian"; 

GET :

string name = Request.Cookies["Name"].Value;

Application Variables

SET :

Application["Name"] = "pandian";

GET :

string Name = Application["Name"].ToString();

Refer the full content here : Pass values from one to another

DataTable, How to conditionally delete rows

You could query the dataset and then loop the selected rows to set them as delete.

var rows = dt.Select("col1 > 5");
foreach (var row in rows)
    row.Delete();

... and you could also create some extension methods to make it easier ...

myTable.Delete("col1 > 5");

public static DataTable Delete(this DataTable table, string filter)
{
    table.Select(filter).Delete();
    return table;
}
public static void Delete(this IEnumerable<DataRow> rows)
{
    foreach (var row in rows)
        row.Delete();
}

How to merge 2 List<T> and removing duplicate values from it in C#

why not simply eg

var newList = list1.Union(list2)/*.Distinct()*//*.ToList()*/;

oh ... according to the documentation you can leave out the .Distinct()

This method excludes duplicates from the return set

How to find/identify large commits in git history?

How can I track down the large files in the git history?

Start by analyzing, validating and selecting the root cause. Use git-repo-analysis to help.

You may also find some value in the detailed reports generated by BFG Repo-Cleaner, which can be run very quickly by cloning to a Digital Ocean droplet using their 10MiB/s network throughput.

How to insert Records in Database using C# language?

You should form the command with the contents of the textboxes:

sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text + "," + textbox3.Text+ ")";

This, of course, provided that you manage to open the connection correctly.

It would be helpful to know what's happening with your current code. If you are getting some error displayed in that message box, it would be great to know what it's saying.

You should also validate the inputs before actually running the command (i.e. make sure they don't contain malicious code...).

Print DIV content by JQuery

You can follow these steps :

  1. wrap the div you want to print into another div.
  2. set the wrapper div display status to none in css.
  3. keep the div you want to print display status as block, anyway it will be hidden as its parent is hidden.
  4. simply call $('SelectorToPrint').printElement();

What do Push and Pop mean for Stacks?

  • push = add to the stack
  • pop = remove from the stack

How to convert Set<String> to String[]?

I was facing the same situation.

I begin by declaring the structures I need:

Set<String> myKeysInSet = null; String[] myArrayOfString = null;

In my case, I have a JSON object and I need all the keys in this JSON to be stored in an array of strings. Using the GSON library, I use JSON.keySet() to get the keys and move to my Set :

myKeysInSet = json_any.keySet();

With this, I have a Set structure with all the keys, as I needed it. So I just need to the values to my Array of Strings. See the code below:

myArrayOfString = myKeysInSet.toArray(new String[myKeysInSet.size()]);

This was my first answer in StackOverflow. Sorry for any error :D

How to clear the cache in NetBeans

Close NetBeans before deleting the cache.

NetBeans 7.2+, Windows 7

Cache is located in C:\Users\<username>\AppData\Local\NetBeans\Cache\.

Clear the cache using the %USERPROFILE% Windows variable:

del /s /q %USERPROFILE%\AppData\Local\NetBeans\Cache\

If it is set, you can also use the environment variable %LOCALAPPDATA%:

del /s /q %LOCALAPPDATA%\NetBeans\Cache\

NetBeans 7.2+, Linux

Cache is at: ~/.cache/netbeans/${netbeans_version}/index/

Mac OS X

Cache is at: ~/Library/Caches/NetBeans/${netbeans_version}/

See also http://wiki.netbeans.org/FaqWhatIsUserdir.

Help Menu

On Windows, selecting the Help » About menu will display a dialog that contains the following text:

Product Version: NetBeans IDE 8.0.2 (Build 201411181905)
Java: 1.7.0_80; Java HotSpot(TM) 64-Bit Server VM 24.80-b11
Runtime: Java(TM) SE Runtime Environment 1.7.0_80-b15
System: Windows 7 version 6.1 running on amd64; Cp1252; en_CA (nb)
User directory: C:\Users\Username\AppData\Roaming\NetBeans\8.0.2
Cache directory: C:\Users\Username\AppData\Local\NetBeans\Cache\8.0.2

Regardless of operating system, the About dialog will contain the correct path to the cache directory.

How to replace all special character into a string using C#

You can use a regular expresion to for example replace all non-alphanumeric characters with commas:

s = Regex.Replace(s, "[^0-9A-Za-z]+", ",");

Note: The + after the set will make it replace each group of non-alphanumeric characters with a comma. If you want to replace each character with a comma, just remove the +.

Python integer division yields float

Oops, immediately found 2//2.

Present and dismiss modal view controller

Swift

self.dismissViewControllerAnimated(true, completion: nil)

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

There is nothing to identify. Interfaces only proscribe a method name and signature. If both interfaces have a method of exactly the same name and signature, the implementing class can implement both interface methods with a single concrete method.

However, if the semantic contracts of the two interface method are contradicting, you've pretty much lost; you cannot implement both interfaces in a single class then.

How to include PHP files that require an absolute path?

have a look at http://au.php.net/reserved.variables

I think the variable you are looking for is: $_SERVER["DOCUMENT_ROOT"]

parseInt with jQuery

var test = parseInt($("#testid").val(), 10);

You have to tell it you want the value of the input you are targeting.

And also, always provide the second argument (radix) to parseInt. It tries to be too clever and autodetect it if not provided and can lead to unexpected results.

Providing 10 assumes you are wanting a base 10 number.

How to define partitioning of DataFrame?

Use the DataFrame returned by:

yourDF.orderBy(account)

There is no explicit way to use partitionBy on a DataFrame, only on a PairRDD, but when you sort a DataFrame, it will use that in it's LogicalPlan and that will help when you need to make calculations on each Account.

I just stumbled upon the same exact issue, with a dataframe that I want to partition by account. I assume that when you say "want to have the data partitioned so that all of the transactions for an account are in the same Spark partition", you want it for scale and performance, but your code doesn't depend on it (like using mapPartitions() etc), right?

Find the most common element in a list

def mostCommonElement(list):
  count = {} // dict holder
  max = 0 // keep track of the count by key
  result = None // holder when count is greater than max
  for i in list:
    if i not in count:
      count[i] = 1
    else:
      count[i] += 1
    if count[i] > max:
      max = count[i]
      result = i
  return result

mostCommonElement(["a","b","a","c"]) -> "a"

How to fix 'Microsoft Excel cannot open or save any more documents'

Go to this key on Registry Editor (Run | Regedit) HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders

change key Cache to something like C:\Windows\Temp

My similar problem was solved like this.

Regards,

Ripley

How do I get the number of elements in a list?

The len() function can be used with several different types in Python - both built-in types and library types. For example:

>>> len([1, 2, 3])
3

How to manually set REFERER header in Javascript?

I think that understanding why you can't change the referer header might help people reading this question.

From this page: https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name

From that link:

A forbidden header name is the name of any HTTP header that cannot be modified programmatically...

Modifying such headers is forbidden because the user agent retains full control over them.

Forbidden header names ... are one of the following names:

...

Referer

...

Accessing attributes from an AngularJS directive

Although using '@' is more appropriate than using '=' for your particular scenario, sometimes I use '=' so that I don't have to remember to use attrs.$observe():

<su-label tooltip="field.su_documentation">{{field.su_name}}</su-label>

Directive:

myApp.directive('suLabel', function() {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: {
            title: '=tooltip'
        },
        template: '<label><a href="#" rel="tooltip" title="{{title}}" data-placement="right" ng-transclude></a></label>',
        link: function(scope, element, attrs) {
            if (scope.title) {
                element.addClass('tooltip-title');
            }
        },
    }
});

Fiddle.

With '=' we get two-way databinding, so care must be taken to ensure scope.title is not accidentally modified in the directive. The advantage is that during the linking phase, the local scope property (scope.title) is defined.

Jquery Open in new Tab (_blank)

Replace this line:

$(this).target = "_blank";

With:

$( this ).attr( 'target', '_blank' );

That will set its HREF to _blank.

SQL server ignore case in a where expression

In the default configuration of a SQL Server database, string comparisons are case-insensitive. If your database overrides this setting (through the use of an alternate collation), then you'll need to specify what sort of collation to use in your query.

SELECT * FROM myTable WHERE myField = 'sOmeVal' COLLATE SQL_Latin1_General_CP1_CI_AS

Note that the collation I provided is just an example (though it will more than likely function just fine for you). A more thorough outline of SQL Server collations can be found here.

What does map(&:name) mean in Ruby?

Another cool shorthand, unknown to many, is

array.each(&method(:foo))

which is a shorthand for

array.each { |element| foo(element) }

By calling method(:foo) we took a Method object from self that represents its foo method, and used the & to signify that it has a to_proc method that converts it into a Proc.

This is very useful when you want to do things point-free style. An example is to check if there is any string in an array that is equal to the string "foo". There is the conventional way:

["bar", "baz", "foo"].any? { |str| str == "foo" }

And there is the point-free way:

["bar", "baz", "foo"].any?(&"foo".method(:==))

The preferred way should be the most readable one.

REST URI convention - Singular or plural name of resource while creating it

Singular

Convenience Things can have irregular plural names. Sometimes they don't have one. But Singular names are always there.

e.g. CustomerAddress over CustomerAddresses

Consider this related resource.

This /order/12/orderdetail/12 is more readable and logical than /orders/12/orderdetails/4.

Database Tables

A resource represents an entity like a database table. It should have a logical singular name. Here's the answer over table names.

Class Mapping

Classes are always singular. ORM tools generate tables with the same names as class names. As more and more tools are being used, singular names are becoming a standard.

Read more about A REST API Developer's Dilemma

For things without singular names

In the case of trousers and sunglasses, they don't seem to have a singular counterpart. They are commonly known and they appear to be singular by use. Like a pair of shoes. Think about naming the class file Shoe or Shoes. Here these names must be considered as a singular entity by their use. You don't see anyone buying a single shoe to have the URL as

/shoe/23

We have to see Shoes as a singular entity.

Reference: Top 6 REST Naming Best Practices

How to install a specific JDK on Mac OS X?

JDK is the Java Development Kit (used to develop Java software).

JRE is the Java Runtime Environment (used to run any .jar file 'Java software').

The JDK contains a JRE inside it.

On Windows when you update Java, it updates the JRE automatically.

On Mac you do not have a JRE separated you have it, but inside the JDK, so when you update Java it will update your JRE which is inside your JDK; it doesn't install an JDK for you. You need to get it from somewhere else.

How to select specified node within Xpath node sets by index with Selenium?

Here is the solution for index variable

Let's say, you have found 5 elements with same locator and you would like to perform action on each element by providing index number (here, variable is used for index as "i")

for(int i=1; i<=5; i++)
{
    string xPathWithVariable = "(//div[@class='className'])" + "[" + i + "]";
    driver.FindElement(By.XPath(xPathWithVariable)).Click();
}

It takes XPath :

(//div[@class='className'])[1]
(//div[@class='className'])[2]
(//div[@class='className'])[3]
(//div[@class='className'])[4]
(//div[@class='className'])[5]

How can I merge the columns from two tables into one output?

When your are three tables or more, just add union and left outer join:

select a.col1, b.col2, a.col3, b.col4, a.category_id 
from 
(
    select category_id from a
    union
    select category_id from b
) as c
left outer join a on a.category_id = c.category_id
left outer join b on b.category_id = c.category_id

Converting pfx to pem using openssl

You can use the OpenSSL Command line tool. The following commands should do the trick

openssl pkcs12 -in client_ssl.pfx -out client_ssl.pem -clcerts

openssl pkcs12 -in client_ssl.pfx -out root.pem -cacerts

If you want your file to be password protected etc, then there are additional options.

You can read the entire documentation here.

How to change the playing speed of videos in HTML5?

(Tested in Chrome while playing videos on YouTube, but should work anywhere--especially useful for speeding up online training videos).

For anyone wanting to add these as "bookmarklets" (bookmarks) to your browser, use these browser bookmark names and URLs, and add each of the following bookmarks to the top of your browser:

enter image description here

Name: 0.5x
URL:

javascript:

document.querySelector('video').playbackRate = 0.5;

Name: 1.0x
URL:

javascript:

document.querySelector('video').playbackRate = 1.0;

Name: 1.5x
URL:

javascript:

document.querySelector('video').playbackRate = 1.5;

Name: 2.0x
URL:

javascript:

document.querySelector('video').playbackRate = 2.0;

References:

  1. The main answer by Jeremy Visser
  2. Copied from my GitHub gist here: https://gist.github.com/ElectricRCAircraftGuy/0a788876da1386ca0daecbe78b4feb44#other-bookmarklets
    1. Get other bookmarklets here too, such as for aiding you on GitHub.

How to add Button over image using CSS?

<div class="content"> 
  Counter-Strike 1.6 Steam 
     <img src="images/CSsteam.png">
     <a href="#">Koupit</a>
</div>

/*Use this css*/
content {
width: 182px; /*328 co je 1/3 - 20margin left*/
height: 121px;
line-height: 20px;
margin-top: 0px;
margin-left: 9px;
margin-right:0px;
display:inline-block;
position:relative;
}
content a{
display:inline-block;
padding:10px;
position:absolute;
bottom:10px;
right:10px;
}

How to restart Jenkins manually?

If you have no permissions or access to the command line directly, you can do e.g. one of the following:

  1. Create a job with shell/batch step that will trigger a restart from the Jenkins installation folder
  2. Install/update some plugin while checking "restart after installation" (at least this works in old versions)

Both above are hacks, but I actively used them in a very restricted environment where no one wanted me to restart Jenkins, huh.

Is there a max array length limit in C++?

There are two limits, both not enforced by C++ but rather by the hardware.

The first limit (should never be reached) is set by the restrictions of the size type used to describe an index in the array (and the size thereof). It is given by the maximum value the system's std::size_t can take. This data type is large enough to contain the size in bytes of any object

The other limit is a physical memory limit. The larger your objects in the array are, the sooner this limit is reached because memory is full. For example, a vector<int> of a given size n typically takes multiple times as much memory as an array of type vector<char> (minus a small constant value), since int is usually bigger than char. Therefore, a vector<char> may contain more items than a vector<int> before memory is full. The same counts for raw C-style arrays like int[] and char[].

Additionally, this upper limit may be influenced by the type of allocator used to construct the vector because an allocator is free to manage memory any way it wants. A very odd but nontheless conceivable allocator could pool memory in such a way that identical instances of an object share resources. This way, you could insert a lot of identical objects into a container that would otherwise use up all the available memory.

Apart from that, C++ doesn't enforce any limits.

How to push a single file in a subdirectory to Github (not master)

git status #then file which you need to push git add example.FileExtension

git commit "message is example"

git push -u origin(or whatever name you used) master(or name of some branch where you want to push it)

SSL peer shut down incorrectly in Java

Apart from the accepted answer, other problems can cause the exception too. For me it was that the certificate was not trusted (i.e., self-signed cert and not in the trust store).

If the certificate file does not exists, or could not be loaded (e.g., typo in path) can---in certain circumstances---cause the same exception.

How to open select file dialog via js?

For the sake of completeness, Ron van der Heijden's solution in pure JavaScript:

<button onclick="document.querySelector('.inputFile').click();">Select File ...</button>
<input class="inputFile" type="file" style="display: none;">

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

I was receiving the same error. You need to go increase the column length while importing the data for particular column. Choose a data source >> Advanced >> increase the column from default 50 to 200 or more.

It worked for me!

How to get the new value of an HTML input after a keypress has modified it?

There are two kinds of input value: field's property and field's html attribute.

If you use keyup event and field.value you shuld get current value of the field. It's not the case when you use field.getAttribute('value') which would return what's in the html attribute (value=""). The property represents what's been typed into the field and changes as you type, while attribute doesn't change automatically (you can change it using field.setAttribute method).

How do I fix "for loop initial declaration used outside C99 mode" GCC error?

To switch to C99 mode in CodeBlocks, follow the next steps:

Click Project/Build options, then in tab Compiler Settings choose subtab Other options, and place -std=c99 in the text area, and click Ok.

This will turn C99 mode on for your Compiler.

I hope this will help someone!

Copy a variable's value into another

I solved it myself for the time being. The original value has only 2 sub-properties. I reformed a new object with the properties from a and then assigned it to b. Now my event handler updates only b, and my original a stays as it is.

var a = { key1: 'value1', key2: 'value2' },
    b = a;

$('#revert').on('click', function(e){
    //FAIL!
    b = a;

    //WIN
    b = { key1: a.key1, key2: a.key2 };
});

This works fine. I have not changed a single line anywhere in my code except for the above, and it works just how I wanted it to. So, trust me, nothing else was updating a.

Why would you use String.Equals over ==?

I want to add that there is another difference. It is related to what Andrew posts.

It is also related to a VERY annoying to find bug in our software. See the following simplified example (I also omitted the null check).

public const int SPECIAL_NUMBER = 213;

public bool IsSpecialNumberEntered(string numberTextBoxTextValue)
{
    return numberTextBoxTextValue.Equals(SPECIAL_NUMBER)
}

This will compile and always return false. While the following will give a compile error:

public const int SPECIAL_NUMBER = 213;

public bool IsSpecialNumberEntered(string numberTextBoxTextValue)
{
    return (numberTextBoxTextValue == SPECIAL_NUMBER);
}

We have had to solve a similar problem where someone compared enums of different type using Equals. You are going to read over this MANY times before realising it is the cause of the bug. Especially if the definition of SPECIAL_NUMBER is not near the problem area.

This is why I am really against the use of Equals in situations where is it not necessary. You lose a little bit of type-safety.

Convert a byte array to integer in Java and vice versa

byte[] toByteArray(int value) {
     return  ByteBuffer.allocate(4).putInt(value).array();
}

byte[] toByteArray(int value) {
    return new byte[] { 
        (byte)(value >> 24),
        (byte)(value >> 16),
        (byte)(value >> 8),
        (byte)value };
}

int fromByteArray(byte[] bytes) {
     return ByteBuffer.wrap(bytes).getInt();
}
// packing an array of 4 bytes to an int, big endian, minimal parentheses
// operator precedence: <<, &, | 
// when operators of equal precedence (here bitwise OR) appear in the same expression, they are evaluated from left to right
int fromByteArray(byte[] bytes) {
     return bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);
}

// packing an array of 4 bytes to an int, big endian, clean code
int fromByteArray(byte[] bytes) {
     return ((bytes[0] & 0xFF) << 24) | 
            ((bytes[1] & 0xFF) << 16) | 
            ((bytes[2] & 0xFF) << 8 ) | 
            ((bytes[3] & 0xFF) << 0 );
}

When packing signed bytes into an int, each byte needs to be masked off because it is sign-extended to 32 bits (rather than zero-extended) due to the arithmetic promotion rule (described in JLS, Conversions and Promotions).

There's an interesting puzzle related to this described in Java Puzzlers ("A Big Delight in Every Byte") by Joshua Bloch and Neal Gafter . When comparing a byte value to an int value, the byte is sign-extended to an int and then this value is compared to the other int

byte[] bytes = (…)
if (bytes[0] == 0xFF) {
   // dead code, bytes[0] is in the range [-128,127] and thus never equal to 255
}

Note that all numeric types are signed in Java with exception to char being a 16-bit unsigned integer type.

Git push error: "origin does not appear to be a git repository"

If you are on HTTPS do this-

git remote add origin URL_TO_YOUR_REPO

How do I enable logging for Spring Security?

You can easily enable debugging support using an option for the @EnableWebSecurity annotation:

@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    …
}

If you need profile-specific control the in your application-{profile}.properties file

org.springframework.security.config.annotation.web.builders.WebSecurity.debugEnabled=false

Get Detailed Post: http://www.bytefold.com/enable-disable-profile-specific-spring-security-debug-flag/

XAMPP Object not found error

Object not found!

The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.

You're having problem because the object really doesn't exist in your htdocs directory. You don't have to append xampp after localhost or 127.0.0.1 because xampp will treat it as an object or a folder under htdocs.

if you want to access your blog, make sure you have a blog folder under htdocs and put in your URL localhost/blog

git rebase: "error: cannot stat 'file': Permission denied"

We resolved permission issues by right-clicking sh.exe in Program Files and by setting "Run as Administrator" in the Security tab.

How to rotate a 3D object on axis three.js?

Just in case...in r52 the method is called setEulerFromRotationMatrix instead of getRotationFromMatrix

exception in initializer error in java when using Netbeans

You get an ExceptionInInitializerError if something goes wrong in the static initializer block.

class C
{
  static
  {
     // if something does wrong -> ExceptionInInitializerError
  }
}

Because static variables are initialized in static blocks there are a source of these errors too. An example:

class C
{
  static int v = D.foo();
}

=>

class C
{
  static int v;

  static
  {
    v = D.foo();
  }
}

So if foo() goes wild, you get a ExceptionInInitializerError.

How to grab substring before a specified character jQuery or JavaScript

You can also use shift().

var streetaddress = addy.split(',').shift();

According to MDN Web Docs:

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

Abstract Class:-Real Time Example

You should be able to cite at least one from the JDK itself. Look in the java.util.collections package. There are several abstract classes. You should fully understand interface, abstract, and concrete for Map and why Joshua Bloch wrote it that way.

What is the C# Using block and why should I use it?

If the type implements IDisposable, it automatically disposes that type.

Given:

public class SomeDisposableType : IDisposable
{
   ...implmentation details...
}

These are equivalent:

SomeDisposableType t = new SomeDisposableType();
try {
    OperateOnType(t);
}
finally {
    if (t != null) {
        ((IDisposable)t).Dispose();
    }
}
using (SomeDisposableType u = new SomeDisposableType()) {
    OperateOnType(u);
}

The second is easier to read and maintain.

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

Be aware to use constant HTTPS or HTTP for all requests. I had the same error msg: "No 'Access-Control-Allow-Origin' header is present on the requested resource."

Create table in SQLite only if it doesn't exist already

Am going to try and add value to this very good question and to build on @BrittonKerin's question in one of the comments under @David Wolever's fantastic answer. Wanted to share here because I had the same challenge as @BrittonKerin and I got something working (i.e. just want to run a piece of code only IF the table doesn't exist).

        # for completeness lets do the routine thing of connections and cursors
        conn = sqlite3.connect(db_file, timeout=1000) 

        cursor = conn.cursor() 

        # get the count of tables with the name  
        tablename = 'KABOOM' 
        cursor.execute("SELECT count(name) FROM sqlite_master WHERE type='table' AND name=? ", (tablename, ))

        print(cursor.fetchone()) # this SHOULD BE in a tuple containing count(name) integer.

        # check if the db has existing table named KABOOM
        # if the count is 1, then table exists 
        if cursor.fetchone()[0] ==1 : 
            print('Table exists. I can do my custom stuff here now.... ')
            pass
        else: 
           # then table doesn't exist. 
           custRET = myCustFunc(foo,bar) # replace this with your custom logic

Difference between Mutable objects and Immutable objects

Mutable objects have fields that can be changed, immutable objects have no fields that can be changed after the object is created.

A very simple immutable object is a object without any field. (For example a simple Comparator Implementation).

class Mutable{
  private int value;

  public Mutable(int value) {
     this.value = value;
  }

  //getter and setter for value
}

class Immutable {
  private final int value;

  public Immutable(int value) {
     this.value = value;
  }

  //only getter
}

Using jQuery's ajax method to retrieve images as a blob

You can't do this with jQuery ajax, but with native XMLHttpRequest.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if (this.readyState == 4 && this.status == 200){
        //this.response is what you're looking for
        handler(this.response);
        console.log(this.response, typeof this.response);
        var img = document.getElementById('img');
        var url = window.URL || window.webkitURL;
        img.src = url.createObjectURL(this.response);
    }
}
xhr.open('GET', 'http://jsfiddle.net/img/logo.png');
xhr.responseType = 'blob';
xhr.send();      

EDIT

So revisiting this topic, it seems it is indeed possible to do this with jQuery 3

_x000D_
_x000D_
jQuery.ajax({_x000D_
        url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
        cache:false,_x000D_
        xhr:function(){// Seems like the only way to get access to the xhr object_x000D_
            var xhr = new XMLHttpRequest();_x000D_
            xhr.responseType= 'blob'_x000D_
            return xhr;_x000D_
        },_x000D_
        success: function(data){_x000D_
            var img = document.getElementById('img');_x000D_
            var url = window.URL || window.webkitURL;_x000D_
            img.src = url.createObjectURL(data);_x000D_
        },_x000D_
        error:function(){_x000D_
            _x000D_
        }_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<img id="img" width=100%>
_x000D_
_x000D_
_x000D_

or

use xhrFields to set the responseType

_x000D_
_x000D_
    jQuery.ajax({_x000D_
            url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
            cache:false,_x000D_
            xhrFields:{_x000D_
                responseType: 'blob'_x000D_
            },_x000D_
            success: function(data){_x000D_
                var img = document.getElementById('img');_x000D_
                var url = window.URL || window.webkitURL;_x000D_
                img.src = url.createObjectURL(data);_x000D_
            },_x000D_
            error:function(){_x000D_
                _x000D_
            }_x000D_
        });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
    <img id="img" width=100%>
_x000D_
_x000D_
_x000D_

Is there a way to link someone to a YouTube Video in HD 1080p quality?

No, this is not working. And it's not just for you, in case you spent the last hour trying to find an answer for having your embeded videos open in HD.

Question: Oh, but how do you know this is not working anymore and there is no other alternative to make embeded videos open in a different quality?

Answer: Just went to Google's official documentation regarding Youtube's player parameters and there is not a single parameter that allows you to change its quality.

Also, hd=1 doesn't work either. More info here.

Apparently Youtube analyses the width and height of the user's window (or iframe) and automatically sets the quality based on this.

UPDATE:

As of 10 of April of 2018 it still doesn't work (see my comment on the accepted answer for more details).

What I can see from comments is that it MAY work sometimes, but some others it doesn't. The accepted answer states that "it measures the network speed and the screen and player sizes". So, by that, we can understand that I CANNOT force HD as YouTube will still do whatever it wants in case of low network speed/screen resolution. From my perspective everyone saying it works just have false positives on their hands and on the occasion they tested it worked for some random reason not related to the vq parameter. If it was a valid parameter, Google would document it somewhere, and vq isn't documented anywhere.

Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

They aren't the same though, are they? One is a copy, the other is a swap. Hence the function names.

My favourite is:

a = b;

Where a and b are vectors.

Check if PHP session has already started

Is this code snippet work for you?

if (!count($_SESSION)>0) {
    session_start();
}

Set 4 Space Indent in Emacs in Text Mode

You can add these lines of code to your .emacs file. It adds a hook for text mode to use insert-tab instead of indent-relative.

(custom-set-variables
 '(indent-line-function 'insert-tab)
 '(indent-tabs-mode t)
 '(tab-width 4))
(add-hook 'text-mode-hook
      (lambda() (setq indent-line-function 'insert-tab)))

I hope it helps.

How to fix "unable to open stdio.h in Turbo C" error?

Just Re install the turbo C++ from your Computer and install again in the Directory C:\TC\ Folder.

Again The Problem exists ,then change the directory from FILE>>CHANGE DIRECTORY to C:\TC\BIN\

Warning: mysqli_error() expects exactly 1 parameter, 0 given error

mysqli_error() needs you to pass the connection to the database as a parameter. Documentation here has some helpful examples:

http://php.net/manual/en/mysqli.error.php

Try altering your problem line like so and you should be in good shape:

$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error($myConnection)); 

"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

Ran into the same problem and at first defragmenting seemed to work. But it was for just a short while. Turns out the server the customer was using, was running the Express version and that has a licensing limit of about 10gb.

So even though the size was set to "unlimited", it wasn't.

Angular: How to update queryParams without changing route

In Angular 5 you can easily obtain and modify a copy of the urlTree by parsing the current url. This will include query params and fragments.

  let urlTree = this.router.parseUrl(this.router.url);
  urlTree.queryParams['newParamKey'] = 'newValue';

  this.router.navigateByUrl(urlTree); 

The "correct way" to modify a query parameter is probably with the createUrlTree like below which creates a new UrlTree from the current while letting us modify it using NavigationExtras.

import { Router } from '@angular/router';

constructor(private router: Router) { }

appendAQueryParam() {

  const urlTree = this.router.createUrlTree([], {
    queryParams: { newParamKey: 'newValue' },
    queryParamsHandling: "merge",
    preserveFragment: true });

  this.router.navigateByUrl(urlTree); 
}

In order to remove a query parameter this way you can set it to undefined or null.

Windows 10 SSH keys

I finally got it to work by running opening command line with "Run a Administrator" even though I was already admin and could create directory manually

npm check and update package if needed

There is also a "fresh" module called npm-check:

npm-check

Check for outdated, incorrect, and unused dependencies.

enter image description here

It also provides a convenient interactive way to update the dependencies with npm-check -u.

Node.js - How to send data from html to express

I'd like to expand on Obertklep's answer. In his example it is an NPM module called body-parser which is doing most of the work. Where he puts req.body.name, I believe he/she is using body-parser to get the contents of the name attribute(s) received when the form is submitted.

If you do not want to use Express, use querystring which is a built-in Node module. See the answers in the link below for an example of how to use querystring.

It might help to look at this answer, which is very similar to your quest.

Why use prefixes on member variables in C++ classes

Some responses focus on refactoring, rather than naming conventions, as the way to improve readability. I don't feel that one can replace the other.

I've known programmers who are uncomfortable with using local declarations; they prefer to place all the declarations at the top of a block (as in C), so they know where to find them. I've found that, where scoping allows for it, declaring variables where they're first used decreases the time that I spend glancing backwards to find the declarations. (This is true for me even for small functions.) That makes it easier for me to understand the code I'm looking at.

I hope it's clear enough how this relates to member naming conventions: When members are uniformly prefixed, I never have to look back at all; I know the declaration won't even be found in the source file.

I'm sure that I didn't start out preferring these styles. Yet over time, working in environments where they were used consistently, I optimized my thinking to take advantage of them. I think it's possible that many folks who currently feel uncomfortable with them would also come to prefer them, given consistent usage.

Best way to find the months between two dates

This post nails it! Use dateutil.relativedelta.

from datetime import datetime
from dateutil import relativedelta
date1 = datetime.strptime(str('2011-08-15 12:00:00'), '%Y-%m-%d %H:%M:%S')
date2 = datetime.strptime(str('2012-02-15'), '%Y-%m-%d')
r = relativedelta.relativedelta(date2, date1)
r.months

Redirect stdout to a file in Python?

you can try this too much better

import sys

class Logger(object):
    def __init__(self, filename="Default.log"):
        self.terminal = sys.stdout
        self.log = open(filename, "a")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

sys.stdout = Logger("yourlogfilename.txt")
print "Hello world !" # this is should be saved in yourlogfilename.txt

Remove duplicate values from JS array

Another method of doing this without writing much code is using the ES5 Object.keys-method:

var arrayWithDuplicates = ['a','b','c','d','a','c'],
    deduper = {};
arrayWithDuplicates.forEach(function (item) {
    deduper[item] = null;
});
var dedupedArray = Object.keys(deduper); // ["a", "b", "c", "d"]

Extracted in a function

function removeDuplicates (arr) {
    var deduper = {}
    arr.forEach(function (item) {
        deduper[item] = null;
    });
    return Object.keys(deduper);
}

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

I've been looking at this too and trying to work out how to apply timezone and DST. Here's my code.

    public long applyGMTOffsetDST(long time) {
    // Works out adjustments for timezone and daylight saving time

    Calendar mCalendar = new GregorianCalendar();  
    TimeZone mTimeZone = mCalendar.getTimeZone();  
    boolean dstBool = mTimeZone.getDefault().inDaylightTime( new Date() );
    // add an hour if DST active

    if (dstBool == true) {
        time = time + secondsPerHour;
    }
    // add offest hours
    int mGMTOffset = mTimeZone.getRawOffset();

    if (mGMTOffset > 0) {
        long offsetSeconds = secondsPerHour * mGMTOffset;
        time = time + offsetSeconds;
    }

    return time;
}

This seems to work, but is there a better way to get the actual time off the device which represents a time that is meaningful and accurate to the user?

CUDA incompatible with my gcc version

Gearoid Murphy's solution works better for me since on my distro (Ubuntu 11.10), gcc-4.4 and gcc-4.6 are in the same directory, so --compiler-bindir is no help. The only caveat is I also had to install g++-4.4 and symlink it as well:

sudo ln -s /usr/bin/gcc-4.4 /usr/local/cuda/bin/gcc
sudo ln -s /usr/bin/g++-4.4 /usr/local/cuda/bin/g++

Why shouldn't `&apos;` be used to escape single quotes?

If you need to write semantically correct mark-up, even in HTML5, you must not use &apos; to escape single quotes. Although, I can imagine you actually meant apostrophe rather then single quote.

single quotes and apostrophes are not the same, semantically, although they might look the same.

Here's one apostrophe.

Use &#39; to insert it if you need HTML4 support. (edited)

In British English, single quotes are used like this:

"He told me to 'give it a try'", I said.

Quotes come in pairs. You can use:

<p><q>He told me to <q>give it a try</q></q>, I said.<p>

to have nested quotes in a semantically correct way, deferring the substitution of the actual characters to the rendering engine. This substitution can then be affected by CSS rules, like:

q {
  quotes: '"' '"' '<' '>';
} 

An old but seemingly still relevant article about semantically correct mark-up: The Trouble With EM ’n EN (and Other Shady Characters).

(edited) This used to be:

Use ’ to insert it if you need HTML4 support.

But, as @James_pic pointed out, that is not the straight single quote, but the "Single curved quote, right".

Change image size with JavaScript

//  This one has print statement so you can see the result at every stage if     you would like.  They are not needed

function crop(image, width, height)
{
    image.width = width;
    image.height = height;
    //print ("in function", image, image.getWidth(), image.getHeight());
    return image;
}

var image = new SimpleImage("name of your image here");
//print ("original", image, image.getWidth(), image.getHeight());
//crop(image,200,300);
print ("final", image, image.getWidth(), image.getHeight());

ES6 export all values from object

I can't really recommend this solution work-around but it does function. Rather than exporting an object, you use named exports each member. In another file, import the first module's named exports into an object and export that object as default. Also export all the named exports from the first module using export * from './file1';

values/value.js

let a = 1;
let b = 2;
let c = 3;

export {a, b, c};

values/index.js

import * as values from './value';

export default values;
export * from './value';

index.js

import values, {a} from './values';

console.log(values, a); // {a: 1, b: 2, c: 3} 1

Downloading and unzipping a .zip file without writing to disk

I'd like to add my Python3 answer for completeness:

from io import BytesIO
from zipfile import ZipFile
import requests

def get_zip(file_url):
    url = requests.get(file_url)
    zipfile = ZipFile(BytesIO(url.content))
    zip_names = zipfile.namelist()
    if len(zip_names) == 1:
        file_name = zip_names.pop()
        extracted_file = zipfile.open(file_name)
        return extracted_file
    return [zipfile.open(file_name) for file_name in zip_names]

How can I programmatically generate keypress events in C#?

I've not used it, but SendKeys may do what you want.

Use SendKeys to send keystrokes and keystroke combinations to the active application. This class cannot be instantiated. To send a keystroke to a class and immediately continue with the flow of your program, use Send. To wait for any processes started by the keystroke, use SendWait.

System.Windows.Forms.SendKeys.Send("A");
System.Windows.Forms.SendKeys.Send("{ENTER}");

Microsoft has some more usage examples here.

Complex JSON nesting of objects and arrays

First, choosing a data structure(xml,json,yaml) usually includes only a readability/size problem. For example

Json is very compact, but no human being can read it easily, very hard do debug,

Xml is very large, but everyone can easily read/debug it,

Yaml is in between Xml and json.

But if you want to work with Javascript heavily and/or your software makes a lot of data transfer between browser-server, you should use Json, because it is pure javascript and very compact. But don't try to write it in a string, use libraries to generate the code you needed from an object.

Hope this helps.

Mockito: Mock private field initialization

Following code can be used to initialize mapper in REST client mock. The mapper field is private and needs to be set during unit test setup.

import org.mockito.internal.util.reflection.FieldSetter;

new FieldSetter(client, Client.class.getDeclaredField("mapper")).set(new Mapper());

Git merge is not possible because I have unmerged files

It might be the Unmerged paths that cause

error: Merging is not possible because you have unmerged files.

If so, try:

git status

if it says

You have unmerged paths.

do as suggested: either resolve conflicts and then commit or abort the merge entirely with

git merge --abort

You might also see files listed under Unmerged paths, which you can resolve by doing

git rm <file>

Is <img> element block level or inline level?

For almost all purposes think of them as an inline element with a width set. Basically you are free to dictate how you would like images to display using CSS. I generally set a few image classes like so:

img.center {display:block;margin:0 auto;}

img.left {float:left;margin-right:10px;}

img.right  {float:right;margin-left:10px;}

img.border  {border:1px solid #333;}

JAVA How to remove trailing zeros from a double

Use a DecimalFormat object with a format string of "0.#".

What is the meaning of curly braces?

"Curly Braces" are used in Python to define a dictionary. A dictionary is a data structure that maps one value to another - kind of like how an English dictionary maps a word to its definition.

Python:

dict = {
    "a" : "Apple",
    "b" : "Banana",
}

They are also used to format strings, instead of the old C style using %, like:

ds = ['a', 'b', 'c', 'd']
x = ['has_{} 1'.format(d) for d in ds]

print x

['has_a 1', 'has_b 1', 'has_c 1', 'has_d 1']

They are not used to denote code blocks as they are in many "C-like" languages.

C:

if (condition) {
    // do this
}

Required attribute on multiple checkboxes with the same name?

To provide another approach similar to the answer by @IvanCollantes. It works by additionally filtering the required checkboxes by name. I also simplified the code a bit and checks for a default checked checkbox.

_x000D_
_x000D_
jQuery(function($) {_x000D_
  var requiredCheckboxes = $(':checkbox[required]');_x000D_
  requiredCheckboxes.on('change', function(e) {_x000D_
    var checkboxGroup = requiredCheckboxes.filter('[name="' + $(this).attr('name') + '"]');_x000D_
    var isChecked = checkboxGroup.is(':checked');_x000D_
    checkboxGroup.prop('required', !isChecked);_x000D_
  });_x000D_
  requiredCheckboxes.trigger('change');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<form target="_blank">_x000D_
  <p>_x000D_
    At least one checkbox from each group is required..._x000D_
  </p>_x000D_
  <fieldset>_x000D_
    <legend>Checkboxes Group test</legend>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test[]" value="1" checked="checked" required="required">test-1_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test[]" value="2" required="required">test-2_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test[]" value="3" required="required">test-3_x000D_
    </label>_x000D_
  </fieldset>_x000D_
  <br>_x000D_
  <fieldset>_x000D_
    <legend>Checkboxes Group test2</legend>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test2[]" value="1" required="required">test2-1_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test2[]" value="2" required="required">test2-2_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test2[]" value="3" required="required">test2-3_x000D_
    </label>_x000D_
  </fieldset>_x000D_
  <hr>_x000D_
  <button type="submit" value="submit">Submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Git commit with no commit message

I found the simplest solution:

git commit -am'save'

That's all,you will work around git commit message stuff.

you can even save that commend to a bash or other stuff to make it more simple.

Our team members always write those messages,but almost no one will see those message again.

Commit message is a time-kill stuff at least in our team,so we ignore it.

how to pass value from one php page to another using session

Use something like this:

page1.php

<?php
session_start();
$_SESSION['myValue']=3; // You can set the value however you like.
?>

Any other PHP page:

<?php
session_start();
echo $_SESSION['myValue'];
?>

A few notes to keep in mind though: You need to call session_start() BEFORE any output, HTML, echos - even whitespace.

You can keep changing the value in the session - but it will only be able to be used after the first page - meaning if you set it in page 1, you will not be able to use it until you get to another page or refresh the page.

The setting of the variable itself can be done in one of a number of ways:

$_SESSION['myValue']=1;
$_SESSION['myValue']=$var;
$_SESSION['myValue']=$_GET['YourFormElement'];

And if you want to check if the variable is set before getting a potential error, use something like this:

if(!empty($_SESSION['myValue'])
{
    echo $_SESSION['myValue'];
}
else
{
    echo "Session not set yet.";
}

The difference between the 'Local System' account and the 'Network Service' account?

Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

First the actual accounts:

  • LocalService account (preferred)

    A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

    • Name: NT AUTHORITY\LocalService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the LocalService user account
    • has minimal privileges on the local computer
    • presents anonymous credentials on the network
    • SID: S-1-5-19
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)

     

  • NetworkService account

    Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

    • NT AUTHORITY\NetworkService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the NetworkService user account
    • has minimal privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers
    • SID: S-1-5-20
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
    • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog

     

  • LocalSystem account (dangerous, don't use!)

    Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

    • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
    • the account has no password (any password information you provide is ignored)
    • SID: S-1-5-18
    • does not have any profile of its own (HKCU represents the default user)
    • has extensive privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers

     

Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).


In Windows Server 2003 you cannot run a scheduled task as

  • NT_AUTHORITY\LocalService (aka the Local Service account), or
  • NT AUTHORITY\NetworkService (aka the Network Service account).

That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

enter image description here

How to set commands output as a variable in a batch file

FOR /F "tokens=* USEBACKQ" %%F IN (`command`) DO (
SET var=%%F
)
ECHO %var%

I always use the USEBACKQ so that if you have a string to insert or a long file name, you can use your double quotes without screwing up the command.

Now if your output will contain multiple lines, you can do this

SETLOCAL ENABLEDELAYEDEXPANSION
SET count=1
FOR /F "tokens=* USEBACKQ" %%F IN (`command`) DO (
  SET var!count!=%%F
  SET /a count=!count!+1
)
ECHO %var1%
ECHO %var2%
ECHO %var3%
ENDLOCAL

git undo all uncommitted or unsaved changes

I'm using source tree.... You can do revert all uncommitted changes with 2 easy steps:

1) just need to reset the workspace file status

enter image description here 2) select all unstage files (command +a), right click and select remove

enter image description here

It's that simple :D

What is the LDF file in SQL Server?

LDF holds the transaction log. If you set your backups correctly - it will be small. It it grows - you have a very common problem of setting database recovery mode to FULL and then forgetting to backup the transaction log (LDF file). Let me explain how to fix it.

  1. If your business can afford to lose a little data between backups, just set the database recovery mode to SIMPLE, then forget about LDF - it will be small. This is the recommended solution for most of the cases.
  2. If you have to be able to restore to the exact point in time - use FULL recovery mode. In this case you have to take regular Transaction Log backups. The simplest way to do it is to use a tool like SqlBackupAndFTP (disclosure - I am a developer). The log file will be truncated at this time and would not grow beyond certain limits.

Some would suggest to use SHRINKFILE to trim you log. Note that this is OK only as an exception. If you do it regularly, it defeats the purpose of FULL recovery model: first you go into trouble of saving every single change in the log, then you just dump it. Set recovery mode to SIMPLE instead.

Saving a Excel File into .txt format without quotes

I just spent the better part of an afternoon on this

There are two common ways of writing to a file, the first being a direct file access "write" statement. This adds the quotes.

The second is the "ActiveWorkbook.SaveAs" or "ActiveWorksheet.SaveAs" which both have the really bad side effect of changing the filename of the active workbook.

The solution here is a hybrid of a few solutions I found online. It basically does this: 1) Copy selected cells to a new worksheet 2) Iterate through each cell one at a time and "print" it to the open file 3) Delete the temporary worksheet.

The function works on the selected cells and takes in a string for a filename or prompts for a filename.

Function SaveFile(myFolder As String) As String
tempSheetName = "fileWrite_temp"
SaveFile = "False"

Dim FilePath As String
Dim CellData As String
Dim LastCol As Long
Dim LastRow As Long

Set myRange = Selection
'myRange.Select
Selection.Copy

'Ask user for folder to save text file to.
If myFolder = "prompt" Then
    myFolder = Application.GetSaveAsFilename(fileFilter:="XML Files (*.xml), *.xml, All Files (*), *")
End If
If myFolder = "False" Then
    End
End If

Open myFolder For Output As #2

'This temporarily adds a sheet named "Test."
Sheets.Add.Name = tempSheetName
Sheets(tempSheetName).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

LastCol = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Column
LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

For i = 1 To LastRow
    For j = 1 To LastCol
        CellData = CellData + Trim(ActiveCell(i, j).Value) + "   "
    Next j

    Print #2, CellData; " "
    CellData = ""

Next i

Close #2

'Remove temporary sheet.
Application.ScreenUpdating = False
Application.DisplayAlerts = False
ActiveWindow.SelectedSheets.Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
'Indicate save action.
MsgBox "Text File Saved to: " & vbNewLine & myFolder
SaveFile = myFolder

End Function

Hibernate Delete query

To understand this peculiar behavior of hibernate, it is important to understand a few hibernate concepts -

Hibernate Object States

Transient - An object is in transient status if it has been instantiated and is still not associated with a Hibernate session.

Persistent - A persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session.

Detached - A detached instance is an object that has been persistent, but its Session has been closed.

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html#objectstate-overview

Transaction Write-Behind

The next thing to understand is 'Transaction Write behind'. When objects attached to a hibernate session are modified they are not immediately propagated to the database. Hibernate does this for at least two different reasons.

  • To perform batch inserts and updates.
  • To propagate only the last change. If an object is updated more than once, it still fires only one update statement.

http://learningviacode.blogspot.com/2012/02/write-behind-technique-in-hibernate.html

First Level Cache

Hibernate has something called 'First Level Cache'. Whenever you pass an object to save(), update() or saveOrUpdate(), and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session. This is where it tracks changes to various objects.

Hibernate Intercepters and Object Lifecycle Listeners -

The Interceptor interface and listener callbacks from the session to the application, allow the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded. http://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/listeners.html#d0e3069


This section Updated

Cascading

Hibernate allows applications to define cascade relationships between associations. For example, 'cascade-delete' from parent to child association will result in deletion of all children when a parent is deleted.

So, why are these important.

To be able to do transaction write-behind, to be able to track multiple changes to objects (object graphs) and to be able to execute lifecycle callbacks hibernate needs to know whether the object is transient/detached and it needs to have the object in it's first level cache before it makes any changes to the underlying object and associated relationships.

That's why hibernate (sometimes) issues a 'SELECT' statement to load the object (if it's not already loaded) in to it's first level cache before it makes changes to it.

Why does hibernate issue the 'SELECT' statement only sometimes?

Hibernate issues a 'SELECT' statement to determine what state the object is in. If the select statement returns an object, the object is in detached state and if it does not return an object, the object is in transient state.

Coming to your scenario -

Delete - The 'Delete' issued a SELECT statement because hibernate needs to know if the object exists in the database or not. If the object exists in the database, hibernate considers it as detached and then re-attches it to the session and processes delete lifecycle.

Update - Since you are explicitly calling 'Update' instead of 'SaveOrUpdate', hibernate blindly assumes that the object is in detached state, re-attaches the given object to the session first level cache and processes the update lifecycle. If it turns out that the object does not exist in the database contrary to hibernate's assumption, an exception is thrown when session flushes.

SaveOrUpdate - If you call 'SaveOrUpdate', hibernate has to determine the state of the object, so it uses a SELECT statement to determine if the object is in Transient/Detached state. If the object is in transient state, it processes the 'insert' lifecycle and if the object is in detached state, it processes the 'Update' lifecycle.

function declaration isn't a prototype

In C int foo() and int foo(void) are different functions. int foo() accepts an arbitrary number of arguments, while int foo(void) accepts 0 arguments. In C++ they mean the same thing. I suggest that you use void consistently when you mean no arguments.

If you have a variable a, extern int a; is a way to tell the compiler that a is a symbol that might be present in a different translation unit (C compiler speak for source file), don't resolve it until link time. On the other hand, symbols which are function names are anyway resolved at link time. The meaning of a storage class specifier on a function (extern, static) only affects its visibility and extern is the default, so extern is actually unnecessary.

I suggest removing the extern, it is extraneous and is usually omitted.

Oracle query to identify columns having special characters

Compare the length using lengthB and length function in oracle.

SELECT * FROM test WHERE length(sampletext) <> lengthb(sampletext)

Attach event to dynamic elements in javascript

I have found the solution posted by jillykate works, but only if the target element is the most nested. If this is not the case, this can be rectified by iterating over the parents, i.e.

function on_window_click(event)
{
    let e = event.target;

    while (e !== null)
    {
        // --- Handle clicks here, e.g. ---
        if (e.getAttribute(`data-say_hello`))
        {
            console.log("Hello, world!");
        }

        e = e.parentElement;
    }
}

window.addEventListener("click", on_window_click);

Also note we can handle events by any attribute, or attach our listener at any level. The code above uses a custom attribute and window. I doubt there is any pragmatic difference between the various methods.

subquery in FROM must have an alias

add an ALIAS on the subquery,

SELECT  COUNT(made_only_recharge) AS made_only_recharge
FROM    
    (
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER = '0130'
        EXCEPT
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER != '0130'
    ) AS derivedTable                           -- <<== HERE

How to get character for a given ascii value

I believe a simple cast can work

int ascii = (int) "A"

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

We had this issue whereby a website that was accessing our API was getting the “The underlying connection was closed: An unexpected error occurred on a send.” message.

Their code was a mix of .NET 3.x and 2.2, which as I understand it means they are using TLS 1.0.

The answer below can help you diagnose the issue by enabling TLS 1.0, SSL 2 and SSL3, but to be very clear, you do not want to do that long-term as all three of those protocols are regarded as insecure and should no longer be used:

To get our IIS to respond to their API calls we had to add registry settings on the IIS's server to explicitly enable versions of TLS - NOTE: You have to restart the Windows server (not just the IIS service) after making these changes:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.0\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.0\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.1\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.1\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.2\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.2\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

If that doesn't do it, you could also experiment with adding the entry for SSL 2.0:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

To be clear, this is not a nice solution, and the right solution is to get the caller to use TLS 1.2, but the above can help diagnose that this is the issue.

You can speed adding those reg entries up with this powershell script:

$ProtocolList       = @("SSL 2.0","SSL 3.0","TLS 1.0", "TLS 1.1", "TLS 1.2")
$ProtocolSubKeyList = @("Client", "Server")
$DisabledByDefault = "DisabledByDefault"
$Enabled = "Enabled"
$registryPath = "HKLM:\\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\"

foreach($Protocol in $ProtocolList)
{
    Write-Host " In 1st For loop"
        foreach($key in $ProtocolSubKeyList)
        {         
            $currentRegPath = $registryPath + $Protocol + "\" + $key
            Write-Host " Current Registry Path $currentRegPath"
            if(!(Test-Path $currentRegPath))
            {
                Write-Host "creating the registry"
                    New-Item -Path $currentRegPath -Force | out-Null             
            }
            Write-Host "Adding protocol"
                New-ItemProperty -Path $currentRegPath -Name $DisabledByDefault -Value "0" -PropertyType DWORD -Force | Out-Null
                New-ItemProperty -Path $currentRegPath -Name $Enabled -Value "1" -PropertyType DWORD -Force | Out-Null    
    }
}
 
Exit 0

That's a modified version of the script from the Microsoft help page for Set up TLS for VMM. This basics.net article was the page that originally gave me the idea to look at these settings.

Uncaught ReferenceError: jQuery is not defined

you need to put it after wp_head(); Because that loads your jQuery and you need to load jQuery first and then your js

How to download a file from a website in C#

Try this example:

public void TheDownload(string path)
{
  System.IO.FileInfo toDownload = new System.IO.FileInfo(HttpContext.Current.Server.MapPath(path));

  HttpContext.Current.Response.Clear();
  HttpContext.Current.Response.AddHeader("Content-Disposition",
             "attachment; filename=" + toDownload.Name);
  HttpContext.Current.Response.AddHeader("Content-Length",
             toDownload.Length.ToString());
  HttpContext.Current.Response.ContentType = "application/octet-stream";
  HttpContext.Current.Response.WriteFile(patch);
  HttpContext.Current.Response.End();
} 

The implementation is done in the follows:

TheDownload("@"c:\Temporal\Test.txt"");

Source: http://www.systemdeveloper.info/2014/03/force-downloading-file-from-c.html

Catching exceptions from Guzzle

Old question, but Guzzle adds the response within the exception object. So a simple try-catch on GuzzleHttp\Exception\ClientException and then using getResponse on that exception to see what 400-level error and continuing from there.

Python: Number of rows affected by cursor.execute("SELECT ...)

Try using fetchone:

cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
result=cursor.fetchone()

result will hold a tuple with one element, the value of COUNT(*). So to find the number of rows:

number_of_rows=result[0]

Or, if you'd rather do it in one fell swoop:

cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
(number_of_rows,)=cursor.fetchone()

PS. It's also good practice to use parametrized arguments whenever possible, because it can automatically quote arguments for you when needed, and protect against sql injection.

The correct syntax for parametrized arguments depends on your python/database adapter (e.g. mysqldb, psycopg2 or sqlite3). It would look something like

cursor.execute("SELECT COUNT(*) from result where server_state= %s AND name LIKE %s",[2,digest+"_"+charset+"_%"])
(number_of_rows,)=cursor.fetchone()

What's the difference between 'int?' and 'int' in C#?

int? is shorthand for Nullable<int>.

This may be the post you were looking for.

Count words in a string method?

public class TestStringCount {

  public static void main(String[] args) {
    int count=0;
    boolean word= false;
    String str = "how ma ny wo rds are th ere in th is sente nce";
    char[] ch = str.toCharArray();
    for(int i =0;i<ch.length;i++){
        if(!(ch[i]==' ')){
            for(int j=i;j<ch.length;j++,i++){
                if(!(ch[j]==' ')){
                    word= true;
                    if(j==ch.length-1){
                        count++;
                    }
                    continue;
                }
                else{
                    if(word){
                        count++;
                    }
                    word = false;
                }
            }
        }
        else{
            continue;
        }
    }
    System.out.println("there are "+(count)+" words");      
    }
}

What's the Use of '\r' escape sequence?

To answer the part of your question,

what is the use of \r?

Many Internet protocols, such as FTP, HTTP and SMTP, are specified in terms of lines delimited by carriage return and newline. So, for example, when sending an email, you might have code such as:

fprintf(socket, "RCPT TO: %s\r\n", recipients);

Or, when a FTP server replies with a permission-denied error:

fprintf(client, "550 Permission denied\r\n");

Escape invalid XML characters in C#

string XMLWriteStringWithoutIllegalCharacters(string UnfilteredString)
{
    if (UnfilteredString == null)
        return string.Empty;

    return XmlConvert.EncodeName(UnfilteredString);
}

string XMLReadStringWithoutIllegalCharacters(string FilteredString)
{
    if (UnfilteredString == null)
        return string.Empty;

    return XmlConvert.DecodeName(UnfilteredString);
}

This simple method replace the invalid characters with the same value but accepted in the XML context.


To write string use XMLWriteStringWithoutIllegalCharacters(string UnfilteredString).
To read string use XMLReadStringWithoutIllegalCharacters(string FilteredString).

Oracle: how to add minutes to a timestamp?

Can we not use this

SELECT date_and_time + INTERVAL '20:00' MINUTE TO SECOND FROM dual;

I am new to this domain.

.do extension in web pages?

Using apache's rewrite_module can change your script extensions. Give this thread a good read.

Amazon Interview Question: Design an OO parking lot

you would need a parking lot, that holds a multi-dimensional array (specified in the constructor) of a type "space". The parking lot can keep track of how many spaces are taken via calls to functions that fill and empty spaces.Space can hold an enumerated type that tells what kind of space it is. Space also has a method taken(). for the valet parking, just find the first space thats open and put the car there. You will also need a Car object to put in the space, that holds whether it is a handicapped, compact, or regular vehicle.


class ParkingLot
{
    Space[][] spaces;

    ParkingLot(wide, long); // constructor

    FindOpenSpace(TypeOfCar); // find first open space where type matches
}

enum TypeOfSpace = {compact, handicapped, regular };
enum TypeOfCar = {compact, handicapped, regular };

class Space
{
    TypeOfSpace type;
    bool empty;
    // gets and sets here
    // make sure car type
}

class car
{
    TypeOfCar type;
}

'git' is not recognized as an internal or external command

Yo! I had lots of problems with this. It seems that Github brings its own console which you need to look for in your drive. I managed to finally run it by doing the following:

  1. Press Start.
  2. Search for "GitHub" (without quotes)
  3. Right click on "GitHub" and select "Open File Location"

*This shall open *

C:\Users\UserName\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\GitHub, Inc

Where username is your PC's username

  1. Look for a program called "Git Shell". Double click on it.

This will open a PowerShell command prompt. Then you can run your git commands normally on it.

React.createElement: type is invalid -- expected a string

In my case, I have added the same custom component as a prop instead of actual prob

   import AddAddress from '../../components/Manager/AddAddress';
    
    class Add extends React.PureComponent {
      render() {
        const {
          history,
          addressFormData,
          formErrors,
          addressChange,
          addAddress,
          isDefault,
          defaultChange
        } = this.props;
    

Error:

    return (
        <AddAddress
          addressFormData={addressFormData}
          formErrors={formErrors}
          addressChange={addressChange}
          addAddress={AddAddress} // here i have used the Component name as probs in same component itself instead of prob
          isDefault={isDefault}
          defaultChange={defaultChange}
        />
      </SubPage>

Solution:

return (
    <AddAddress
      addressFormData={addressFormData}
      formErrors={formErrors}
      addressChange={addressChange}
      addAddress={addAddress} // removed the component name and give prob name
      isDefault={isDefault}
      defaultChange={defaultChange}
    />
  </SubPage>

Best way to clear a PHP array's values

Sadly I can't answer the other questions, don't have enough reputation, but I need to point something out that was VERY important for me, and I think it will help other people too.

Unsetting the variable is a nice way, unless you need the reference of the original array!

To make clear what I mean: If you have a function wich uses the reference of the array, for example a sorting function like

function special_sort_my_array(&$array)
{
    $temporary_list = create_assoziative_special_list_out_of_array($array);

    sort_my_list($temporary_list);

    unset($array);
    foreach($temporary_list as $k => $v)
    {
        $array[$k] = $v;
    }
}

it is not working! Be careful here, unset deletes the reference, so the variable $array is created again and filled correctly, but the values are not accessable from outside the function.

So if you have references, you need to use $array = array() instead of unset, even if it is less clean and understandable.

How to add favicon.ico in ASP.NET site

/favicon.ico

might do the trick
I have tried this on my sample website

<link rel="shortcut icon" type="image/x-icon" href="~/ows.ico" />

Try this one in your site put the link in MasterPage,It works :)

<link rel="shortcut icon" type="image/x-icon" href="~/favicon.ico" />


I have tested in ,
FireFox.
enter image description here
Chrome.
enter image description here
Opera.
enter image description here

Some troubleshoots:
1. Check if your favicon is accessible (correct url) ,goto view source and click on the favicon link
2. Full refresh your browser by Ctrl+F5 every time you make changes.
3. Try searching from SO you may find your related problem here.


Some Links to help you out:
Serving favicon.ico in ASP.NET MVC
Favicon Not Showing
Why is favicon not visible

How to create a new branch from a tag?

The situation becomes a little bit problematic if we want to create a branch from a tag with the same name.

In this, and in similar scenarios, the important thing is to know: branches and tags are actually single-line text files in .git/refs directory, and we can reference them explicitly using their pathes below .git. Branches are called here "heads", to make our life more simple.

Thus, refs/heads/master is the real, explicit name of the master branch. And refs/tags/cica is the exact name of the tag named cica.

The correct command to create a branch named cica from the tag named cica is:

git branch cica refs/tags/cica

How does the class_weight parameter in scikit-learn work?

First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class. I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level) that you are interested in.

For how class_weight works: It penalizes mistakes in samples of class[i] with class_weight[i] instead of 1. So higher class-weight means you want to put more emphasis on a class. From what you say it seems class 0 is 19 times more frequent than class 1. So you should increase the class_weight of class 1 relative to class 0, say {0:.1, 1:.9}. If the class_weight doesn't sum to 1, it will basically change the regularization parameter.

For how class_weight="auto" works, you can have a look at this discussion. In the dev version you can use class_weight="balanced", which is easier to understand: it basically means replicating the smaller class until you have as many samples as in the larger one, but in an implicit way.

java.lang.ClassNotFoundException: HttpServletRequest

So the problem is connected with the metadata errors of elcipse. Go to the metadata folder where this configuration is saved. For me one of the erorrs was that:

SEVERE: Error starting static Resources java.lang.IllegalArgumentException: Document base C:\Users\Cannibal\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\FoodQuantityService does not exist or is not a readable directory

So go there is in the workspace of your eclipse it is different for all and delete all its content . My services was named FoodQuantityService so I deleted all files in org.eclipse.wst.server.core but before that delete your server configuration from Eclipse

Delete current server configuration

Then create new configuration File->New->Other->Server select Tomcat and then projects which you want to be published. Start the server and everything will be ok.

Uncaught TypeError: Cannot read property 'length' of undefined

"ProjectID" JSON data format problem Remove "ProjectID": This value collection objeckt key value

 { * * "ProjectID" * * : {
            "name": "ProjectID",
            "value": "16,36,8,7",
            "group": "Genel",
            "editor": {
                "type": "combobox",
                "options": {
                    "url": "..\/jsonEntityVarServices\/?id=6&task=7",
                    "valueField": "value",
                    "textField": "text",
                    "multiple": "true"
                }
            },
            "id": "14",
            "entityVarID": "16",
            "EVarMemID": "47"
        }
    }

Component is not part of any NgModule or the module has not been imported into your module

I ran into this same issue and none of what I was seeing here was working. If you are listing your Component in the app-routing.module issue you may have run into the same problem I was having.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { TopbarComponent } from './topbar/topbar.component';
import { FooterbarComponent } from './footerbar/footerbar.component';
import { MRDBGlobalConstants } from './shared/mrdb.global.constants';
import {AppRoutingModule} from './app.routing';
import {HomeModule} from './Home/home.module';
// import HomeComponent here

@NgModule({
  declarations: [
    AppComponent,
    FooterbarComponent,
    TopbarComponent,
    NavbarComponent,
    // add HomeComponent here
  ],
  imports: [
    BrowserModule,
    HttpModule,
    AppRoutingModule,
    HomeModule  // remove this

  ],
  providers: [MRDBGlobalConstants],
  bootstrap: [AppComponent]
})
export class AppModule { }

home/index.ts

export * from './';

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './components';

const routes: Routes = [
    { path: 'app/home', component: HomeComponent },
    { path: '', redirectTo: 'app/home', pathMatch: 'full' },
    { path: '**', redirectTo: 'app/home' }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

home/home.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// import { HomeComponent } from './home.component'; This would cause app to break
import { HomeComponent } from './';
@NgModule({
  imports: [
    CommonModule
  ],
  exports: [HomeComponent],
  declarations: [HomeComponent]
})
export class HomeModule { }

I won't claim to understand exactly why this is the case, but when using indexing to export components (and I would assume the same for services, etc.), when referencing the same component in separate modules you need to import them from the same file, in this case the index, in order to avoid this issue.

psql - save results of command to a file

Use the below query to store the result in a CSV file

\copy (your query) to 'file path' csv header;

Example

\copy (select name,date_order from purchase_order) to '/home/ankit/Desktop/result.csv' cvs header;

Hope this helps you.

Python string.replace regular expression

As a summary

import sys
import re

f = sys.argv[1]
find = sys.argv[2]
replace = sys.argv[3]
with open (f, "r") as myfile:
     s=myfile.read()
ret = re.sub(find,replace, s)   # <<< This is where the magic happens
print ret

jquery background-color change on focus and blur

#FFFFEEE is not a correct color code. Try with #FFFFEE instead.

How does OkHttp get Json string?

try {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
        .url(urls[0])
        .build();
    Response responses = null;

    try {
        responses = client.newCall(request).execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
    String jsonData = responses.body().string();
    JSONObject Jobject = new JSONObject(jsonData);
    JSONArray Jarray = Jobject.getJSONArray("employees");

    for (int i = 0; i < Jarray.length(); i++) {
        JSONObject object     = Jarray.getJSONObject(i);
    }
}

Example add to your columns:

JCol employees  = new employees();
colums.Setid(object.getInt("firstName"));
columnlist.add(lastName);           

How to get a tab character?

As mentioned, for efficiency reasons sequential spaces are consolidated into one space the browser actually displays. Remember what the ML in HTML stand for. It's a Mark-up Language, designed to control how text is displayed.. not whitespace :p

Still, you can pretend the browser respects tabs since all the TAB does is prepend 4 spaces, and that's easy with CSS. either in line like ...

 <div style="padding-left:4.00em;">Indenented text </div>

Or as a regular class in a style sheet

.tabbed {padding-left:4.00em;}

Then the HTML might look like

<p>regular paragraph regular paragraph regular paragraph</p>
<p class="tabbed">Indented text Indented text Indented text</p>
<p>regular paragraph regular paragraph regular paragraph</p>

node.js - how to write an array to file

To do what you want, using the fs.createWriteStream(path[, options]) function in a ES6 way:

const fs = require('fs');
const writeStream = fs.createWriteStream('file.txt');
const pathName = writeStream.path;
 
let array = ['1','2','3','4','5','6','7'];
  
// write each value of the array on the file breaking line
array.forEach(value => writeStream.write(`${value}\n`));

// the finish event is emitted when all data has been flushed from the stream
writeStream.on('finish', () => {
   console.log(`wrote all the array data to file ${pathName}`);
});

// handle the errors on the write process
writeStream.on('error', (err) => {
    console.error(`There is an error writing the file ${pathName} => ${err}`)
});

// close the stream
writeStream.end();

How to filter object array based on attributes?

var filterHome = homes.filter(home =>
  return (home.price <= 999 &&
         home.num_of_baths >= 2.5 &&
         home.num_of_beds >=2 &&
         home.sqft >= 998));
console.log(filterHome);

You can use this lambda function. More detail can be found here since we are filtering the data based on you have condition which return true or false and it will collect the data in different array so your actual array will be not modified.

@JGreig Please look into it.

PHP: Get the key from an array in a foreach loop

you need nested foreach loops

foreach($samplearr as $key => $item){
   echo $key;
    foreach($item as $detail){
       echo $detail['value1'] . " " . $detail['value2']
     }
 }

How can I count all the lines of code in a directory recursively?

I wanted to check on multiple file types and was to lazy to calculate the total by hand. So I use this now to get the total in one go.

find . -name '*.js' -or -name '*.php' | xargs wc -l | grep 'total'  | awk '{ SUM += $1; print $1} END { print "Total text lines in PHP and JS",SUM }'

79351
15318
Total text lines in PHP and JS 94669

This allows you to chain multiple extension types you wish to filter on. Just add them in the -name '*.js' -or -name '*.php' part, and possibly modify the otuput message to your liking.

How to force cp to overwrite without confirmation

As some of the other answers have stated, you probably use an alias somewhere which maps cp to cp -i or something similar. You can run a command without any aliases by preceding it with a backslash. In your case, try

\cp -r /zzz/zzz/* /xxx/xxx

The backslash will temporarily disable any aliases you have called cp.

JQuery wait for page to finish loading before starting the slideshow?

If you pass jQuery a function, it will not run until the page has loaded:

<script type="text/javascript">
$(function() {
    //your header rotation code goes here
});
</script>

case-insensitive matching in xpath?

matches() is an XPATH 2.0 function that allows for case-insensitive regex matching.

One of the flags is i for case-insensitive matching.

The following XPATH using the matches() function with the case-insensitive flag:

//CD[matches(@title,'empire burlesque','i')]

What is the naming convention in Python for variable and function names?

Most python people prefer underscores, but even I am using python since more than 5 years right now, I still do not like them. They just look ugly to me, but maybe that's all the Java in my head.

I simply like CamelCase better since it fits better with the way classes are named, It feels more logical to have SomeClass.doSomething() than SomeClass.do_something(). If you look around in the global module index in python, you will find both, which is due to the fact that it's a collection of libraries from various sources that grew overtime and not something that was developed by one company like Sun with strict coding rules. I would say the bottom line is: Use whatever you like better, it's just a question of personal taste.

SQL sum with condition

Try this instead:

SUM(CASE WHEN ValueDate > @startMonthDate THEN cash ELSE 0 END)

Explanation

Your CASE expression has incorrect syntax. It seems you are confusing the simple CASE expression syntax with the searched CASE expression syntax. See the documentation for CASE:

The CASE expression has two formats:

  • The simple CASE expression compares an expression to a set of simple expressions to determine the result.
  • The searched CASE expression evaluates a set of Boolean expressions to determine the result.

You want the searched CASE expression syntax:

CASE
     WHEN Boolean_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

As a side note, if performance is an issue you may find that this expression runs more quickly if you rewrite using a JOIN and GROUP BY instead of using a dependent subquery.

get next and previous day with PHP

Requirement: PHP 5 >= 5.2.0

You should make use of the DateTime and DateInterval classes in Php, and things will turn to be very easy and readable.

Example: Lets get the previous day.

// always make sure to have set your default timezone
date_default_timezone_set('Europe/Berlin');

// create DateTime instance, holding the current datetime
$datetime = new DateTime();

// create one day interval
$interval = new DateInterval('P1D');

// modify the DateTime instance
$datetime->sub($interval);

// display the result, or print_r($datetime); for more insight 
echo $datetime->format('Y-m-d');


/** 
* TIP:
* if you dont want to change the default timezone, use
* use the DateTimeZone class instead.
*
* $myTimezone = new DateTimeZone('Europe/Berlin');
* $datetime->setTimezone($myTimezone); 
*
* or just include it inside the constructor 
* in this form new DateTime("now",   $myTimezone);
*/

References: Modern PHP, New Features and Good Practices By Josh Lockhart

Format a Go string without printing?

In your case, you need to use Sprintf() for format string.

func Sprintf(format string, a ...interface{}) string

Sprintf formats according to a format specifier and returns the resulting string.

s := fmt.Sprintf("Good Morning, This is %s and I'm living here from last %d years ", "John", 20)

Your output will be :

Good Morning, This is John and I'm living here from last 20 years.

REST API - Bulk Create or Update in single request

In a project I worked at we solved this problem by implement something we called 'Batch' requests. We defined a path /batch where we accepted json in the following format:

[  
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 1,
         binder: 1
      }
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 5,
         binder: 8
      }
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 6,
         binder: 3
      }
   },
]

The response have the status code 207 (Multi-Status) and looks like this:

[  
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 1,
         binder: 1
      }
      status: 200
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         error: {
            msg: 'A document with doc_number 5 already exists'
            ...
         }
      },
      status: 409
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 6,
         binder: 3
      },
      status: 200
   },
]

You could also add support for headers in this structure. We implemented something that proved useful which was variables to use between requests in a batch, meaning we can use the response from one request as input to another.

Facebook and Google have similar implementations:
https://developers.google.com/gmail/api/guides/batch
https://developers.facebook.com/docs/graph-api/making-multiple-requests

When you want to create or update a resource with the same call I would use either POST or PUT depending on the case. If the document already exist, do you want the entire document to be:

  1. Replaced by the document you send in (i.e. missing properties in request will be removed and already existing overwritten)?
  2. Merged with the document you send in (i.e. missing properties in request will not be removed and already existing properties will be overwritten)?

In case you want the behavior from alternative 1 you should use a POST and in case you want the behavior from alternative 2 you should use PUT.

http://restcookbook.com/HTTP%20Methods/put-vs-post/

As people already suggested you could also go for PATCH, but I prefer to keep API's simple and not use extra verbs if they are not needed.

SQL Plus change current directory

I don't think you can!

/home/export/user1 $ sqlplus / 
> @script1.sql
> HOST CD /home/export/user2
> @script2.sql

script2.sql has to be in /home/export/user1.

You either use the full path, or exit the script and start sqlplus again from the right directory.

#!/bin/bash
oraenv .
cd /home/export/user1
sqlplus / @script1.sql
cd /home/export/user2
sqlplus / @script2.sql

(something like that - doing this from memory!)

Multiple cases in switch statement

One lesser known facet of switch in C# is that it relies on the operator= and since it can be overriden you could have something like this:


string s = foo();

switch (s) {
  case "abc": /*...*/ break;
  case "def": /*...*/ break;
}

python pip on Windows - command 'cl.exe' failed

This is easily the simplest solution. For those who don't know how to do this:

  1. Install the C++ compiler https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019

  2. Go to the installation folder (In my case it is): C:\Program Files (x86)\Microsoft Visual C++ Build Tools

  3. Open Visual C++ 2015 x86 x64 Cross Build Tools Command Prompt

  4. Type: pip install package_name

Differences between Ant and Maven

Maven acts as both a dependency management tool - it can be used to retrieve jars from a central repository or from a repository you set up - and as a declarative build tool. The difference between a "declarative" build tool and a more traditional one like ant or make is you configure what needs to get done, not how it gets done. For example, you can say in a maven script that a project should be packaged as a WAR file, and maven knows how to handle that.

Maven relies on conventions about how project directories are laid out in order to achieve its "declarativeness." For example, it has a convention for where to put your main code, where to put your web.xml, your unit tests, and so on, but also gives the ability to change them if you need to.

You should also keep in mind that there is a plugin for running ant commands from within maven:

http://maven.apache.org/plugins/maven-ant-plugin/

Also, maven's archetypes make getting started with a project really fast. For example, there is a Wicket archetype, which provides a maven command you run to get a whole, ready-to-run hello world-type project.

https://wicket.apache.org/start/quickstart.html

How to print formatted BigDecimal values?

 BigDecimal pi = new BigDecimal(3.14);
 BigDecimal pi4 = new BigDecimal(12.56);

 System.out.printf("%.2f",pi);

// prints 3.14

System.out.printf("%.0f",pi4);

// prints 13

error: package javax.servlet does not exist

The javax.servlet dependency is missing in your pom.xml. Add the following to the dependencies-Node:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

iText - add content to existing PDF file

This is the most complicated scenario I can imagine: I have a PDF file created with Ilustrator and modified with Acrobat to have AcroFields (AcroForm) that I'm going to fill with data with this Java code, the result of that PDF file with the data in the fields is modified adding a Document.

Actually in this case I'm dynamically generating a background that is added to a PDF that is also dynamically generated with a Document with an unknown amount of data or pages.

I'm using JBoss and this code is inside a JSP file (should work in any JSP webserver).

Note: if you are using IExplorer you must submit a HTTP form with POST method to be able to download the file. If not you are going to see the PDF code in the screen. This does not happen in Chrome or Firefox.

<%@ page import="java.io.*, com.lowagie.text.*, com.lowagie.text.pdf.*" %><%

response.setContentType("application/download");
response.setHeader("Content-disposition","attachment;filename=listaPrecios.pdf" );  

// -------- FIRST THE PDF WITH THE INFO ----------
String str = "";
// lots of words
for(int i = 0; i < 800; i++) str += "Hello" + i + " ";
// the document
Document doc = new Document( PageSize.A4, 25, 25, 200, 70 );
ByteArrayOutputStream streamDoc = new ByteArrayOutputStream();
PdfWriter.getInstance( doc, streamDoc );
// lets start filling with info
doc.open();
doc.add(new Paragraph(str));
doc.close();
// the beauty of this is the PDF will have all the pages it needs
PdfReader frente = new PdfReader(streamDoc.toByteArray());
PdfStamper stamperDoc = new PdfStamper( frente, response.getOutputStream());

// -------- THE BACKGROUND PDF FILE -------
// in JBoss the file has to be in webinf/classes to be readed this way
PdfReader fondo = new PdfReader("listaPrecios.pdf");
ByteArrayOutputStream streamFondo = new ByteArrayOutputStream();
PdfStamper stamperFondo = new PdfStamper( fondo, streamFondo);
// the acroform
AcroFields form = stamperFondo.getAcroFields();
// the fields 
form.setField("nombre","Avicultura");
form.setField("descripcion","Esto describe para que sirve la lista ");
stamperFondo.setFormFlattening(true);
stamperFondo.close();
// our background is ready
PdfReader fondoEstampado = new PdfReader( streamFondo.toByteArray() );

// ---- ADDING THE BACKGROUND TO EACH DATA PAGE ---------
PdfImportedPage pagina = stamperDoc.getImportedPage(fondoEstampado,1);
int n = frente.getNumberOfPages();
PdfContentByte background;
for (int i = 1; i <= n; i++) {
    background = stamperDoc.getUnderContent(i);
    background.addTemplate(pagina, 0, 0);
}
// after this everithing will be written in response.getOutputStream()
stamperDoc.close(); 
%>

There is another solution much simpler, and solves your problem. It depends the amount of text you want to add.

// read the file
PdfReader fondo = new PdfReader("listaPrecios.pdf");
PdfStamper stamper = new PdfStamper( fondo, response.getOutputStream());
PdfContentByte content = stamper.getOverContent(1);
// add text
ColumnText ct = new ColumnText( content );
// this are the coordinates where you want to add text
// if the text does not fit inside it will be cropped
ct.setSimpleColumn(50,500,500,50);
ct.setText(new Phrase(str, titulo1));
ct.go();

PostgreSQL IF statement

Just to help if anyone stumble on this question like me, if you want to use if in PostgreSQL, you use "CASE"

select 
    case
        when stage = 1 then 'running'
        when stage = 2 then 'done'
        when stage = 3 then 'stopped'
    else 
        'not running'
    end as run_status from processes

how to convert `content://media/external/images/media/Y` to `file:///storage/sdcard0/Pictures/X.jpg` in android?

If you just want the bitmap, This too works

InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
if( inputStream != null ) inputStream.close();

sample uri : content://media/external/images/media/12345

How to check if a particular service is running on Ubuntu

There is a simple way to verify if a service is running

systemctl status service_name

Try PostgreSQL:

systemctl status postgresql

Setting dynamic scope variables in AngularJs - scope.<some_string>

Create Dynamic angular variables from results

angular.forEach(results, function (value, key) {          
  if (key != null) {                       
    $parse(key).assign($scope, value);                                
  }          
});

ps. don't forget to pass in the $parse attribute into your controller's function

Why am I getting a FileNotFoundError?

Is test.rtf located in the same directory you're in when you run this?

If not, you'll need to provide the full path to that file.

Suppose it's located in

/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/data

In that case you'd enter

data/test.rtf

as your file name

Or it could be in

/Users/AshleyStallings/Documents/School Work/Computer Programming/some_other_folder

In that case you'd enter

../some_other_folder/test.rtf

Is it possible to animate scrollTop with jQuery?

You can use the jQuery animation for scroll page with a specific duration:

$("html, body").animate({scrollTop: "1024px"}, 5000);

where 1024px is the scroll offset and 5000 is the duration of animations in millisecond.

jQuery - how can I find the element with a certain id?

This

var verificaHorario = $("#tbIntervalos").find("#" + horaInicial);

will find you the td that needs to be blocked.

Actually this will also do:

var verificaHorario = $("#" + horaInicial);

Testing for the size() of the wrapped set will answer your question regarding the existence of the id.

Floating elements within a div, floats outside of div. Why?

The easiest is to put overflow:hidden on the parent div and don't specify a height:

#parent { overflow: hidden }

Another way is to also float the parent div:

#parent { float: left; width: 100% }

Another way uses a clear element:

<div class="parent">
   <img class="floated_child" src="..." />
   <span class="clear"></span>
</div>

CSS

span.clear { clear: left; display: block; }

Oracle JDBC ojdbc6 Jar as a Maven Dependency

Go to the C drive->user->PcName->find .m2 and Paste the downloaded ojdbc jar file there, Server will automatically pick this.

How to convert a string to number in TypeScript?

Exactly like in JavaScript, you can use the parseInt or parseFloat functions, or simply use the unary + operator:

var x = "32";
var y: number = +x;

All of the mentioned techniques will have correct typing and will correctly parse simple decimal integer strings like "123", but will behave differently for various other, possibly expected, cases (like "123.45") and corner cases (like null).

Conversion table Table taken from this answer

Using <style> tags in the <body> with other HTML

Not valid HTML, anyway pretty much every browser seems to consider just the second instance.

Tested under the last versions of FF and Google Chrome under Fedora, and FF, Opera, IE, and Chrome under XP.

Passing a Bundle on startActivity()?

Write this is the activity you are in:

Intent intent = new Intent(CurrentActivity.this,NextActivity.class);
intent.putExtras("string_name","string_to_pass");
startActivity(intent);

In the NextActivity.java

Intent getIntent = getIntent();
//call a TextView object to set the string to
TextView text = (TextView)findViewById(R.id.textview_id);
text.setText(getIntent.getStringExtra("string_name"));

This works for me, you can try it.

Source:https://www.c-sharpcorner.com/article/how-to-send-the-data-one-activity-to-another-activity-in-android-application/

How to make picturebox transparent?

GameBoard is control of type DataGridView; The image should be type of PNG with transparent alpha channel background;

        Image test = Properties.Resources.checker_black;
        PictureBox b = new PictureBox();
        b.Parent = GameBoard;
        b.Image = test;
        b.Width = test.Width*2;
        b.Height = test.Height*2;
        b.Location = new Point(0, 90);
        b.BackColor = Color.Transparent;
        b.BringToFront();

enter image description here

JavaScript math, round to two decimal places

Fastest Way - faster than toFixed():

TWO DECIMALS

x      = .123456
result = Math.round(x * 100) / 100  // result .12

THREE DECIMALS

x      = .123456
result = Math.round(x * 1000) / 1000      // result .123

Can I have a video with transparent background using HTML5 video tag?

Yes, this sort of thing is possible without Flash:

However, only very modern browsers supports HTML5 videos, and this should be your consideration when deploying in HTML 5, and you should provide a fallback (probably Flash or just omit the transparency).

Multiple radio button groups in MVC 4 Razor

You can use Dictonary to map Assume Milk,Butter,Chesse are group A (ListA) Water,Beer,Wine are group B

Dictonary<string,List<string>>) dataMap;
dataMap.add("A",ListA);
dataMap.add("B",ListB);

At View , you can foreach Keys in dataMap and process your action

How to send json data in POST request using C#

You can do it with HttpWebRequest:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
            {
                Username = "myusername",
                Password = "pass"
            });
    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

Creating a new column based on if-elif-else condition

For this particular relationship, you could use np.sign:

>>> df["C"] = np.sign(df.A - df.B)
>>> df
   A  B  C
a  2  2  0
b  3  1  1
c  1  3 -1

The given key was not present in the dictionary. Which key?

If you want to manage key misses you should use TryGetValue

https://msdn.microsoft.com/en-gb/library/bb347013(v=vs.110).aspx

string value = "";
if (openWith.TryGetValue("tif", out value))
{
    Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
    Console.WriteLine("Key = \"tif\" is not found.");
}

How to sign in kubernetes dashboard?

The skip login has been disabled by default due to security issues. https://github.com/kubernetes/dashboard/issues/2672

in your dashboard yaml add this arg

- --enable-skip-login

to get it back

The cast to value type 'Int32' failed because the materialized value is null

I see that this question is already answered. But if you want it to be split into two statements, following may be considered.

var credits = from u in context.User
              join ch in context.CreditHistory 
                  on u.ID equals ch.UserID                                        
              where u.ID == userID
              select ch;

var creditSum= credits.Sum(x => (int?)x.Amount) ?? 0;

VB.NET Inputbox - How to identify when the Cancel Button is pressed?

You can do it in a simpler way using the DialogResult.cancel method.

Eg:

Dim anInput as String = InputBox("Enter your pin")

If anInput <>"" then

   ' Do something
Elseif DialogResult.Cancel then

  Msgbox("You've canceled")
End if

Creating a copy of a database in PostgreSQL

What's the correct way to copy entire database (its structure and data) to a new one in pgAdmin?

Answer:

CREATE DATABASE newdb WITH TEMPLATE originaldb;

Tried and tested.

How do I kill an Activity when the Back button is pressed?

add this to your activity

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

ASP.NET MVC Dropdown List From SelectList

Just try this in razor

@{
    var selectList = new SelectList(
        new List<SelectListItem>
        {
            new SelectListItem {Text = "Google", Value = "Google"},
            new SelectListItem {Text = "Other", Value = "Other"},
        }, "Value", "Text");
}

and then

@Html.DropDownListFor(m => m.YourFieldName, selectList, "Default label", new { @class = "css-class" })

or

@Html.DropDownList("ddlDropDownList", selectList, "Default label", new { @class = "css-class" })

Python executable not finding libpython shared library

All it needs is the installation of libpython [3 or 2] dev files installation.

MySQL: @variable vs. variable. What's the difference?

In principle, I use UserDefinedVariables (prepended with @) within Stored Procedures. This makes life easier, especially when I need these variables in two or more Stored Procedures. Just when I need a variable only within ONE Stored Procedure, than I use a System Variable (without prepended @).

@Xybo: I don't understand why using @variables in StoredProcedures should be risky. Could you please explain "scope" and "boundaries" a little bit easier (for me as a newbe)?

Is there an easy way to convert Android Application to IPad, IPhone

In the box is working on being able to convert android projects to iOS

https://code.google.com/p/in-the-box/

Convert javascript object or array to json for ajax data

I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:

var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";

console.log( JSON.stringify(display) );

This will print:

["none","block","none"]

This is how JSON actually serializes array. However what you want to see is something like:

{"0":"none","1":"block","2":"none"}

To get this format you want to serialize object, not array. So let's rewrite above code like this:

var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";

console.log( JSON.stringify(display2) );

This will print in the format you want.

You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

Add Json NamingStrategy property to your class definition.

_x000D_
_x000D_
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
_x000D_
_x000D_
_x000D_

Add two textbox values and display the sum in a third textbox automatically

This is the correct code

function sum() 
{ 
    var txtFirstNumberValue = document.getElementById('total_fees').value; 
    var txtSecondNumberValue = document.getElementById('advance_payement').value; 
    var result = parseInt(txtFirstNumberValue) - parseInt(txtSecondNumberValue); 
    if(txtFirstNumberValue=="" ||txtSecondNumberValue=="") 
    { 
        document.getElementById('balance_payement').value = 0; 
    }
    if (!isNaN(result)) 
    { 
        document.getElementById('balance_payement').value = result;
    }
} 

How can I map True/False to 1/0 in a Pandas DataFrame?

You can use a transformation for your data frame:

df = pd.DataFrame(my_data condition)

transforming True/False in 1/0

df = df*1

How do I get the list of keys in a Dictionary?

I often used this to get the key and value inside a dictionary: (VB.Net)

 For Each kv As KeyValuePair(Of String, Integer) In layerList

 Next

(layerList is of type Dictionary(Of String, Integer))

How do I find which application is using up my port?

To see which ports are available on your machine run:

C:>  netstat -an |find /i "listening"

How can I test an AngularJS service from the console?

Angularjs Dependency Injection framework is responsible for injecting the dependancies of you app module to your controllers. This is possible through its injector.

You need to first identify the ng-app and get the associated injector. The below query works to find your ng-app in the DOM and retrieve the injector.

angular.element('*[ng-app]').injector()

In chrome, however, you can point to target ng-app as shown below. and use the $0 hack and issue angular.element($0).injector()

Once you have the injector, get any dependency injected service as below

injector = angular.element($0).injector();
injector.get('$mdToast');

enter image description here

Is a view faster than a simple query?

Generally speaking, no. Views are primarily used for convenience and security, and won't (by themselves) produce any speed benefit.

That said, SQL Server 2000 and above do have a feature called Indexed Views that can greatly improve performance, with a few caveats:

  1. Not every view can be made into an indexed view; they have to follow a specific set of guidelines, which (among other restrictions) means you can't include common query elements like COUNT, MIN, MAX, or TOP.
  2. Indexed views use physical space in the database, just like indexes on a table.

This article describes additional benefits and limitations of indexed views:

You Can…

  • The view definition can reference one or more tables in the same database.
  • Once the unique clustered index is created, additional nonclustered indexes can be created against the view.
  • You can update the data in the underlying tables – including inserts, updates, deletes, and even truncates.

You Can’t…

  • The view definition can’t reference other views, or tables in other databases.
  • It can’t contain COUNT, MIN, MAX, TOP, outer joins, or a few other keywords or elements.
  • You can’t modify the underlying tables and columns. The view is created with the WITH SCHEMABINDING option.
  • You can’t always predict what the query optimizer will do. If you’re using Enterprise Edition, it will automatically consider the unique clustered index as an option for a query – but if it finds a “better” index, that will be used. You could force the optimizer to use the index through the WITH NOEXPAND hint – but be cautious when using any hint.

Yii2 data provider default sorting

Try to this one

$dataProvider = new ActiveDataProvider([
    'query' => $query,
]);

$sort = $dataProvider->getSort();

$sort->defaultOrder = ['id' => SORT_ASC];

$dataProvider->setSort($sort);

Java - ignore exception and continue

It's generally considered a bad idea to ignore exceptions. Usually, if it's appropriate, you want to either notify the user of the issue (if they would care) or at the very least, log the exception, or print the stack trace to the console.

However, if that's truly not necessary (you're the one making the decision) then no, there's no other way to ignore an exception that forces you to catch it. The only revision, in that case, that I would suggest is explicitly listing the the class of the Exceptions you're ignoring, and some comment as to why you're ignoring them, rather than simply ignoring any exception, as you've done in your example.

Load a UIView from nib in Swift

I prefer this solution (based on the answer if @GK100):

  1. I created a XIB and a class named SomeView (used the same name for convenience and readability). I based both on a UIView.
  2. In the XIB, I changed the "File's Owner" class to SomeView (in the identity inspector).
  3. I created a UIView outlet in SomeView.swift, linking it to the top level view in the XIB file (named it "view" for convenience). I then added other outlets to other controls in the XIB file as needed.
  4. In SomeView.swift, I loaded the XIB inside the init or init:frame: CGRect initializer. There is no need to assign anything to "self". As soon as the XIB is loaded, all outlets are connected, including the top level view. The only thing missing, is to add the top view to the view hierarchy:

    class SomeView: UIView {
      override init(frame: CGRect) {
        super.init(frame: frame)
        NSBundle.mainBundle().loadNibNamed("SomeObject", owner: self, options: nil)
        self.addSubview(self.view);    // adding the top level view to the view hierarchy
      }
    
      required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        NSBundle.mainBundle().loadNibNamed("SomeObject", owner: self, options: nil)
        self.addSubview(self.view);    // adding the top level view to the view hierarchy
      }
    
    
      ...
    }
    

Hidden Features of C#?

Reflection Emit and Expression trees come to mind...

Don't miss Jeffrey Richter's CLR via C# and Jon Skeet's alt text

See here for some resources:

http://www.codeproject.com/KB/trace/releasemodebreakpoint.aspx

http://www.codeproject.com/KB/dotnet/Creating_Dynamic_Types.aspx

http://www.codeproject.com/KB/cs/lambdaexpressions.aspx

How to specify maven's distributionManagement organisation wide?

Regarding the answer from Michael Wyraz, where you use alt*DeploymentRepository in your settings.xml or command on the line, be careful if you are using version 3.0.0-M1 of the maven-deploy-plugin (which is the latest version at the time of writing), there is a bug in this version that could cause a server authentication issue.

A workaround is as follows. In the value:

releases::default::https://YOUR_NEXUS_URL/releases

you need to remove the default section, making it:

releases::https://YOUR_NEXUS_URL/releases

The prior version 2.8.2 does not have this bug.

Stopword removal with NLTK

I suggest you create your own list of operator words that you take out of the stopword list. Sets can be conveniently subtracted, so:

operators = set(('and', 'or', 'not'))
stop = set(stopwords...) - operators

Then you can simply test if a word is in or not in the set without relying on whether your operators are part of the stopword list. You can then later switch to another stopword list or add an operator.

if word.lower() not in stop:
    # use word

How to check if a column exists in Pandas

This will work:

if 'A' in df:

But for clarity, I'd probably write it as:

if 'A' in df.columns:

jQuery validation: change default error message

Since we're already using JQuery, we can let page designers add custom messages to the markup rather than the code:

<input ... data-msg-required="my message" ...

Or, a more general solution using a single short data-msg attribute on all fields:

<form id="form1">
    <input type="text" id="firstName" name="firstName" 
        data-msg="Please enter your first name" />
    <br />
    <input type="text" id="lastName" name="lastName" 
        data-msg="Please enter your last name" />
    <br />
    <input type="submit" />
</form>

And the code then contains something like this:

function getMsg(selector) {
    return $(selector).attr('data-msg');
}

$('#form1').validate({
    // ...
    messages: {
        firstName: getMsg('#firstName'),
        lastName: getMsg('#lastName')
    }
    // ...
});

Hide axis values but keep axis tick labels in matplotlib

to remove tickmarks entirely use:

ax.set_yticks([])
ax.set_xticks([])

otherwise ax.set_yticklabels([]) and ax.set_xticklabels([]) will keep tickmarks.

How to Update Date and Time of Raspberry Pi With out Internet

Remember that Raspberry Pi does not have real time clock. So even you are connected to internet have to set the time every time you power on or restart.

This is how it works:

  1. Type sudo raspi-config in the Raspberry Pi command line
  2. Internationalization options
  3. Change Time Zone
  4. Select geographical area
  5. Select city or region
  6. Reboot your pi

Next thing you can set time using this command

sudo date -s "Mon Aug  12 20:14:11 UTC 2014"

More about data and time

man date

When Pi is connected to computer should have to manually set data and time

Most efficient way to convert an HTMLCollection to an Array

To convert array-like to array in efficient way we can make use of the jQuery makeArray :

makeArray: Convert an array-like object into a true JavaScript array.

Usage:

var domArray = jQuery.makeArray(htmlCollection);

A little extra:

If you do not want to keep reference to the array object (most of the time HTMLCollections are dynamically changes so its better to copy them into another array, This example pay close attention to performance:

var domDataLength = domData.length //Better performance, no need to calculate every iteration the domArray length
var resultArray = new Array(domDataLength) // Since we know the length its improves the performance to declare the result array from the beginning.

for (var i = 0 ; i < domDataLength ; i++) {
    resultArray[i] = domArray[i]; //Since we already declared the resultArray we can not make use of the more expensive push method.
}

What is array-like?

HTMLCollection is an "array-like" object, the array-like objects are similar to array's object but missing a lot of its functionally definition:

Array-like objects look like arrays. They have various numbered elements and a length property. But that’s where the similarity stops. Array-like objects do not have any of Array’s functions, and for-in loops don’t even work!

How Can I Resolve:"can not open 'git-upload-pack' " error in eclipse?

......../info/refs?service=git-upload-pack not found: did you run git update-server-info on the server?

For me the issue was a password issue. I run Keychain and deleted Github passwords. I run the pull command after that and it asked me for username and password. After that it worked ok.

How do I rotate text in css?

In your case, it's the best to use rotate option from transform property as mentioned before. There is also writing-mode property and it works like rotate(90deg) so in your case, it should be rotated after it's applied. Even it's not the right solution in this case but you should be aware of this property.

Example:

writing-mode:vertical-rl;

More about transform: https://kolosek.com/css-transform/

More about writing-mode: https://css-tricks.com/almanac/properties/w/writing-mode/

Unit Tests not discovered in Visual Studio 2017

Don't read out of date articles under MSDN. .NET Core relevant materials are under docs.microsoft.com

https://docs.microsoft.com/en-us/dotnet/articles/core/testing/

Generally speaking you need a .NET Core console app to contain the unit test cases.

How do I 'overwrite', rather than 'merge', a branch on another branch in Git?

You can use the 'ours' merge strategy:

$ git checkout staging
$ git merge -s ours email # Merge branches, but use our (=staging) branch head
$ git checkout email
$ git merge staging

EDIT 2020-07-30:

I thought a bit more about this question and possible solutions. If you absolutely require the merge parents in the correct order, need perform this action with a single command line invocation, and don't mind running plumbing commands, you can do the following:

$ git checkout A
$ git merge --ff-only $(git commit-tree -m "Throw away branch 'A'" -p A -p B B^{tree})

This basically acts like the (non-existent) merge -s theirs strategy. You can find the resulting history in the plumbing branch of the demo repository

Not very readable and not as easy to remember compared to the -s ours switch, but it does the job. The resulting tree is again the same as branch B:

$ git rev-parse A^{tree} B^{tree} HEAD^{tree}
3859ea064e85b2291d189e798bfa1bff87f51f3e
0389f8f2a3e560b639d82597a7bc5489a4c96d44
0389f8f2a3e560b639d82597a7bc5489a4c96d44

EDIT 2020-07-29:

There seems to be a lot of confusion as to what the difference between -s ours and -X ours (equivalent to -s recursive --strategy-option ours) is. Here's a small example to show the two results from using the strategy vs the strategy option. I also recommend reading the question and answers of (Git Merging) When to use 'ours' strategy, 'ours' option and 'theirs' option?

First, setup a repository with 2 branches and 3 commits (1 base commit, and 1 commit per branch). You can find the sample repository on GitHub

$ git init
$ echo 'original' | tee file1 file2 file3
$ git commit -m 'initial commit'
$ git branch A
$ git branch B
$ git checkout A
$ echo 'A' > file1
$ git commit -m 'change on branch A' file1
$ git checkout B
$ echo 'B' > file2
$ git commit -m 'change on branch B' file2

Now, let's try the strategy option (doesn't really matter if we use theirs or ours for this explanation):

$ git merge -X ours A
$ cat file*
A
B
original

We end up with a merge of both branches' contents (branch "strategy-option" in the sample repo). Compare that to using the merge strategy (re-init your repository or reset branch, before executing the next steps):

$ git merge -s ours A
$ cat file*
original
B
original

The result is quite different (branch "merge-strategy" in the sample repo). With the strategy option, we get a merge result of both branches, with the strategy we throw away any changes which happened in the other branch.

You will also notice that the commit created by the merge-strategy in fact points to the exact same tree than the latest commit of "our" branch, while the strategy-option created a new, previously unseen tree:

$ git rev-parse A^{tree} B^{tree} merge-strategy^{tree} strategy-option^{tree}
3859ea064e85b2291d189e798bfa1bff87f51f3e
0389f8f2a3e560b639d82597a7bc5489a4c96d44
0389f8f2a3e560b639d82597a7bc5489a4c96d44
5b09d34a37a183723b409d25268c8cb4d073206e

OP indeed asked for "I no longer need the old changes in […] branch" and "So I just want to dump all the contents of [A] into [B]", which is not possible to do with a strategy option. Using the 'ours' merge strategy is one possibility of many, but likely the easiest (other possibilities include using low level commands of Git such as write-tree and commit-tree).

Get the last non-empty cell in a column in Google Sheets

To find the last non-empty cell you can use INDEX and MATCH functions like this:

=DAYS360(A2; INDEX(A:A; MATCH(99^99;A:A; 1)))

I think this is a little bit faster and easier.

Make install, but not to default directories?

It depends on the package. If the Makefile is generated by GNU autotools (./configure) you can usually set the target location like so:

./configure --prefix=/somewhere/else/than/usr/local

If the Makefile is not generated by autotools, but distributed along with the software, simply open it up in an editor and change it. The install target directory is probably defined in a variable somewhere.

Why does the html input with type "number" allow the letter 'e' to be entered in the field?

<input type="number" onkeydown="return FilterInput(event)" onpaste="handlePaste(event)"  >

function FilterInput(event) {
    var keyCode = ('which' in event) ? event.which : event.keyCode;

    isNotWanted = (keyCode == 69 || keyCode == 101);
    return !isNotWanted;
};
function handlePaste (e) {
    var clipboardData, pastedData;

    // Get pasted data via clipboard API
    clipboardData = e.clipboardData || window.clipboardData;
    pastedData = clipboardData.getData('Text').toUpperCase();

    if(pastedData.indexOf('E')>-1) {
        //alert('found an E');
        e.stopPropagation();
        e.preventDefault();
    }
};

How do I create a user account for basic authentication?

Just to add a note, since I can't comment without 50+ rep...

If you have FIPS enabled on the server, it doesn't allow you to create users. Because IIS v8 (and lower I would imagine) does not use FIPS encryption algorithms. It would be great if it supported it , because obviously a user account in windows is insecure compared to a virtual user mapped to an isolated folder. Too bad.

enter image description here