Programs & Examples On #Linq to objects

The term "LINQ to Objects" refers to the use of LINQ queries with any IEnumerable or IEnumerable collection directly, without the use of an intermediate LINQ provider or API such as LINQ to SQL [https://msdn.microsoft.com/en-us/library/bb386976.aspx] or LINQ to XML.

Using LINQ to group a list of objects

var groupedCustomerList = CustomerList.GroupBy(u => u.GroupID)
                                      .Select(grp =>new { GroupID =grp.Key, CustomerList = grp.ToList()})
                                      .ToList();

Sorting a list using Lambda/Linq to objects

Sort uses the IComparable interface, if the type implements it. And you can avoid the ifs by implementing a custom IComparer:

class EmpComp : IComparer<Employee>
{
    string fieldName;
    public EmpComp(string fieldName)
    {
        this.fieldName = fieldName;
    }

    public int Compare(Employee x, Employee y)
    {
        // compare x.fieldName and y.fieldName
    }
}

and then

list.Sort(new EmpComp(sortBy));

how to query LIST using linq

Well, the code you've given is invalid to start with - List is a generic type, and it has an Add method instead of add etc.

But you could do something like:

List<Person> list = new List<Person>
{
    new person{ID=1,Name="jhon",salary=2500},
    new person{ID=2,Name="Sena",salary=1500},
    new person{ID=3,Name="Max",salary=5500}.
    new person{ID=4,Name="Gen",salary=3500}
};

// The "Where" LINQ operator filters a sequence
var highEarners = list.Where(p => p.salary > 3000);

foreach (var person in highEarners)
{
    Console.WriteLine(person.Name);
}

If you want to learn details of what all the LINQ operators do, and how they can be implemented in LINQ to Objects, you might be interested in my Edulinq blog series.

How can I get LINQ to return the object which has the max value for a given property?

Or you can write your own extension method:

static partial class Extensions
{
    public static T WhereMax<T, U>(this IEnumerable<T> items, Func<T, U> selector)
    {
        if (!items.Any())
        {
            throw new InvalidOperationException("Empty input sequence");
        }

        var comparer = Comparer<U>.Default;
        T   maxItem  = items.First();
        U   maxValue = selector(maxItem);

        foreach (T item in items.Skip(1))
        {
            // Get the value of the item and compare it to the current max.
            U value = selector(item);
            if (comparer.Compare(value, maxValue) > 0)
            {
                maxValue = value;
                maxItem  = item;
            }
        }

        return maxItem;
    }
}

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

An alternate solution uses the following class/interface. It's not truly dynamic, but it works.

public interface IID
{
    int ID
    {
        get; set;
    }
}

public static class Utils
{
    public static int GetID<T>(ObjectQuery<T> items) where T:EntityObject, IID
    {
        if (items.Count() == 0) return 1;
        return items.OrderByDescending(u => u.ID).FirstOrDefault().ID + 1;
    }
}

Remove duplicates in the list using linq

Try this extension method out. Hopefully this could help.

public static class DistinctHelper
{
    public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    {
        var identifiedKeys = new HashSet<TKey>();
        return source.Where(element => identifiedKeys.Add(keySelector(element)));
    }
}

Usage:

var outputList = sourceList.DistinctBy(x => x.TargetProperty);

Filtering lists using LINQ

I couldn't figure out how to do this in pure MS LINQ, so I wrote my own extension method to do it:

public static bool In<T>(this T objToCheck, params T[] values)
{
    if (values == null || values.Length == 0) 
    {
        return false; //early out
    }
    else
    {
        foreach (T t in values)
        {
            if (t.Equals(objToCheck))
                return true;   //RETURN found!
        }

        return false; //nothing found
    }
}

Linq select objects in list where exists IN (A,B,C)

Just be careful, .Contains() will match any substring including the string that you do not expect. For eg. new[] { "A", "B", "AA" }.Contains("A") will return you both A and AA which you might not want. I have been bitten by it.

.Any() or .Exists() is safer choice

how to display excel sheet in html page

Like you, I cannot get MS Office Web Components to work. I would not consider Google Docs since Google seems to think they own anything that passes through their hands. I have tried MS Publish Objects but the quality of the generated html/css is truely awful.

The secret of converting an Excel worksheet to html that will display correctly on a smartphone is to create clean, lean html/css.

The structure of the HTML is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    HEAD
  </head>
  <body>
    BODY
  </body>
</html>

There are useful html elements that can replace "HEAD" but it is not clear to me how you would generate them from an Excel worksheet. They would need to be added separately.

The obvious output for a worksheet or a range is an html table so the following assumes BODY will be replaced by an html table.

The structure of an html table is:

<table TABLE-ATTRIBUTES>
  <tr TABLE-ROW-ATTRIBUTES>
    <td TABLE-CELL-ATTRIBUTES>CELL-VALUE</td>
    More <td>...</td> elements as necessary
  </tr>
  More <tr>...</tr> as necessary
</table>  

Include as few TABLE-ATTRIBUTES, TABLE-ROW-ATTRIBUTES and TABLE-CELL-ATTRIBUTES as possible. Do not set column widths in pixels. Use css attributes rather than html attributes.

A table attribute worth considering is style = "border-collapse: collapse;". The default is separate with a gap around each cell. With collapse the cells touch as they do with Excel.

Three table attribute worth considering are style="background-color:aliceblue;", style="color:#0000FF;" and style="text-align:right;". With the first, you can specify the background colour to be any of the fifty or so named html colours. With the second, you can specify the font colour to be any of 256*256*256 colours. With the third you can right-align numeric values.

The above covers only a fraction of the formatting information that could be converted from Excel to html/css. I am developing an add-in that will convert as much Excel formatting as possible but I hope the above helps anyone with simple requirements.

Converting NSString to NSDictionary / JSON

Use this code where str is your JSON string:

NSError *err = nil;
NSArray *arr = 
 [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] 
                                 options:NSJSONReadingMutableContainers 
                                   error:&err];
// access the dictionaries
NSMutableDictionary *dict = arr[0];
for (NSMutableDictionary *dictionary in arr) {
  // do something using dictionary
}

How can I read pdf in python?

You can USE PyPDF2 package

#install pyDF2
pip install PyPDF2

# importing all the required modules
import PyPDF2

# creating an object 
file = open('example.pdf', 'rb')

# creating a pdf reader object
fileReader = PyPDF2.PdfFileReader(file)

# print the number of pages in pdf file
print(fileReader.numPages)

Follow this Documentation http://pythonhosted.org/PyPDF2/

Unable to generate an explicit migration in entity framework

Scenario

  • I am working in a branch in which I created a new DB migration.
  • I am ready to update from master, but master has a recent DB migration, too.
  • I delete my branch's db migration to prevent conflicts.
  • I "update from master".

Problem

After updating from master, I run "Add-Migration my_migration_name", but get the following error:

Unable to generate an explicit migration because the following explicit migrations are pending: [201607181944091_AddExternalEmailActivity]. Apply the pending explicit migrations before attempting to generate a new explicit migration.

So, I run "Update-Database" and get the following error:

Unable to update database to match the current model because there are pending changes and automatic migration is disabled

Solution

At this point re-running "Add-Migration my_migration_name" solved my problem. My theory is that running "Update-Database" got everything in the state it needed to be in order for "Add-Migration" to work.

React Native: Getting the position of an element

If you use function components and don't want to use a forwardRef to measure your component's absolute layout, you can get a reference to it from the LayoutChangeEvent in the onLayout callback.

This way, you can get the absolute position of the element:

<MyFunctionComp
  onLayout={(event) => {
    event.target.measure(
      (x, y, width, height, pageX, pageX) => {
        doSomethingWithAbsolutePosition({
          x: x + pageX, 
          y: y + pageY,
        });
      },
    );
  }}
/>

Tested with React Native 0.63.3.

Closing WebSocket correctly (HTML5, Javascript)

The thing of it is there are 2 main protocol versions of WebSockets in use today. The old version which uses the [0x00][message][0xFF] protocol, and then there's the new version using Hybi formatted packets.

The old protocol version is used by Opera and iPod/iPad/iPhones so it's actually important that backward compatibility is implemented in WebSockets servers. With these browsers using the old protocol, I discovered that refreshing the page, or navigating away from the page, or closing the browser, all result in the browser automatically closing the connection. Great!!

However with browsers using the new protocol version (eg. Firefox, Chrome and eventually IE10), only closing the browser will result in the browser automatically closing the connection. That is to say, if you refresh the page, or navigate away from the page, the browser does NOT automatically close the connection. However, what the browser does do, is send a hybi packet to the server with the first byte (the proto ident) being 0x88 (better known as the close data frame). Once the server receives this packet it can forcefully close the connection itself, if you so choose.

how to compare the Java Byte[] array?

They are returning false because you are testing for object identity rather than value equality. This returns false because your arrays are actually different objects in memory.

If you want to test for value equality should use the handy comparison functions in java.util.Arrays

e.g.

import java.util.Arrays;

'''''

Arrays.equals(a,b);

How to embed PDF file with responsive width

I did that mistake once - embedding PDF files in HTML pages. I will suggest that you use a JavaScript library for displaying the content of the PDF. Like https://github.com/mozilla/pdf.js/

Current Subversion revision command

REV=svn info svn://svn.code.sf.net/p/retroshare/code/trunk | grep 'Revision:' | cut -d\ -f2

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

I added the following to my htaccess file, which did the trick:

BrowserMatch MSIE ie
Header set X-UA-Compatible "IE=Edge,chrome=1" env=ie

List of all unique characters in a string?

char_seen = []
for char in string:
    if char not in char_seen:
        char_seen.append(char)
print(''.join(char_seen))

This will preserve the order in which alphabets are coming,

output will be

abcd

Explicit vs implicit SQL joins

Performance wise, it should not make any difference. The explicit join syntax seems cleaner to me as it clearly defines relationships between tables in the from clause and does not clutter up the where clause.

How to get full width in body element

You should set body and html to position:fixed;, and then set right:, left:, top:, and bottom: to 0;. That way, even if content overflows it will not extend past the limits of the viewport.

For example:

<html>
<body>
    <div id="wrapper"></div>
</body>
</html>

CSS:

html, body, {
    position:fixed;
    top:0;
    bottom:0;
    left:0;
    right:0;
}

JS Fiddle Example

Caveat: Using this method, if the user makes their window smaller, content will be cut off.

Git and nasty "error: cannot lock existing info/refs fatal"

For me this worked:

git remote prune origin

Since this answer seems to help a lot of people, I dug a little bit into what actually happens here. What this will do is remove references to remote branches in the folder .git/refs/remotes/origin. So this will not affect your local branches and it will not change anything remote, but it will update the local references you have to remote branches. It seems in some cases these references can contain data Git cannot handle correctly.

Declare a const array

For my needs I define static array, instead of impossible const and it works: public static string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };

Entity Framework change connection at runtime

The created class is 'partial'!

public partial class Database1Entities1 : DbContext
{
    public Database1Entities1()
        : base("name=Database1Entities1")
    {
    }

... and you call it like this:

using (var ctx = new Database1Entities1())
      {
        #if DEBUG
        ctx.Database.Log = Console.Write;
        #endif

so, you need only create a partial own class file for original auto-generated class (with same class name!) and add a new constructor with connection string parameter, like Moho's answer before.

After it you able to use parametrized constructor against original. :-)

example:

using (var ctx = new Database1Entities1(myOwnConnectionString))
      {
        #if DEBUG
        ctx.Database.Log = Console.Write;
        #endif

How to create a hidden <img> in JavaScript?

This question is vague, but if you want to make the image with Javascript. It is simple.

function loadImages(src) {
  if (document.images) {
    img1 = new Image();
    img1.src = src;
}
loadImages("image.jpg");

The image will be requested but until you show it it will never be displayed. great for pre loading images you expect to be requests but delaying it until the document is loaded.

Example

How do I delete an item or object from an array using ng-click?

I usually write in such style :

<a class="btn" ng-click="remove($index)">Delete</a>


$scope.remove = function(index){
  $scope.[yourArray].splice(index, 1)
};

Hope this will help You have to use a dot(.) between $scope and [yourArray]

Simple prime number generator in Python

Here is a numpy version of Sieve of Eratosthenes having both okay complexity (lower than sorting an array of length n) and vectorization.

import numpy as np 
def generate_primes(n):
    is_prime = np.ones(n+1,dtype=bool)
    is_prime[0:2] = False
    for i in range(int(n**0.5)+1):
        if is_prime[i]:
            is_prime[i*2::i]=False
    return np.where(is_prime)[0]

Timings:

import time    
for i in range(2,10):
    timer =time.time()
    generate_primes(10**i)
    print('n = 10^',i,' time =', round(time.time()-timer,6))

>> n = 10^ 2  time = 5.6e-05
>> n = 10^ 3  time = 6.4e-05
>> n = 10^ 4  time = 0.000114
>> n = 10^ 5  time = 0.000593
>> n = 10^ 6  time = 0.00467
>> n = 10^ 7  time = 0.177758
>> n = 10^ 8  time = 1.701312
>> n = 10^ 9  time = 19.322478

Maximum filename length in NTFS (Windows XP and Windows Vista)?

199 on Windows XP NTFS, I just checked.

This is not theory but from just trying on my laptop. There may be mitigating effects, but it physically won't let me make it bigger.

Is there some other setting limiting this, I wonder? Try it for yourself.

Log.INFO vs. Log.DEBUG

I usually try to use it like this:

  • DEBUG: Information interesting for Developers, when trying to debug a problem.
  • INFO: Information interesting for Support staff trying to figure out the context of a given error
  • WARN to FATAL: Problems and Errors depending on level of damage.

Installing Java 7 on Ubuntu

Download java jdk<version>-linux-x64.tar.gz file from https://www.oracle.com/technetwork/java/javase/downloads/index.html.

Extract this file where you want. like: /home/java(Folder name created by user in home directory).

Now open terminal. Set path JAVA_HOME=path of your jdk folder(open jdk folder then right click on any folder, go to properties then copy the path using select all) and paste here.

Like: JAVA_HOME=/home/xxxx/java/JDK1.8.0_201

Let Ubuntu know where our JDK/JRE is located.

sudo update-alternatives --install /usr/bin/java java /home/xxxx/java/jdk1.8.0_201/bin/java 20000
sudo update-alternatives --install /usr/bin/javac javac /home/xxxx/java/jdk1.8.0_201/bin/javac 20000
sudo update-alternatives --install /usr/bin/javaws javaws /home/xxxx/java/jdk1.8.0_201/bin/javaws 20000

Tell Ubuntu that our installation i.e., jdk1.8.0_05 must be the default Java.

sudo update-alternatives --set java /home/xxxx/sipTest/jdk1.8.0_201/bin/java
sudo update-alternatives --set javac /home/xxxx/java/sipTest/jdk1.8.0_201/bin/javac
sudo update-alternatives --set javaws /home/xxxxx/sipTest/jdk1.8.0_201/bin/javaws

Now try:

$ sudo update-alternatives --config java

There are 3 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                  Priority   Status
------------------------------------------------------------
* 0            /usr/lib/jvm/java-6-oracle1/bin/java   1047      auto mode
  1            /usr/bin/gij-4.6                       1046      manual mode
  2            /usr/lib/jvm/java-6-oracle1/bin/java   1047      manual mode
  3            /usr/lib/jvm/jdk1.7.0_75/bin/java      1         manual mode

Press enter to keep the current choice [*], or type selection number: 3

update-alternatives: using /usr/lib/jvm/jdk1.7.0_75/bin/java to provide /usr/bin/java (java) in manual mode

Repeat the above for:

sudo update-alternatives --config javac
sudo update-alternatives --config javaws

What does it mean to have an index to scalar variable error? python

IndexError: invalid index to scalar variable happens when you try to index a numpy scalar such as numpy.int64 or numpy.float64. It is very similar to TypeError: 'int' object has no attribute '__getitem__' when you try to index an int.

>>> a = np.int64(5)
>>> type(a)
<type 'numpy.int64'>
>>> a[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: invalid index to scalar variable.
>>> a = 5
>>> type(a)
<type 'int'>
>>> a[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'

Lightweight Javascript DB for use in Node.js

I wrote jaguarDb to handle some of the things that you are mentioning since I sometimes need a "little" database for demo or test projects too and I don't want to depend on mongoDB or another real database.

https://github.com/hectorcorrea/jaguarDb

Remove pandas rows with duplicate indices

Remove duplicates (Keeping First)

idx = np.unique( df.index.values, return_index = True )[1]
df = df.iloc[idx]

Remove duplicates (Keeping Last)

df = df[::-1]
df = df.iloc[ np.unique( df.index.values, return_index = True )[1] ]

Tests: 10k loops using OP's data

numpy method - 3.03 seconds
df.loc[~df.index.duplicated(keep='first')] - 4.43 seconds
df.groupby(df.index).first() - 21 seconds
reset_index() method - 29 seconds

Vertically centering a div inside another div

You can do this with a simple javascript (jQuery) block.

CSS:

#outerDiv{
    height:100%;
}

Javascript:

<script type="text/javascript">
    $(document).ready(function () {
        $("#innerDiv").css('top', ($(window).height() - $("#content").height()) / 2);
    });
</script>

Delete entire row if cell contains the string X

In the "Developer Tab" go to "Visual Basic" and create a Module. Copy paste the following. Remember changing the code, depending on what you want. Then run the module.

  Sub sbDelete_Rows_IF_Cell_Contains_String_Text_Value()
    Dim lRow As Long
    Dim iCntr As Long
    lRow = 390
    For iCntr = lRow To 1 Step -1
        If Cells(iCntr, 5).Value = "none" Then
            Rows(iCntr).Delete
        End If
    Next
    End Sub

lRow : Put the number of the rows that the current file has.

The number "5" in the "If" is for the fifth (E) column

Check string for palindrome

We can reduce the loop to half of the length:

function isPallindrome(s) {
  let word= s.toLowerCase();
  let length = word.length -1;
  let isPallindrome= true;
  for(let i=0; i< length/2 ;i++){
    if(word[i] !== word[length -i]){
      isPallindrome= false;
      break;
    }
  }
  return isPallindrome;
}

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

My npm install worked fine, but I had this problem with npm update. To fix it, I had to run npm cache clean and then npm cache clear.

How to use a typescript enum value in an Angular2 ngSwitch statement

This's simple and works like a charm :) just declare your enum like this and you can use it on HTML template

  statusEnum: typeof StatusEnum = StatusEnum;

What is the difference between <section> and <div>?

<div>—the generic flow container we all know and love. It’s a block-level element with no additional semantic meaning (W3C:Markup, WhatWG)

<section>—a generic document or application section. A normally has a heading (title) and maybe a footer too. It’s a chunk of related content, like a subsection of a long article, a major part of the page (eg the news section on the homepage), or a page in a webapp’s tabbed interface. (W3C:Markup, WhatWG)

My suggestion: div: used lower version( i think 4.01 to still) html element(lot of designers handled that). section: recently comming (html5) html element.

Big-oh vs big-theta

Bonus: why do people seemingly always use big-oh when talking informally?

Because in big-oh, this loop:

for i = 1 to n do
    something in O(1) that doesn't change n and i and isn't a jump

is O(n), O(n^2), O(n^3), O(n^1423424). big-oh is just an upper bound, which makes it easier to calculate because you don't have to find a tight bound.

The above loop is only big-theta(n) however.

What's the complexity of the sieve of eratosthenes? If you said O(n log n) you wouldn't be wrong, but it wouldn't be the best answer either. If you said big-theta(n log n), you would be wrong.

How can I create an error 404 in PHP?

The up-to-date answer (as of PHP 5.4 or newer) for generating 404 pages is to use http_response_code:

<?php
http_response_code(404);
include('my_404.php'); // provide your own HTML for the error page
die();

die() is not strictly necessary, but it makes sure that you don't continue the normal execution.

Can I define a class name on paragraph using Markdown?

It should also be mentioned that <span> tags allow inside them -- block-level items negate MD natively inside them unless you configure them not to do so, but in-line styles natively allow MD within them. As such, I often do something akin to...

This is a superfluous paragraph thing.

<span class="class-red">And thus I delve into my topic, Lorem ipsum lollipop bubblegum.</span>

And thus with that I conclude.

I am not 100% sure if this is universal but seems to be the case in all MD editors I've used.

rails simple_form - hidden field - create?

Correct way (if you are not trying to reset the value of the hidden_field input) is:

f.hidden_field :method, :value => value_of_the_hidden_field_as_it_comes_through_in_your_form

Where :method is the method that when called on the object results in the value you want

So following the example above:

= simple_form_for @movie do |f|
  = f.hidden :title, "some value"
  = f.button :submit

The code used in the example will reset the value (:title) of @movie being passed by the form. If you need to access the value (:title) of a movie, instead of resetting it, do this:

= simple_form_for @movie do |f|
  = f.hidden :title, :value => params[:movie][:title]
  = f.button :submit

Again only use my answer is you do not want to reset the value submitted by the user.

I hope this makes sense.

Why is there still a row limit in Microsoft Excel?

Probably because of optimizations. Excel 2007 can have a maximum of 16 384 columns and 1 048 576 rows. Strange numbers?

14 bits = 16 384, 20 bits = 1 048 576

14 + 20 = 34 bits = more than one 32 bit register can hold.

But they also need to store the format of the cell (text, number etc) and formatting (colors, borders etc). Assuming they use two 32-bit words (64 bit) they use 34 bits for the cell number and have 30 bits for other things.

Why is that important? In memory they don't need to allocate all the memory needed for the whole spreadsheet but only the memory necessary for your data, and every data is tagged with in what cell it is supposed to be in.

Update 2016:

Found a link to Microsoft's specification for Excel 2013 & 2016

  • Open workbooks: Limited by available memory and system resources
  • Worksheet size: 1,048,576 rows (20 bits) by 16,384 columns (14 bits)
  • Column width: 255 characters (8 bits)
  • Row height: 409 points
  • Page breaks: 1,026 horizontal and vertical (unexpected number, probably wrong, 10 bits is 1024)
  • Total number of characters that a cell can contain: 32,767 characters (signed 16 bits)
  • Characters in a header or footer: 255 (8 bits)
  • Sheets in a workbook: Limited by available memory (default is 1 sheet)
  • Colors in a workbook: 16 million colors (32 bit with full access to 24 bit color spectrum)
  • Named views in a workbook: Limited by available memory
  • Unique cell formats/cell styles: 64,000 (16 bits = 65536)
  • Fill styles: 256 (8 bits)
  • Line weight and styles: 256 (8 bits)
  • Unique font types: 1,024 (10 bits) global fonts available for use; 512 per workbook
  • Number formats in a workbook: Between 200 and 250, depending on the language version of Excel that you have installed
  • Names in a workbook: Limited by available memory
  • Windows in a workbook: Limited by available memory
  • Hyperlinks in a worksheet: 66,530 hyperlinks (unexpected number, probably wrong. 16 bits = 65536)
  • Panes in a window: 4
  • Linked sheets: Limited by available memory
  • Scenarios: Limited by available memory; a summary report shows only the first 251 scenarios
  • Changing cells in a scenario: 32
  • Adjustable cells in Solver: 200
  • Custom functions: Limited by available memory
  • Zoom range: 10 percent to 400 percent
  • Reports: Limited by available memory
  • Sort references: 64 in a single sort; unlimited when using sequential sorts
  • Undo levels: 100
  • Fields in a data form: 32
  • Workbook parameters: 255 parameters per workbook
  • Items displayed in filter drop-down lists: 10,000

Call php function from JavaScript

I recently published a jQuery plugin which allows you to make PHP function calls in various ways: https://github.com/Xaxis/jquery.php

Simple example usage:

// Both .end() and .data() return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25

// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]

git discard all changes and pull from upstream

I finally realized now that instead of

git fetch --all && git reset --hard origin/master

it should be

git fetch --all && git reset --hard origin/<branch_name>

instead (if one works on a different branch)

How to run a javascript function during a mouseover on a div

Here's a jQuery solution.

<script type="text/javascript" src="/path/to/your/copy/of/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#sub1").mouseover(function() {
        $("#welcome").toggle();
    });
});
</script>

Using this markup:

<div id="sub1">some text</div>
<div id="welcome" style="display:none;">Welcome message</div>

You didn't really specify if (or when) you wanted to hide the welcome message, but this would toggle hiding or showing each time you moused over the text.

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

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

Here is an example of using this strategy:

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

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

ReactJS call parent method

React 16+

Child Component

import React from 'react'

class ChildComponent extends React.Component
{
    constructor(props){
        super(props);       
    }

    render()
    {
        return <div>
            <button onClick={()=>this.props.greetChild('child')}>Call parent Component</button>
        </div>
    }
}

export default ChildComponent;

Parent Component

import React from "react";
import ChildComponent from "./childComponent";

class MasterComponent extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state={
            master:'master',
            message:''
        }
        this.greetHandler=this.greetHandler.bind(this);
    }

    greetHandler(childName){
        if(typeof(childName)=='object')
        {
            this.setState({            
                message:`this is ${this.state.master}`
            });
        }
        else
        {
            this.setState({            
                message:`this is ${childName}`
            });
        }

    }

    render()
    {
        return <div>
           <p> {this.state.message}</p>
            <button onClick={this.greetHandler}>Click Me</button>
            <ChildComponent greetChild={this.greetHandler}></ChildComponent>
        </div>
    }
}
export default  MasterComponent;

Set android shape color programmatically

The simple way to fill the shape with the Radius is:

(view.getBackground()).setColorFilter(Color.parseColor("#FFDE03"), PorterDuff.Mode.SRC_IN);

XSL substring and indexOf

The following is the complete example containing both XML and XSLT where substring-before and substring-after are used

<?xml version="1.0" encoding="UTF-8"?>
<persons name="Group_SOEM">
    <person>
        <first>Joe Smith</first>
        <last>Joe Smith</last>
        <address>123 Main St, Anycity</address>
    </person>
</persons>    

The following is XSLT which changes value of first/last name by separating the value by space so that after applying this XSL the first name element will have value "Joe" and last "Smith".

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="first">
    <first>
        <xsl:value-of select="substring-before(.,' ')" />
    </first>
</xsl:template> 
<xsl:template match="last">
    <last>
        <xsl:value-of select="substring-after(.,' ')" />
    </last>
</xsl:template> 
<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()" />
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>   

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

How does bitshifting work in Java?

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

Why is there an unexplainable gap between these inline-block div elements?

The easiest fix is to just float the container. (eg. float: left;) On another note, each id should be unique, meaning you can't use the same id twice in the same HTML document. You should use classes instead, where you can use the same class for multiple elements.

.container {
    position: relative;
    background: rgb(255, 100, 0);
    margin: 0;
    width: 40%;
    height: 100px;
    float: left;
}

Why does the 'int' object is not callable error occur when using the sum() function?

You probably redefined your "sum" function to be an integer data type. So it is rightly telling you that an integer is not something you can pass a range.

To fix this, restart your interpreter.

Python 2.7.3 (default, Apr 20 2012, 22:44:07) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> data1 = range(0, 1000, 3)
>>> data2 = range(0, 1000, 5)
>>> data3 = list(set(data1 + data2)) # makes new list without duplicates
>>> total = sum(data3) # calculate sum of data3 list's elements
>>> print total
233168

If you shadow the sum builtin, you can get the error you are seeing

>>> sum = 0
>>> total = sum(data3) # calculate sum of data3 list's elements
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

Also, note that sum will work fine on the set there is no need to convert it to a list

How do I change the value of a global variable inside of a function

Just reference the variable inside the function; no magic, just use it's name. If it's been created globally, then you'll be updating the global variable.

You can override this behaviour by declaring it locally using var, but if you don't use var, then a variable name used in a function will be global if that variable has been declared globally.

That's why it's considered best practice to always declare your variables explicitly with var. Because if you forget it, you can start messing with globals by accident. It's an easy mistake to make. But in your case, this turn around and becomes an easy answer to your question.

Apple Cover-flow effect using jQuery or other library?

i am currently working on this and planning on releasing it as a jQuery-ui plugin.

-> http://coulisse.luvdasun.com/

please let me know if you are interested and what you are hoping to see in such a plugin.

gr

Countdown timer using Moment js

Check out this plugin:

moment-countdown

moment-countdown is a tiny moment.js plugin that integrates with Countdown.js. The file is here.

How it works?

//from then until now
moment("1982-5-25").countdown().toString(); //=> '30 years, 10 months, 14 days, 1 hour, 8 minutes, and 14 seconds'

//accepts a moment, JS Date, or anything parsable by the Date constructor
moment("1955-8-21").countdown("1982-5-25").toString(); //=> '26 years, 9 months, and 4 days'

//also works with the args flipped, like diff()
moment("1982-5-25").countdown("1955-8-21").toString(); //=> '26 years, 9 months, and 4 days'

//accepts all of countdown's options
moment().countdown("1982-5-25", countdown.MONTHS|countdown.WEEKS, NaN, 2).toString(); //=> '370 months, and 2.01 weeks'

Code to loop through all records in MS Access

In "References", import DAO 3.6 object reference.

private sub showTableData

dim db as dao.database
dim rs as dao.recordset

set db = currentDb
set rs = db.OpenRecordSet("myTable") 'myTable is a MS-Access table created previously

'populate the table
rs.movelast
rs.movefirst

do while not rs.EOF
   debug.print(rs!myField) 'myField is a field name in table myTable
   rs.movenext             'press Ctrl+G to see debuG window beneath
loop

msgbox("End of Table")

end sub

You can interate data objects like queries and filtered tables in different ways:

Trhough query:

private sub showQueryData

dim db as dao.database
dim rs as dao.recordset
dim sqlStr as string

sqlStr = "SELECT * FROM customers as c WHERE c.country='Brazil'"

set db = currentDb
set rs = db.openRecordset(sqlStr)

rs.movefirst

do while not rs.EOF
  debug.print("cust ID: " & rs!id & " cust name: " & rs!name)
  rs.movenext
loop

msgbox("End of customers from Brazil")

end sub

You should also look for "Filter" property of the recordset object to filter only the desired records and then interact with them in the same way (see VB6 Help in MS-Access code window), or create a "QueryDef" object to run a query and use it as a recordset too (a little bit more tricky). Tell me if you want another aproach.

I hope I've helped.

How does Facebook disable the browser's integrated Developer Tools?

I'm a security engineer at Facebook and this is my fault. We're testing this for some users to see if it can slow down some attacks where users are tricked into pasting (malicious) JavaScript code into the browser console.

Just to be clear: trying to block hackers client-side is a bad idea in general; this is to protect against a specific social engineering attack.

If you ended up in the test group and are annoyed by this, sorry. I tried to make the old opt-out page (now help page) as simple as possible while still being scary enough to stop at least some of the victims.

The actual code is pretty similar to @joeldixon66's link; ours is a little more complicated for no good reason.

Chrome wraps all console code in

with ((console && console._commandLineAPI) || {}) {
  <code goes here>
}

... so the site redefines console._commandLineAPI to throw:

Object.defineProperty(console, '_commandLineAPI',
   { get : function() { throw 'Nooo!' } })

This is not quite enough (try it!), but that's the main trick.


Epilogue: The Chrome team decided that defeating the console from user-side JS was a bug and fixed the issue, rendering this technique invalid. Afterwards, additional protection was added to protect users from self-xss.

C# Validating input for textbox on winforms

With WinForms you can use the ErrorProvider in conjunction with the Validating event to handle the validation of user input. The Validating event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.

http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Your cells object is not fully qualified. You need to add a DOT before the cells object. For example

With Worksheets("Cable Cards")
    .Range(.Cells(RangeStartRow, RangeStartColumn), _
           .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

Similarly, fully qualify all your Cells object.

What does \0 stand for?

\0 is zero character. In C it is mostly used to indicate the termination of a character string. Of course it is a regular character and may be used as such but this is rarely the case.

The simpler versions of the built-in string manipulation functions in C require that your string is null-terminated(or ends with \0).

How do I automatically resize an image for a mobile site?

img {
  max-width: 100%;
}

Should set the image to take up 100% of its containing element.

add item to dropdown list in html using javascript

Try this

<script type="text/javascript">
    function AddItem()
    {
        // Create an Option object       
        var opt = document.createElement("option");        

        // Assign text and value to Option object
        opt.text = "New Value";
        opt.value = "New Value";

        // Add an Option object to Drop Down List Box
        document.getElementById('<%=DropDownList.ClientID%>').options.add(opt);
    }
<script />

The Value will append to the drop down list.

What is the best way to declare global variable in Vue.js?

In vue cli-3 You can define the variable in main.js like

window.basurl="http://localhost:8000/";

And you can also access this variable in any component by using the the window.basurl

How to remove all debug logging calls before building the release version of an Android app?

my Way:

1) enable Column Selection Mode (alt+shift+insert)

2) select on one Log.d(TAG, "text"); the part 'Log.'

3) then do shift + ctrl + alt + j

4) click left arrow

5) do shift+end

6) hit delete.

this removes all LOG calls at once in a java file.

What is the difference between Spring, Struts, Hibernate, JavaServer Faces, Tapestry?

Spring is an application framework which deals with IOC (Inversion of Control).

Struts 2 is a web application MVC framework which deals with actions.

Hibernate is an ORM (Object-Relational Mapping) that deals with persistent data.

What is the difference between association, aggregation and composition?

For two objects, Foo and Bar the relationships can be defined

Association - I have a relationship with an object. Foo uses Bar

public class Foo { 
    void Baz(Bar bar) {
    } 
};

Composition - I own an object and I am responsible for its lifetime. When Foo dies, so does Bar

public class Foo {
    private Bar bar = new Bar(); 
}

Aggregation - I have an object which I've borrowed from someone else. When Foo dies, Bar may live on.

public class Foo { 
    private Bar bar; 
    Foo(Bar bar) { 
       this.bar = bar; 
    }
}

Making a div vertically scrollable using CSS

Use overflow-y: auto; on the div.

Also, you should be setting the width as well.

Copy and paste content from one file to another file in vi

Example: fileA and fileB - start in fileA at line 25, copy 50 lines, and paste to fileB

fileA

Goto 25th line

25G

copy 50 lines into buffer v

"v50yy

Goto fileB

:e fileB

Goto line 10

10G    

paste contents of buffer v
"vp

How do I allow HTTPS for Apache on localhost?

tl;dr

ssh -R youruniquesubdomain:80:localhost:3000 serveo.net

And your local environment can be accessed from https://youruniquesubdomain.serveo.net

Serveo is the best

  • No signup.
  • No install.
  • Has HTTPS.
  • Accessible world-wide.
  • You can specify a custom fix, subdomain.
  • You can self host it, so you can use your own domain, and be future proof, even if the service goes down.

I couldn't believe when I found this service. It offers everything and it is the easiest to use. If there would be such an easy and painless tool for every problem...

How to get json key and value in javascript?

It looks like data not contains what you think it contains - check it.

_x000D_
_x000D_
let data={"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"};_x000D_
_x000D_
console.log( data["jobtitel"] );_x000D_
console.log( data.jobtitel );
_x000D_
_x000D_
_x000D_

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

Response you are getting is in object form i.e.

{ 
  "dstOffset" : 3600, 
  "rawOffset" : 36000, 
  "status" : "OK", 
  "timeZoneId" : "Australia/Hobart", 
  "timeZoneName" : "Australian Eastern Daylight Time" 
}

Replace below line of code :

List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))

with

Post post = gson.fromJson(reader, Post.class);

Delete commit on gitlab

We've had similar problem and it was not enough to only remove commit and force push to GitLab.
It was still available in GitLab interface using url:

https://gitlab.example.com/<group>/<project>/commit/<commit hash>

We've had to remove project from GitLab and recreate it to get rid of this commit in GitLab UI.

Magento Product Attribute Get Value

A way that I know of:

$product->getResource()->getAttribute($attribute_code)
        ->getFrontend()->getValue($product)

Get HTML inside iframe using jQuery

var iframe = document.getElementById('iframe');
  $(iframe).contents().find("html").html();

Define make variable at rule execution time

I dislike "Don't" answers, but... don't.

make's variables are global and are supposed to be evaluated during makefile's "parsing" stage, not during execution stage.

In this case, as long as the variable local to a single target, follow @nobar's answer and make it a shell variable.

Target-specific variables, too, are considered harmful by other make implementations: kati, Mozilla pymake. Because of them, a target can be built differently depending on if it's built standalone, or as a dependency of a parent target with a target-specific variable. And you won't know which way it was, because you don't know what is already built.

Howto: Clean a mysql InnoDB storage engine?

The InnoDB engine does not store deleted data. As you insert and delete rows, unused space is left allocated within the InnoDB storage files. Over time, the overall space will not decrease, but over time the 'deleted and freed' space will be automatically reused by the DB server.

You can further tune and manage the space used by the engine through an manual re-org of the tables. To do this, dump the data in the affected tables using mysqldump, drop the tables, restart the mysql service, and then recreate the tables from the dump files.

Import existing source code to GitHub

  1. Open your GitHub dashboard (it's at https://github.com/ if you're logged in)
  2. Click on New Repository
  3. Fill in the blanks; click on Create Repository
  4. Follow instructions on the page that appears then

Java code for getting current time

try this:

final String currentTime    = String.valueOf(System.currentTimeMillis());

Is there a better way to iterate over two lists, getting one element from each list for each iteration?

in case your Latitude and Longitude lists are large and lazily loaded:

from itertools import izip
for lat, lon in izip(latitudes, longitudes):
    process(lat, lon)

or if you want to avoid the for-loop

from itertools import izip, imap
out = imap(process, izip(latitudes, longitudes))

Parsing a JSON string in Ruby

Don't see any answers here that mention parsing directly to an object other than a Hash, but it is possible using the poorly-documented object_class option(see https://ruby-doc.org/stdlib-2.7.1/libdoc/json/rdoc/JSON.html):

JSON.parse('{"foo":{"bar": 2}}', object_class: OpenStruct).foo.bar
=> 2

The better way to read that option is "The ruby class that a json object turns into", which explains why it defaults to Hash. Likewise, there is an array_class option for json arrays.

How to select rows where column value IS NOT NULL using CodeIgniter's ActiveRecord?

The Active Record definitely has some quirks. When you pass an array to the $this->db->where() function it will generate an IS NULL. For example:

$this->db->where(array('archived' => NULL));

produces

WHERE `archived` IS NULL 

The quirk is that there is no equivalent for the negative IS NOT NULL. There is, however, a way to do it that produces the correct result and still escapes the statement:

$this->db->where('archived IS NOT NULL');

produces

WHERE `archived` IS NOT NULL

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app

I fixed this issue by setting a newer version of node as default in nvm i.e.:

nvm alias default 12.XX.X

self referential struct definition?

There is sort of a way around this:

struct Cell {
  bool isParent;
  struct Cell* child;
};

struct Cell;
typedef struct Cell Cell;

If you declare it like this, it properly tells the compiler that struct Cell and plain-ol'-cell are the same. So you can use Cell just like normal. Still have to use struct Cell inside of the initial declaration itself though.

Base64 encoding in SQL Server 2005 T-SQL

Pulling in things from all the answers above, here's what I came up with.

There are essentially two ways to do this:

;WITH TMP AS (
    SELECT CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("bin")))', 'VARCHAR(MAX)') as  Base64Encoding
    FROM 
    (
        SELECT TOP 10000 CAST(Words AS VARBINARY(MAX)) AS bin FROM TestData
    ) SRC
) 

SELECT *, CAST(CAST(N'' AS XML).value('xs:base64Binary(sql:column("Base64Encoding"))', 'VARBINARY(MAX)') AS NVARCHAR(MAX)) as ASCIIEncoding
FROM
(
    SELECT * FROM TMP
) SRC

And the second way

;WITH TMP AS 
(
    SELECT TOP 10000 CONVERT(VARCHAR(MAX), (SELECT CAST(Wordsas varbinary(max)) FOR XML PATH(''))) as BX
    FROM TestData
)

SELECT *, CONVERT(NVARCHAR(MAX), CONVERT(XML, BX).value('.','varbinary(max)'))
FROM TMP

When comparing performance, the first one has a subtree cost of 2.4414 and the second one has a subtree cost of 4.1538. Which means the first one is about twice as fast as the second one (which is expected, since it uses XML, which is notoriously slow).

type checking in javascript

A variable will never be an integer type in JavaScript — it doesn't distinguish between different types of Number.

You can test if the variable contains a number, and if that number is an integer.

(typeof foo === "number") && Math.floor(foo) === foo

If the variable might be a string containing an integer and you want to see if that is the case:

foo == parseInt(foo, 10)

Install specific branch from github using Npm

Tried suggested answers, but got it working only with this prefix approach:

npm i github:user/repo.git#version --save -D

How to create a density plot in matplotlib?

The density plot can also be created by using matplotlib: The function plt.hist(data) returns the y and x values necessary for the density plot (see the documentation https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.hist.html). Resultingly, the following code creates a density plot by using the matplotlib library:

import matplotlib.pyplot as plt
dat=[-1,2,1,4,-5,3,6,1,2,1,2,5,6,5,6,2,2,2]
a=plt.hist(dat,density=True)
plt.close()
plt.figure()
plt.plot(a[1][1:],a[0])      

This code returns the following density plot

enter image description here

How to put php inside JavaScript?

Try this:

<?php $htmlString= 'testing'; ?>
<html>
  <body>
    <script type="text/javascript">  
      // notice the quotes around the ?php tag         
      var htmlString="<?php echo $htmlString; ?>";
      alert(htmlString);
    </script>
  </body>
</html>

When you run into problems like this one, a good idea is to check your browser for JavaScript errors. Different browsers have different ways of showing this, but look for a javascript console or something like that. Also, check the source of your page as viewed by the browser.

Sometimes beginners are confused about the quotes in the string: In the PHP part, you assigned 'testing' to $htmlString. This puts a string value inside that variable, but the value does not have the quotes in it: They are just for the interpreter, so he knows: oh, now comes a string literal.

Using multiple case statements in select query

There are two ways to write case statements, you seem to be using a combination of the two

case a.updatedDate
    when 1760 then 'Entered on' + a.updatedDate
    when 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

or

case 
    when a.updatedDate = 1760 then 'Entered on' + a.updatedDate
    when a.updatedDate = 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

are equivalent. They may not work because you may need to convert date types to varchars to append them to other varchars.

vi/vim editor, copy a block (not usual action)

I found the below command much more convenient. If you want to copy lines from 6 to 12 and paste from the current cursor position.

:6,12 co .

If you want to copy lines from 6 to 12 and paste from 100th line.

:6,12t100

Source: https://www.reddit.com/r/vim/comments/8i6vbd/efficient_ways_of_copying_few_lines/

How to load local file in sc.textFile, instead of HDFS

While Spark supports loading files from the local filesystem, it requires that the files are available at the same path on all nodes in your cluster.

Some network filesystems, like NFS, AFS, and MapR’s NFS layer, are exposed to the user as a regular filesystem.

If your data is already in one of these systems, then you can use it as an input by just specifying a file:// path; Spark will handle it as long as the filesystem is mounted at the same path on each node. Every node needs to have the same path

 rdd = sc.textFile("file:///path/to/file")

If your file isn’t already on all nodes in the cluster, you can load it locally on the driver without going through Spark and then call parallelize to distribute the contents to workers

Take care to put file:// in front and the use of "/" or "\" according to OS.

How do I horizontally center an absolute positioned element inside a 100% width div?

here is the best practiced method to center a div as position absolute

DEMO FIDDLE

code --

#header {
background:black;
height:90px;
width:100%;
position:relative; // you forgot this, this is very important
}

#logo {
background:red;
height:50px;
position:absolute;
width:50px;
margin: auto; // margin auto works just you need to put top left bottom right as 0
top:0;
bottom:0;
left:0;
right:0;
}

How to adjust layout when soft keyboard appears

This question has beeen asked a few years ago and "Secret Andro Geni" has a good base explanation and "tir38" also made a good attempt on the complete solution, but alas there is no complete solution posted here. I've spend a couple of hours figuring out things and here is my complete solution with detailed explanation at the bottom:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/mainLayout"
            android:layout_alignParentTop="true"
            android:id="@+id/headerLayout">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:gravity="center_horizontal">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/textView1"
                    android:text="facebook"
                    android:textStyle="bold"
                    android:ellipsize="marquee"
                    android:singleLine="true"
                    android:textAppearance="?android:attr/textAppearanceLarge" />

            </LinearLayout>

        </RelativeLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:id="@+id/mainLayout"
            android:orientation="vertical">

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/editText1"
                android:ems="10"
                android:hint="Email or Phone"
                android:inputType="textVisiblePassword">

                <requestFocus />
            </EditText>

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:id="@+id/editText2"
                android:ems="10"
                android:hint="Password"
                android:inputType="textPassword" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:id="@+id/button1"
                android:text="Log In"
                android:onClick="login" />

        </LinearLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_below="@+id/mainLayout"
            android:id="@+id/footerLayout">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:id="@+id/textView2"
                        android:text="Sign Up for Facebook"
                        android:layout_centerHorizontal="true"
                        android:layout_alignBottom="@+id/helpButton"
                        android:ellipsize="marquee"
                        android:singleLine="true"
                        android:textAppearance="?android:attr/textAppearanceSmall" />

                    <Button
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:id="@+id/helpButton"
                        android:text="\?"
                        android:onClick="help" />

                </RelativeLayout>

            </LinearLayout>

        </RelativeLayout>

    </RelativeLayout>

</ScrollView>

And in AndroidManifest.xml, don't forget to set:

android:windowSoftInputMode="adjustResize"

on the <activity> tag that you want such layout.

Thoughts:

I've realized that RelativeLayout are the layouts that span thru all available space and are then resized when the keyboard pops up.

And LinearLayout are layouts that don't get resized in the resizing process.

That's why you need to have 1 RelativeLayout immediately after ScrollView to span thru all available screen space. And you need to have a LinearLayout inside a RelativeLayout else your insides would get crushed when the resizing occurs. Good example is "headerLayout". If there wouldn't be a LinearLayout inside that RelativeLayout "facebook" text would get crushed and wouldn't be shown.

In the "facebook" login pictures posted in the question I've also noticed that the whole login part (mainLayout) is centered vertical in relation to the whole screen, hence the attribute:

android:layout_centerVertical="true"

on the LinearLayout layout. And because mainLayout is inside a LinearLayout this means that that part does't get resized (again see picture in question).

Bootstrap 3 Align Text To Bottom of Div

I think your best bet would be to use a combination of absolute and relative positioning.

Here's a fiddle: http://jsfiddle.net/PKVza/2/

given your html:

<div class="row">
    <div class="col-sm-6">
        <img src="~/Images/MyLogo.png" alt="Logo" />
    </div>
    <div class="bottom-align-text col-sm-6">
        <h3>Some Text</h3>
    </div>
</div>

use the following CSS:

@media (min-width: 768px ) {
  .row {
      position: relative;
  }

  .bottom-align-text {
    position: absolute;
    bottom: 0;
    right: 0;
  }
}

EDIT - Fixed CSS and JSFiddle for mobile responsiveness and changed the ID to a class.

Erase the current printed console line

under windows 10 one can use VT100 style by activating the VT100 mode in the current console to use escape sequences as follow :

#include <windows.h>
#include <iostream>

#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#define DISABLE_NEWLINE_AUTO_RETURN  0x0008

int main(){

  // enabling VT100 style in current console
  DWORD l_mode;
  HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
  GetConsoleMode(hStdout,&l_mode)
  SetConsoleMode( hStdout, l_mode |
            ENABLE_VIRTUAL_TERMINAL_PROCESSING |
            DISABLE_NEWLINE_AUTO_RETURN );

  // create a waiting loop with changing text every seconds
  while(true) {
    // erase current line and go to line begining 
    std::cout << "\x1B[2K\r";
    std::cout << "wait a second .";
    Sleep(1);
    std::cout << "\x1B[2K\r";
    std::cout << "wait a second ..";
    Sleep(1);
    std::cout << "\x1B[2K\r";
    std::cout << "wait a second ...";
    Sleep(1);
    std::cout << "\x1B[2K\r";
    std::cout << "wait a second ....";
 }

}

see following link : windows VT100

Setting a max height on a table

NOTE this answer is now incorrect. I may get back to it at a later time.

As others have pointed out, you can't set the height of a table unless you set its display to block, but then you get a scrolling header. So what you're looking for is to set the height and display:block on the tbody alone:

<table style="border: 1px solid red">
    <thead>
        <tr>
            <td>Header stays put, no scrolling</td>
        </tr>
    </thead>
    <tbody style="display: block; border: 1px solid green; height: 30px; overflow-y: scroll">
        <tr>
            <td>cell 1/1</td>
            <td>cell 1/2</td>
        </tr>
        <tr>
            <td>cell 2/1</td>
            <td>cell 2/2</td>
        </tr>
        <tr>
            <td>cell 3/1</td>
            <td>cell 3/2</td>
        </tr>
    </tbody>
</table>

Here's the fiddle.

How can I use break or continue within for loop in Twig template?

From @NHG comment — works perfectly

{% for post in posts|slice(0,10) %}

graphing an equation with matplotlib

This is because in line

graph(x**3+2*x-4, range(-10, 11))

x is not defined.

The easiest way is to pass the function you want to plot as a string and use eval to evaluate it as an expression.

So your code with minimal modifications will be

import numpy as np  
import matplotlib.pyplot as plt  
def graph(formula, x_range):  
    x = np.array(x_range)  
    y = eval(formula)
    plt.plot(x, y)  
    plt.show()

and you can call it as

graph('x**3+2*x-4', range(-10, 11))

How to display HTML in TextView?

You need to use Html.fromHtml() to use HTML in your XML Strings. Simply referencing a String with HTML in your layout XML will not work.

This is what you should do:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    textView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>", Html.FROM_HTML_MODE_COMPACT));
} else { 
    textView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>"));
}

How to delete a line from a text file in C#?

I'd very simply:

  • Open the file for read/write
  • Read/seek through it until the start of the line you want to delete
  • Set the write pointer to the current read pointer
  • Read through to the end of the line we're deleting and skip the newline delimiters (counting the number of characters as we go, we'll call it nline)
  • Read byte-by-byte and write each byte to the file
  • When finished truncate the file to (orig_length - nline).

How To Upload Files on GitHub

You need to create a git repo locally, add your project files to that repo, commit them to the local repo, and then sync that repo to your repo on github. You can find good instructions on how to do the latter bit on github, and the former should be easy to do with the software you've downloaded.

How to parse a query string into a NameValueCollection in .NET

    private void button1_Click( object sender, EventArgs e )
    {
        string s = @"p1=6&p2=7&p3=8";
        NameValueCollection nvc = new NameValueCollection();

        foreach ( string vp in Regex.Split( s, "&" ) )
        {
            string[] singlePair = Regex.Split( vp, "=" );
            if ( singlePair.Length == 2 )
            {
                nvc.Add( singlePair[ 0 ], singlePair[ 1 ] );    
            }    
        }
    }

JQuery datepicker not working

For me.. the problem was that the anchor needs a title, and that was missing!

Getting the array length of a 2D array in Java

If you have this array:

String [][] example = {{{"Please!", "Thanks"}, {"Hello!", "Hey", "Hi!"}},
                       {{"Why?", "Where?", "When?", "Who?"}, {"Yes!"}}};

You can do this:

example.length;

= 2

example[0].length;

= 2

example[1].length;

= 2

example[0][1].length;

= 3

example[1][0].length;

= 4

What is the use of a private static variable in Java?

What is the use of a private static class variable?

Let's say you have a library book Class. Each time you create a new Book, you want to assign it a unique id. One way is to simply start at 0 and increment the id number. But, how do all the other books know the last created id number? Simple, save it as a static variable. Do patrons need to know that the actual internal id number is for each book? No. That information is private.

public class Book {
    private static int numBooks = 0;
    private int id;
    public String name;

    Book(String name) {
        id = numBooks++;
        this.name = name;
    }
}

This is a contrived example, but I'm sure you can easily think of cases where you'd want all class instances to have access to common information that should be kept private from everyone else. Or even if you can't, it is good programming practice to make things as private as possible. What if you accidentally made that numBooks field public, even though Book users were not supposed to do anything with it. Then someone could change the number of Books without creating a new Book.

Very sneaky!

When saving, how can you check if a field has changed?

If you are using a form, you can use Form's changed_data (docs):

class AliasForm(ModelForm):

    def save(self, commit=True):
        if 'remote_image' in self.changed_data:
            # do things
            remote_image = self.cleaned_data['remote_image']
            do_things(remote_image)
        super(AliasForm, self).save(commit)

    class Meta:
        model = Alias

How to configure PHP to send e-mail?

This will not work on a local host, but uploaded on a server, this code should do the trick. Just make sure to enter your own email address for the $to line.

<?php
if (isset($_POST['name']) && isset($_POST['email'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $to = '[email protected]';
    $subject = "New Message on YourWebsite.com";
    $body = '<html>
                <body>
                    <h2>Title</h2>
                    <br>
                    <p>Name:<br>'.$name.'</p>
                    <p>Email:<br>'.$email.'</p>

                </body>
            </html>';

//headers
$headers = "From: ".$name." <".$email.">\r\n";
$headers = "Reply-To: ".$email."\r\n";
$headers = "MIME-Version: 1.0\r\n";
$headers = "Content-type: text/html; charset=utf-8";

//send
$send = mail($to, $subject, $body, $headers);
if ($send) {
    echo '<br>';
    echo "Success. Thanks for Your Message.";
} else {
    echo 'Error.';
}
}
?>

<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <form action="" method="post">
            <input type="text" name="name" placeholder="Your Name"><br>
            <input type="text" name="email" placeholder="Your Email"><br>
            <button type="submit">Subscribe</button>
        </form>
    </body>
</html>

'MOD' is not a recognized built-in function name

If using JDBC driver you may use function escape sequence like this:

select {fn MOD(5, 2)}
#Result 1

select  mod(5, 2)
#SQL Error [195] [S00010]: 'mod' is not a recognized built-in function name.

Android - SMS Broadcast receiver

intent.getAction().equals(SMS_RECEIVED)

I have tried it out successfully.

How to return multiple values?

You can return an object of a Class in Java.

If you are returning more than 1 value that are related, then it makes sense to encapsulate them into a class and then return an object of that class.

If you want to return unrelated values, then you can use Java's built-in container classes like Map, List, Set etc. Check the java.util package's JavaDoc for more details.

How to Automatically Start a Download in PHP?

Here is an example of sending back a pdf.

header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Transfer-Encoding: binary');
readfile($filename);

@Swish I didn't find application/force-download content type to do anything different (tested in IE and Firefox). Is there a reason for not sending back the actual MIME type?

Also in the PHP manual Hayley Watson posted:

If you wish to force a file to be downloaded and saved, instead of being rendered, remember that there is no such MIME type as "application/force-download". The correct type to use in this situation is "application/octet-stream", and using anything else is merely relying on the fact that clients are supposed to ignore unrecognised MIME types and use "application/octet-stream" instead (reference: Sections 4.1.4 and 4.5.1 of RFC 2046).

Also according IANA there is no registered application/force-download type.

How do you disable viewport zooming on Mobile Safari?

In Safari 9.0 and up you can use shrink-to-fit in viewport meta tag as shown below

<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

CSS performance relative to translateZ(0)

It forces the browser to use hardware acceleration to access the device’s graphical processing unit (GPU) to make pixels fly. Web applications, on the other hand, run in the context of the browser, which lets the software do most (if not all) of the rendering, resulting in less horsepower for transitions. But the Web has been catching up, and most browser vendors now provide graphical hardware acceleration by means of particular CSS rules.

Using -webkit-transform: translate3d(0,0,0); will kick the GPU into action for the CSS transitions, making them smoother (higher FPS).

Note: translate3d(0,0,0) does nothing in terms of what you see. It moves the object by 0px in x,y and z axis. It's only a technique to force the hardware acceleration.

Good read here: http://www.smashingmagazine.com/2012/06/21/play-with-hardware-accelerated-css/

Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

In my case the problem was because of conflicting Jars.

Here is the full list of jars which is working absolutely fine for me.

antlr-2.7.7.jar
byte-buddy-1.8.12.jar
c3p0-0.9.5.2.jar
classmate-1.3.4.jar
dom4j-1.6.1.jar
geolatte-geom-1.3.0.jar
hibernate-c3p0-5.3.1.Final.jar
hibernate-commons-annotations-5.0.3.Final.jar
hibernate-core-5.3.1.Final.jar
hibernate-envers-5.3.1.Final.jar
hibernate-jpamodelgen-5.3.1.Final.jar
hibernate-osgi-5.3.1.Final.jar
hibernate-proxool-5.3.1.Final.jar
hibernate-spatial-5.3.1.Final.jar
jandex-2.0.3.Final.jar
javassist-3.22.0-GA.jar
javax.interceptor-api-1.2.jar
javax.persistence-api-2.2.jar
jboss-logging-3.3.2.Final.jar
jboss-transaction-api_1.2_spec-1.1.1.Final.jar
jts-core-1.14.0.jar
mchange-commons-java-0.2.11.jar
mysql-connector-java-5.1.21.jar
org.osgi.compendium-4.3.1.jar
org.osgi.core-4.3.1.jar
postgresql-42.2.2.jar
proxool-0.8.3.jar
slf4j-api-1.6.1.jar

How to set input type date's default value to today?

This is what I did in my code, I have just tested and it worked fine, input type="date" does not support to set curdate automatically, so the way I used to overcome this limitation was using PHP code a simple code like this.

<html>
<head></head>
    <body>
        <form ...>
            <?php
                echo "<label for='submission_date'>Data de submissão</label>";
                echo "<input type='date' name='submission_date' min='2012-01-01' value='" . date('Y-m-d') . "' required/>";
            ?>
        </form>
    </body>
</html>

Hope it helps!

Find an object in array?

For example, if we had an array of numbers:

let numbers = [2, 4, 6, 8, 9, 10]

We could find the first odd number like this:

let firstOdd = numbers.index { $0 % 2 == 1 }

That will send back 4 as an optional integer, because the first odd number (9) is at index four.

Post to another page within a PHP script

Although not ideal, if the cURL option doesn't do it for you, may be try using shell_exec();

Java ArrayList - Check if list is empty

Source: CodeSpeedy Click to know more Check if an ArrayList is empty or not

import java.util.ArrayList;
public class arraycheck {
public static void main(String args[]){
ArrayList<Integer> list=new ArrayList<Integer>();

    if(list.size()==0){
        System.out.println("Its Empty");

    }
    else
        System.out.println("Not Empty");

   }

}

Output:

run:
Its Empty
BUILD SUCCESSFUL (total time: 0 seconds)

How to open a website when a Button is clicked in Android application?

If you are talking about an RCP app, then what you need is the SWT link widget.

Here is the official link event handler snippet.

Update

Here is minimalist android application to connect to either superuser or stackoverflow with 2 buttons.

package ap.android;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

public class LinkButtons extends Activity {

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

    public void goToSo (View view) {
        goToUrl ( "http://stackoverflow.com/");
    }

    public void goToSu (View view) {
        goToUrl ( "http://superuser.com/");
    }

    private void goToUrl (String url) {
        Uri uriUrl = Uri.parse(url);
        Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
        startActivity(launchBrowser);
    }

}

And here is the layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/select" />
    <Button android:layout_height="wrap_content" android:clickable="true" android:autoLink="web" android:cursorVisible="true" android:layout_width="match_parent" android:id="@+id/button_so" android:text="StackOverflow" android:linksClickable="true" android:onClick="goToSo"></Button>
    <Button android:layout_height="wrap_content" android:layout_width="match_parent" android:text="SuperUser" android:autoLink="web" android:clickable="true" android:id="@+id/button_su" android:onClick="goToSu"></Button>
</LinearLayout>

How can I add spaces between two <input> lines using CSS?

You don't need to wrap everything in a DIV to achieve basic styling on inputs.

input[type="text"] {margin: 0 0 10px 0;}

will do the trick in most cases.

Semantically, one <br/> tag is okay between elements to position them. When you find yourself using multiple <br/>'s (which are semantic elements) to achieve cosmetic effects, that's a flag that you're mixing responsibilities, and you should consider getting back to basics.

How to change the type of a field?

demo change type of field mid from string to mongo objectId using mongoose

 Post.find({}, {mid: 1,_id:1}).exec(function (err, doc) {
             doc.map((item, key) => {
                Post.findByIdAndUpdate({_id:item._id},{$set:{mid: mongoose.Types.ObjectId(item.mid)}}).exec((err,res)=>{
                    if(err) throw err;
                    reply(res);
                });
            });
        });

Mongo ObjectId is just another example of such styles as

Number, string, boolean that hope the answer will help someone else.

what is this value means 1.845E-07 in excel?

1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.

1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.

C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.

You can specify a format string if you don't want to use the e-notation.

JQuery: Change value of hidden input field

Seems to work

$(".selector").change(function() {

    var $value = $(this).val();

    var $title = $(this).children('option[value='+$value+']').html();

    $('#bacon').val($title);

});

Just check with your firebug. And don't put css on hidden input.

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

You have forgotten to mark the getProducts return type as an array. In your getProducts it says that it will return a single product. So change it to this:

public getProducts(): Observable<Product[]> {
    return this.http.get<Product[]>(`api/products/v1/`);
  }

Label python data points on plot

I had a similar issue and ended up with this:

enter image description here

For me this has the advantage that data and annotation are not overlapping.

from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)

# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
    x = A[ind]
    y = B[ind]
    xPos = x1 + .02 * (x1 - x0)
    yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
    ax.annotate('',#label,
          xy=(x, y), xycoords='data',
          xytext=(xPos, yPos), textcoords='data',
          arrowprops=dict(
                          connectionstyle="arc3,rad=0.",
                          shrinkA=0, shrinkB=10,
                          arrowstyle= '-|>', ls= '-', linewidth=2
                          ),
          va='bottom', ha='left', zorder=19
          )
    ax.text(xPos + .01 * (x1 - x0), yPos,
            '({:.2f}, {:.2f})'.format(x,y),
            transform=ax.transData, va='center')

plt.grid()
plt.show()

Using the text argument in .annotate ended up with unfavorable text positions. Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.

SQL Server NOLOCK and joins

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

How to change the default background color white to something else in twitter bootstrap

You have to override the bootstrap default by being a bit more specific. Try this for a black background:

html body {
    background-color: rgba(0,0,0,1.00);

}

How to make an ng-click event conditional?

You could try to use ng-class.
Here is my simple example:
http://plnkr.co/edit/wS3QkQ5dvHNdc6Lb8ZSF?p=preview

<div ng-repeat="object in objects">
  <span ng-class="{'disabled': object.status}" ng-click="disableIt(object)">
    {{object.value}}
  </span>
</div>

The status is a custom attribute of object, you could name it whatever you want.
The disabled in ng-class is a CSS class name, the object.status should be true or false

You could change every object's status in function disableIt.
In your Controller, you could do this:

$scope.disableIt = function(obj) {
  obj.status = !obj.status
}

Update GCC on OSX

The following recipe using Homebrew worked for me to update to gcc/g++ 4.7:

$ brew tap SynthiNet/synthinet
$ brew install gcc47

Found it on a post here.

How to find out which processes are using swap space in Linux?

iotop is a very useful tool. It gives live stats of I/O and swap usage per process/thread. By default it shows per thread but you can do iotop -P to get per process info. This is not available by default. You may have to install via rpm/apt.

Fast query runs slow in SSRS

I had the same scenario occuring..Very basic report, the SP (which only takes in 1 param) was taking 5 seconds to bring back 10K records, yet the report would take 6 minutes to run. According to profiler and the RS ExecutionLogStorage table, the report was spending all it's time on the query. Brian S.'s comment led me to the solution..I simply added WITH RECOMPILE before the AS statement in the SP, and now the report time pretty much matches the SP execution time.

Output an Image in PHP

header('Content-type: image/jpeg');
readfile($image);

What is the correct value for the disabled attribute?

In HTML5, there is no correct value, all the major browsers do not really care what the attribute is, they are just checking if the attribute exists so the element is disabled.

Which JRE am I using?

In Linux:

java -version

In Windows:

java.exe -version

If you need more info about the JVM you can call the executable with the parameter -XshowSettings:properties. It will show a lot of System Properties. These properties can also be accessed by means of the static method System.getProperty(String) in a Java class. As example this is an excerpt of some of the properties that can be obtained:

$ java -XshowSettings:properties -version
[...]
java.specification.version = 1.7
java.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
java.vendor.url.bug = http://bugreport.sun.com/bugreport/
java.version = 1.7.0_95
[...]

So if you need to access any of these properties from Java code you can use:

System.getProperty("java.specification.version");
System.getProperty("java.vendor");
System.getProperty("java.vendor.url");
System.getProperty("java.version");

Take into account that sometimes the vendor is not exposed as clear as Oracle or IBM. For example,

$ java version
"1.6.0_22" Java(TM) SE Runtime Environment (build 1.6.0_22-b04) Java HotSpot(TM) Client VM (build 17.1-b03, mixed mode, sharing)

HotSpot is what Oracle calls their implementation of the JVM. Check this list if the vendor does not seem to be shown with -version.

Convert Data URI to File then append to FormData

Thanks to @Stoive and @vava720 I combined the two in this way, avoiding to use the deprecated BlobBuilder and ArrayBuffer

function dataURItoBlob(dataURI) {
    'use strict'
    var byteString, 
        mimestring 

    if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
        byteString = atob(dataURI.split(',')[1])
    } else {
        byteString = decodeURI(dataURI.split(',')[1])
    }

    mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]

    var content = new Array();
    for (var i = 0; i < byteString.length; i++) {
        content[i] = byteString.charCodeAt(i)
    }

    return new Blob([new Uint8Array(content)], {type: mimestring});
}

What is the HTML tabindex attribute?

When the user presses the tab button the user will be taken through the form in the order 1, 2, and 3 as indicated in the example below.

For example:

Name: <input name="name" tabindex="1"  />
Age: <input name="age" tabindex="3"  />
Email: <input name="email" tabindex="2"  />

How to pass arguments to a Button command in Tkinter?

One simple way would be to configure button with lambda like the following syntax:

button['command'] = lambda arg1 = local_var1, arg2 = local_var2 : function(arg1, arg2)

Is there a way to do repetitive tasks at intervals?

If you want to stop it in any moment ticker

ticker := time.NewTicker(500 * time.Millisecond)
go func() {
    for range ticker.C {
        fmt.Println("Tick")
    }
}()
time.Sleep(1600 * time.Millisecond)
ticker.Stop()

If you do not want to stop it tick:

tick := time.Tick(500 * time.Millisecond)
for range tick {
    fmt.Println("Tick")
}

PHP json_encode json_decode UTF-8

For me both methods

<?php

header('Content-Type: text/html; charset=utf-8');

echo json_encode($YourData, \JSON_UNESCAPED_UNICODE);

What is the equivalent of bigint in C#?

I just had a script that returned the primary key of an insert and used a

SELECT @@identity

on my bigint primary key, and I get a cast error using long - that was why I started this search. The correct answer, at least in my case, is that the type returned by that select is NUMERIC which equates to a decimal type. Using a long will cause a cast exception.

This is one reason to check your answers in more than one Google search (or even on Stack Overflow!).

To quote a database administrator who helped me out:

... BigInt is not the same as INT64 no matter how much they look alike. Part of the reason is that SQL will frequently convert Int/BigInt to Numeric as part of the normal processing. So when it goes to OLE or .NET the required conversion is NUMERIC to INT.

We don't often notice since the printed value looks the same.

Anaconda site-packages

You should find installed packages in :

anaconda's directory / lib / site_packages

That's where i found mine.

Convert a list to a data frame

Every solution I have found seems to only apply when every object in a list has the same length. I needed to convert a list to a data.frame when the length of the objects in the list were of unequal length. Below is the base R solution I came up with. It no doubt is very inefficient, but it does seem to work.

x1 <- c(2, 13)
x2 <- c(2, 4, 6, 9, 11, 13)
x3 <- c(1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8, 9, 9, 10, 11, 11, 12, 13, 13)
my.results <- list(x1, x2, x3)

# identify length of each list
my.lengths <- unlist(lapply(my.results, function (x) { length(unlist(x))}))
my.lengths
#[1]  2  6 20

# create a vector of values in all lists
my.values <- as.numeric(unlist(c(do.call(rbind, lapply(my.results, as.data.frame)))))
my.values
#[1]  2 13  2  4  6  9 11 13  1  1  2  3  3  4  5  5  6  7  7  8  9  9 10 11 11 12 13 13

my.matrix <- matrix(NA, nrow = max(my.lengths), ncol = length(my.lengths))

my.cumsum <- cumsum(my.lengths)

mm <- 1

for(i in 1:length(my.lengths)) {

     my.matrix[1:my.lengths[i],i] <- my.values[mm:my.cumsum[i]]

     mm <- my.cumsum[i]+1

}

my.df <- as.data.frame(my.matrix)
my.df
#   V1 V2 V3
#1   2  2  1
#2  13  4  1
#3  NA  6  2
#4  NA  9  3
#5  NA 11  3
#6  NA 13  4
#7  NA NA  5
#8  NA NA  5
#9  NA NA  6
#10 NA NA  7
#11 NA NA  7
#12 NA NA  8
#13 NA NA  9
#14 NA NA  9
#15 NA NA 10
#16 NA NA 11
#17 NA NA 11
#18 NA NA 12
#19 NA NA 13
#20 NA NA 13

How to convert std::string to LPCWSTR in C++ (Unicode)

I prefer using standard converters:

#include <codecvt>

std::string s = "Hi";
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring wide = converter.from_bytes(s);
LPCWSTR result = wide.c_str();

Please find more details in this answer: https://stackoverflow.com/a/18597384/592651


Update 12/21/2020 : My answer was commented on by @Andreas H . I thought his comment is valuable, so I updated my answer accordingly:

  1. codecvt_utf8_utf16 is deprecated in C++17.
  2. Also the code implies that source encoding is UTF-8 which it usually isn't.
  3. In C++20 there is a separate type std::u8string for UTF-8 because of that.

But it worked for me because I am still using an old version of C++ and it happened that my source encoding was UTF-8 .

Inserting data into a MySQL table using VB.NET

You need to use ?param instead of @param when performing queries to MySQL

 str_carSql = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (?id,?m_id,?model,?color,?ch_id,?pt_num,?code)"
        sqlCommand.Connection = SQLConnection
        sqlCommand.CommandText = str_carSql
        sqlCommand.Parameters.AddWithValue("?id", TextBox20.Text)
        sqlCommand.Parameters.AddWithValue("?m_id", TextBox20.Text)
        sqlCommand.Parameters.AddWithValue("?model", TextBox23.Text)
        sqlCommand.Parameters.AddWithValue("?color", TextBox24.Text)
        sqlCommand.Parameters.AddWithValue("?ch_id", TextBox22.Text)
        sqlCommand.Parameters.AddWithValue("?pt_num", TextBox21.Text)
        sqlCommand.Parameters.AddWithValue("?code", ComboBox1.SelectedItem)
        sqlCommand.ExecuteNonQuery()

Change the catch block to see the actual exception:

  Catch ex As Exception
         MsgBox(ex.Message)   
          Return False

    End Try

How do I sort an observable collection?

None of these answers worked in my case. Either because it screws up binding, or requires so much additional coding that it's kind of a nightmare, or the answer is just broken. So, here's yet another simpler answer i thought. It's a lot less code and it remains the same observable collection with an additional this.sort type of method. Let me know if there's some reason I shouldn't be doing it this way (efficiency etc.)?

public class ScoutItems : ObservableCollection<ScoutItem>
{
    public void Sort(SortDirection _sDir, string _sItem)
    {
             //TODO: Add logic to look at _sItem and decide what property to sort on
            IEnumerable<ScoutItem> si_enum = this.AsEnumerable();

            if (_sDir == SortDirection.Ascending)
            {
                si_enum = si_enum.OrderBy(p => p.UPC).AsEnumerable();
            } else
            {
                si_enum = si_enum.OrderByDescending(p => p.UPC).AsEnumerable();
            }

            foreach (ScoutItem si in si_enum)
            {
                int _OldIndex = this.IndexOf(si);
                int _NewIndex = si_enum.ToList().IndexOf(si);
                this.MoveItem(_OldIndex, _NewIndex);
            }
      }
}

...Where ScoutItem is my public class. Just seemed a lot simpler. Added benefit: it actually works and doesn't mess with bindings or return a new collection etc.

Difference between session affinity and sticky session?

Sticky session means to route the requests of particular session to the same physical machine who served the first request for that session.

Calling other function in the same controller?

Try:

return $this->sendRequest($uri);

Since PHP is not a pure Object-Orieneted language, it interprets sendRequest() as an attempt to invoke a globally defined function (just like nl2br() for example), but since your function is part of a class ('InstagramController'), you need to use $this to point the interpreter in the right direction.

Using a batch to copy from network drive to C: or D: drive

This might be due to a security check. This thread might help you.

There are two suggestions: one with pushd and one with a registry change. I'd suggest to use the first one...

Make DateTimePicker work as TimePicker only in WinForms

If you want to do it from properties, you can do this by setting the Format property of DateTimePicker to DateTimePickerFormat.Time and ShowUpDown property to true. Also, customFormat can be set in properties.

Goal Seek Macro with Goal as a Formula

GoalSeek will throw an "Invalid Reference" error if the GoalSeek cell contains a value rather than a formula or if the ChangingCell contains a formula instead of a value or nothing.

The GoalSeek cell must contain a formula that refers directly or indirectly to the ChangingCell; if the formula doesn't refer to the ChangingCell in some way, GoalSeek either may not converge to an answer or may produce a nonsensical answer.

I tested your code with a different GoalSeek formula than yours (I wasn't quite clear whether some of the terms referred to cells or values).

For the test, I set:

  the GoalSeek cell  H18 = (G18^3)+(3*G18^2)+6
  the Goal cell      H32 =  11
  the ChangingCell   G18 =  0 

The code was:

Sub GSeek()
    With Worksheets("Sheet1")
        .Range("H18").GoalSeek _
        Goal:=.Range("H32").Value, _
        ChangingCell:=.Range("G18")
    End With
End Sub

And the code produced the (correct) answer of 1.1038, the value of G18 at which the formula in H18 produces the value of 11, the goal I was seeking.

Mocking a class: Mock() or patch()?

Key points which explain difference and provide guidance upon working with unittest.mock

  1. Use Mock if you want to replace some interface elements(passing args) of the object under test
  2. Use patch if you want to replace internal call to some objects and imported modules of the object under test
  3. Always provide spec from the object you are mocking
    • With patch you can always provide autospec
    • With Mock you can provide spec
    • Instead of Mock, you can use create_autospec, which intended to create Mock objects with specification.

In the question above the right answer would be to use Mock, or to be more precise create_autospec (because it will add spec to the mock methods of the class you are mocking), the defined spec on the mock will be helpful in case of an attempt to call method of the class which doesn't exists ( regardless signature), please see some

from unittest import TestCase
from unittest.mock import Mock, create_autospec, patch


class MyClass:
    
    @staticmethod
    def method(foo, bar):
        print(foo)


def something(some_class: MyClass):
    arg = 1
    # Would fail becuase of wrong parameters passed to methd.
    return some_class.method(arg)


def second(some_class: MyClass):
    arg = 1
    return some_class.unexisted_method(arg)


class TestSomethingTestCase(TestCase):
    def test_something_with_autospec(self):
        mock = create_autospec(MyClass)
        mock.method.return_value = True
        # Fails because of signature misuse.
        result = something(mock)
        self.assertTrue(result)
        self.assertTrue(mock.method.called)
    
    def test_something(self):
        mock = Mock()  # Note that Mock(spec=MyClass) will also pass, because signatures of mock don't have spec.
        mock.method.return_value = True
        
        result = something(mock)
        
        self.assertTrue(result)
        self.assertTrue(mock.method.called)
        
    def test_second_with_patch_autospec(self):
        with patch(f'{__name__}.MyClass', autospec=True) as mock:
            # Fails because of signature misuse.
            result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)


class TestSecondTestCase(TestCase):
    def test_second_with_autospec(self):
        mock = Mock(spec=MyClass)
        # Fails because of signature misuse.
        result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)
    
    def test_second_with_patch_autospec(self):
        with patch(f'{__name__}.MyClass', autospec=True) as mock:
            # Fails because of signature misuse.
            result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)
    
    def test_second(self):
        mock = Mock()
        mock.unexisted_method.return_value = True
        
        result = second(mock)
        
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)

The test cases with defined spec used fail because methods called from something and second functions aren't complaint with MyClass, which means - they catch bugs, whereas default Mock will display.

As a side note there is one more option: use patch.object to mock just the class method which is called with.

The good use cases for patch would be the case when the class is used as inner part of function:

def something():
    arg = 1
    return MyClass.method(arg)

Then you will want to use patch as a decorator to mock the MyClass.

jquery to change style attribute of a div class

Just try $('.handle').css('left', '300px');

How can I search (case-insensitive) in a column using LIKE wildcard?

You must set up proper encoding and collation for your tables.

Table encoding must reflect the actual data encoding. What is your data encoding?

To see table encoding, you can run a query SHOW CREATE TABLE tablename

jQuery - select all text from a textarea

$('textarea').focus(function() {
    this.select();
}).mouseup(function() {
    return false;
});

How should I cast in VB.NET?

Cstr() is compiled inline for better performance.

CType allows for casts between types if a conversion operator is defined

ToString() Between base type and string throws an exception if conversion is not possible.

TryParse() From String to base typeif possible otherwise returns false

DirectCast used if the types are related via inheritance or share a common interface , will throw an exception if the cast is not possible, trycast will return nothing in this instance

Finding duplicate integers in an array and display how many times they occurred

Use Group by:

int[] values = new []{1,2,3,4,5,4,4,3};

var groups = values.GroupBy(v => v);
foreach(var group in groups)
    Console.WriteLine("Value {0} has {1} items", group.Key, group.Count());

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

I found the solution as Its problem with Android Studio 3.1 Canary 6

My backup of Android Studio 3.1 Canary 5 is useful to me and saved my half day.

Now My build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.2'
    defaultConfig {
        applicationId "com.example.demo"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    dataBinding {
        enabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:design:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:support-v4:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:recyclerview-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:cardview-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.squareup.retrofit2:retrofit:2.3.0"
    implementation "com.google.code.gson:gson:2.8.2"
    implementation "com.android.support.constraint:constraint-layout:1.0.2"
    implementation "com.squareup.retrofit2:converter-gson:2.3.0"
    implementation "com.squareup.okhttp3:logging-interceptor:3.6.0"
    implementation "com.squareup.picasso:picasso:2.5.2"
    implementation "com.dlazaro66.qrcodereaderview:qrcodereaderview:2.0.3"
    compile 'com.github.elevenetc:badgeview:v1.0.0'
    annotationProcessor 'com.github.elevenetc:badgeview:v1.0.0'
    testImplementation "junit:junit:4.12"
    androidTestImplementation("com.android.support.test.espresso:espresso-core:3.0.1", {
        exclude group: "com.android.support", module: "support-annotations"
    })
}

and My gradle is:

classpath 'com.android.tools.build:gradle:3.1.0-alpha06'

and its working finally.

I think there problem in Android Studio 3.1 Canary 6

Thank you all for your time.

Head and tail in one line

Building on the Python 2 solution from @GarethLatty, the following is a way to get a single line equivalent without intermediate variables in Python 2.

t=iter([1, 1, 2, 3, 5, 8, 13, 21, 34, 55]);h,t = [(h,list(t)) for h in t][0]

If you need it to be exception-proof (i.e. supporting empty list), then add:

t=iter([]);h,t = ([(h,list(t)) for h in t]+[(None,[])])[0]

If you want to do it without the semicolon, use:

h,t = ([(h,list(t)) for t in [iter([1,2,3,4])] for h in t]+[(None,[])])[0]

How to sort findAll Doctrine's method?

Modify the default findAll function in EntityRepository like this:

public function findAll( array $orderBy = null )
{
    return $this->findBy([], $orderBy);
}

That way you can use the ''findAll'' on any query for any data table with an option to sort the query

Custom events in jQuery?

Take a look at this:

(reprinted from the expired blog page http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/ based on the archived version at http://web.archive.org/web/20130120010146/http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/)


Publish / Subscribe With jQuery

June 17th, 2008

With a view to writing a jQuery UI integrated with the offline functionality of Google Gears i’ve been toying with some code to poll for network connection status using jQuery.

The Network Detection Object

The basic premise is very simple. We create an instance of a network detection object which will poll a URL at regular intervals. Should these HTTP requests fail we can assume that network connectivity has been lost, or the server is simply unreachable at the current time.

$.networkDetection = function(url,interval){
    var url = url;
    var interval = interval;
    online = false;
    this.StartPolling = function(){
        this.StopPolling();
        this.timer = setInterval(poll, interval);
    };
    this.StopPolling = function(){
        clearInterval(this.timer);
    };
    this.setPollInterval= function(i) {
        interval = i;
    };
    this.getOnlineStatus = function(){
        return online;
    };
    function poll() {
        $.ajax({
            type: "POST",
            url: url,
            dataType: "text",
            error: function(){
                online = false;
                $(document).trigger('status.networkDetection',[false]);
            },
            success: function(){
                online = true;
                $(document).trigger('status.networkDetection',[true]);
            }
        });
    };
};

You can view the demo here. Set your browser to work offline and see what happens…. no, it’s not very exciting.

Trigger and Bind

What is exciting though (or at least what is exciting me) is the method by which the status gets relayed through the application. I’ve stumbled upon a largely un-discussed method of implementing a pub/sub system using jQuery’s trigger and bind methods.

The demo code is more obtuse than it need to be. The network detection object publishes ’status ‘events to the document which actively listens for them and in turn publishes ‘notify’ events to all subscribers (more on those later). The reasoning behind this is that in a real world application there would probably be some more logic controlling when and how the ‘notify’ events are published.

$(document).bind("status.networkDetection", function(e, status){
    // subscribers can be namespaced with multiple classes
    subscribers = $('.subscriber.networkDetection');
    // publish notify.networkDetection even to subscribers
    subscribers.trigger("notify.networkDetection", [status])
    /*
    other logic based on network connectivity could go here
    use google gears offline storage etc
    maybe trigger some other events
    */
});

Because of jQuery’s DOM centric approach events are published to (triggered on) DOM elements. This can be the window or document object for general events or you can generate a jQuery object using a selector. The approach i’ve taken with the demo is to create an almost namespaced approach to defining subscribers.

DOM elements which are to be subscribers are classed simply with “subscriber” and “networkDetection”. We can then publish events only to these elements (of which there is only one in the demo) by triggering a notify event on $(“.subscriber.networkDetection”)

The #notifier div which is part of the .subscriber.networkDetection group of subscribers then has an anonymous function bound to it, effectively acting as a listener.

$('#notifier').bind("notify.networkDetection",function(e, online){
    // the following simply demonstrates
    notifier = $(this);
    if(online){
        if (!notifier.hasClass("online")){
            $(this)
                .addClass("online")
                .removeClass("offline")
                .text("ONLINE");
        }
    }else{
        if (!notifier.hasClass("offline")){
            $(this)
                .addClass("offline")
                .removeClass("online")
                .text("OFFLINE");
        }
    };
});

So, there you go. It’s all pretty verbose and my example isn’t at all exciting. It also doesn’t showcase anything interesting you could do with these methods, but if anyone’s at all interested to dig through the source feel free. All the code is inline in the head of the demo page

Laravel Migration Change to Make a Column Nullable

Laravel 5 now supports changing a column; here's an example from the offical documentation:

Schema::table('users', function($table)
{
    $table->string('name', 50)->nullable()->change();
});

Source: http://laravel.com/docs/5.0/schema#changing-columns

Laravel 4 does not support modifying columns, so you'll need use another technique such as writing a raw SQL command. For example:

// getting Laravel App Instance
$app = app();

// getting laravel main version
$laravelVer = explode('.',$app::VERSION);

switch ($laravelVer[0]) {

    // Laravel 4
    case('4'):

        DB::statement('ALTER TABLE `pro_categories_langs` MODIFY `name` VARCHAR(100) NULL;');
        break;

    // Laravel 5, or Laravel 6
    default:                

        Schema::table('pro_categories_langs', function(Blueprint $t) {
            $t->string('name', 100)->nullable()->change();
        });               

}

How to force a list to be vertical using html css

Try putting display: block in the <li> tags instead of the <ul>

How to automatically import data from uploaded CSV or XLS file into Google Sheets

(Mar 2017) The accepted answer is not the best solution. It relies on manual translation using Apps Script, and the code may not be resilient, requiring maintenance. If your legacy system autogenerates CSV files, it's best they go into another folder for temporary processing (importing [uploading to Google Drive & converting] to Google Sheets files).

My thought is to let the Drive API do all the heavy-lifting. The Google Drive API team released v3 at the end of 2015, and in that release, insert() changed names to create() so as to better reflect the file operation. There's also no more convert flag -- you just specify MIMEtypes... imagine that!

The documentation has also been improved: there's now a special guide devoted to uploads (simple, multipart, and resumable) that comes with sample code in Java, Python, PHP, C#/.NET, Ruby, JavaScript/Node.js, and iOS/Obj-C that imports CSV files into Google Sheets format as desired.

Below is one alternate Python solution for short files ("simple upload") where you don't need the apiclient.http.MediaFileUpload class. This snippet assumes your auth code works where your service endpoint is DRIVE with a minimum auth scope of https://www.googleapis.com/auth/drive.file.

# filenames & MIMEtypes
DST_FILENAME = 'inventory'
SRC_FILENAME = DST_FILENAME + '.csv'
SHT_MIMETYPE = 'application/vnd.google-apps.spreadsheet'
CSV_MIMETYPE = 'text/csv'

# Import CSV file to Google Drive as a Google Sheets file
METADATA = {'name': DST_FILENAME, 'mimeType': SHT_MIMETYPE}
rsp = DRIVE.files().create(body=METADATA, media_body=SRC_FILENAME).execute()
if rsp:
    print('Imported %r to %r (as %s)' % (SRC_FILENAME, DST_FILENAME, rsp['mimeType']))

Better yet, rather than uploading to My Drive, you'd upload to one (or more) specific folder(s), meaning you'd add the parent folder ID(s) to METADATA. (Also see the code sample on this page.) Finally, there's no native .gsheet "file" -- that file just has a link to the online Sheet, so what's above is what you want to do.

If not using Python, you can use the snippet above as pseudocode to port to your system language. Regardless, there's much less code to maintain because there's no CSV parsing. The only thing remaining is to blow away the CSV file temp folder your legacy system wrote to.

Reading HTML content from a UIWebView

To read:-

NSString *html = [myWebView stringByEvaluatingJavaScriptFromString: @"document.getElementById('your div id').textContent"];
NSLog(html);    

To modify:-

html = [myWebView stringByEvaluatingJavaScriptFromString: @"document.getElementById('your div id').textContent=''"];

What is the ideal data type to use when storing latitude / longitude in a MySQL database?

No need to go far, according to Google Maps, the best is FLOAT(10,6) for lat and lng.

Get Value of Row in Datatable c#

for (int i=0; i<dt_pattern.Rows.Count; i++)
{
    DataRow dr = dt_pattern.Rows[i];
}

In the loop, you can now reference row i+1 (assuming there is an i+1)

How to format column to number format in Excel sheet?

Sorry to bump an old question but the answer is to count the character length of the cell and not its value.

CellCount = Cells(Row, 10).Value
If Len(CellCount) <= "13" Then
'do something
End If

hope that helps. Cheers

How do you check current view controller class in Swift?

You can easily iterate over your view controllers if you are using a navigation controller. And then you can check for the particular instance as:
Swift 5

 if let viewControllers = navigationController?.viewControllers {
            for viewController in viewControllers {
                if viewController.isKind(of: LoginViewController.self) {
                    
                }
            }
        }

Android : Fill Spinner From Java Code Programmatically

Here is an example to fully programmatically:

  • init a Spinner.
  • fill it with data via a String List.
  • resize the Spinner and add it to my View.
  • format the Spinner font (font size, colour, padding).
  • clear the Spinner.
  • add new values to the Spinner.
  • redraw the Spinner.

I am using the following class vars:

Spinner varSpinner;
List<String> varSpinnerData;

float varScaleX;
float varScaleY;    

A - Init and render the Spinner (varRoot is a pointer to my main Activity):

public void renderSpinner() {


    List<String> myArraySpinner = new ArrayList<String>();

    myArraySpinner.add("red");
    myArraySpinner.add("green");
    myArraySpinner.add("blue");     

    varSpinnerData = myArraySpinner;

    Spinner mySpinner = new Spinner(varRoot);               

    varSpinner = mySpinner;

    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, myArraySpinner);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
    mySpinner.setAdapter(spinnerArrayAdapter);

B - Resize and Add the Spinner to my View:

    FrameLayout.LayoutParams myParamsLayout = new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT, 
            FrameLayout.LayoutParams.WRAP_CONTENT);
    myParamsLayout.gravity = Gravity.NO_GRAVITY;             

    myParamsLayout.leftMargin = (int) (100 * varScaleX);
    myParamsLayout.topMargin = (int) (350 * varScaleY);             
    myParamsLayout.width = (int) (300 * varScaleX);;
    myParamsLayout.height = (int) (60 * varScaleY);;


    varLayoutECommerce_Dialogue.addView(mySpinner, myParamsLayout);

C - Make the Click handler and use this to set the font.

    mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int myPosition, long myID) {

            Log.i("renderSpinner -> ", "onItemSelected: " + myPosition + "/" + myID);

            ((TextView) parentView.getChildAt(0)).setTextColor(Color.GREEN);
            ((TextView) parentView.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_PX, (int) (varScaleY * 22.0f) );
            ((TextView) parentView.getChildAt(0)).setPadding(1,1,1,1);


        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            // your code here
        }

    });

}   

D - Update the Spinner with new data:

private void updateInitSpinners(){

     String mySelected = varSpinner.getSelectedItem().toString();
     Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);


     varSpinnerData.clear();

     varSpinnerData.add("Hello World");
     varSpinnerData.add("Hello World 2");

     ((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
     varSpinner.invalidate();
     varSpinner.setSelection(1);

}

}

What I have not been able to solve in the updateInitSpinners, is to do varSpinner.setSelection(0); and have the custom font settings activated automatically.

UPDATE:

This "ugly" solution solves the varSpinner.setSelection(0); issue, but I am not very happy with it:

private void updateInitSpinners(){

    String mySelected = varSpinner.getSelectedItem().toString();
    Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);


    varSpinnerData.clear();

    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, varSpinnerData);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    varSpinner.setAdapter(spinnerArrayAdapter);  


    varSpinnerData.add("Hello World");
    varSpinnerData.add("Hello World 2");

    ((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
    varSpinner.invalidate();
    varSpinner.setSelection(0);

}

}

Hope this helps......

Match all elements having class name starting with a specific string

You can easily add multiple classes to divs... So:

<div class="myclass myclass-one"></div>
<div class="myclass myclass-two"></div>
<div class="myclass myclass-three"></div>

Then in the CSS call to the share class to apply the same styles:

.myclass {...}

And you can still use your other classes like this:

.myclass-three {...}

Or if you want to be more specific in the CSS like this:

.myclass.myclass-three {...}

Eclipse - no Java (JRE) / (JDK) ... no virtual machine

Just Add the JRE PATH FOR Ex: C:\Program Files\Java\jre5\bin in the environmental variable Put ";" in between every path. Then click the eclipse.exe It will work.....

crudrepository findBy method signature with multiple in operators?

The following signature will do:

List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);

Spring Data JPA supports a large number of keywords to build a query. IN and AND are among them.

Indentation Error in Python

For Sublime Text Editor

Indentation Error generally occurs when the code contains a mix of both tabs and spaces for indentation. I have got a very nice solution to correct it, just open your code in a sublime text editor and find 'Tab Size' in the bottom right corner of Sublime Text Editor and click it. Now select either

'Convert Indentation to Spaces'

OR

'Convert Indentation to Tabs'

Your code will work in either case.

Additionally, if you want Sublime text to do it automatically for you for every code you can update the Preference settings as below:-

Sublime Text menu > Preferences > Settings - Syntax Specific :

Python.sublime-settings

{
    "tab_size": 4,
    "translate_tabs_to_spaces": true
}

Customize the Authorization HTTP header

This is a bit dated but there may be others looking for answers to the same question. You should think about what protection spaces make sense for your APIs. For example, you may want to identify and authenticate client application access to your APIs to restrict their use to known, registered client applications. In this case, you can use the Basic authentication scheme with the client identifier as the user-id and client shared secret as the password. You don't need proprietary authentication schemes just clearly identify the one(s) to be used by clients for each protection space. I prefer only one for each protection space but the HTTP standards allow both multiple authentication schemes on each WWW-Authenticate header response and multiple WWW-Authenticate headers in each response; this will be confusing for API clients which options to use. Be consistent and clear then your APIs will be used.

jQuery: Get height of hidden element in jQuery

You are confuising two CSS styles, the display style and the visibility style.

If the element is hidden by setting the visibility css style, then you should be able to get the height regardless of whether or not the element is visible or not as the element still takes space on the page.

If the element is hidden by changing the display css style to "none", then the element doesn't take space on the page, and you will have to give it a display style which will cause the element to render in some space, at which point, you can get the height.

Write a number with two decimal places SQL Server

Multiply the value you want to insert (ex. 2.99) by 100

Then insert the division by 100 of the result adding .01 to the end:

299.01/100

Using the GET parameter of a URL in JavaScript

Here's some sample code for that.

<script>
var param1var = getQueryVariable("param1");

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  alert('Query Variable ' + variable + ' not found');
}
</script>

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

About hyperlinks:

The main use of anchor tags - <a></a> - is as hyperlinks. That basically means that they take you somewhere. Hyperlinks require the href property, because it specifies a location.

Hash:

A hash - # within a hyperlink specifies an html element id to which the window should be scrolled.

href="#some-id" would scroll to an element on the current page such as <div id="some-id">.

href="//site.com/#some-id" would go to site.com and scroll to the id on that page.

Scroll to Top:

href="#" doesn't specify an id name, but does have a corresponding location - the top of the page. Clicking an anchor with href="#" will move the scroll position to the top.

See this demo.

This is the expected behavior according to the w3 documentation.

Hyperlink placeholders:

An example where a hyperlink placeholder makes sense is within template previews. On single page demos for templates, I have often seen <a href="#"> so that the anchor tag is a hyperlink, but doesn't go anywhere. Why not leave the href property blank? A blank href property is actually a hyperlink to the current page. In other words, it will cause a page refresh. As I discussed, href="#" is also a hyperlink, and causes scrolling. Therefore, the best solution for hyperlink placeholders is actually href="#!" The idea here is that there hopefully isn't an element on the page with id="!" (who does that!?) and the hyperlink therefore refers to nothing - so nothing happens.

About anchor tags:

Another question that you may be wondering is, "Why not just leave the href property off?". A common response I've heard is that the href property is required, so it "should" be present on anchors. This is FALSE! The href property is required only for an anchor to actually be a hyperlink! Read this from w3. So, why not just leave it off for placeholders? Browsers render default styles for elements and will change the default style of an anchor tag that doesn't have the href property. Instead, it will be considered like regular text. It even changes the browser's behavior regarding the element. The status bar (bottom of the screen) will not be displayed when hovering on an anchor without the href property. It is best to use a placeholder href value on an anchor to ensure it is treated as a hyperlink.

See this demo demonstrating style and behavior differences.

How to change ProgressBar's progress indicator color in Android

Just create a style in values/styles.xml.

<style name="ProgressBarStyle">
    <item name="colorAccent">@color/greenLight</item>
</style>

Then set this style as your ProgressBar theme.

<ProgressBar
    android:theme="@style/ProgressBarStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

and doesn't matter your progress bar is horizontal or circular. That's all.

Are there .NET implementation of TLS 1.2?

You can enable TLS 1.2 in IIS by following these instructions. I presume this would be sufficient if you have an ASP.NET-based application that runs on top of IIS, although it looks like it does not really meet your needs.

How to add a new row to an empty numpy array

Here is my solution:

arr = []
arr.append([1,2,3])
arr.append([4,5,6])
np_arr = np.array(arr)

Access to the requested object is only available from the local network phpmyadmin

I newer version of xampp you may use another method first open your httpd-xampp.conf file and find the string "phpmyadmin" using ctrl+F command (Windows). and then replace this code

Alias /phpmyadmin "D:/server/phpMyAdmin/"
<Directory "D:/server/phpMyAdmin">
    AllowOverride AuthConfig
    Require local
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>

with this

Alias /phpmyadmin "D:/server/phpMyAdmin/"
<Directory "D:/server/phpMyAdmin">
    AllowOverride AuthConfig
    Require all granted
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>

Don't Forget to Restart your Xampp.

How do I get the max ID with Linq to Entity?

The best way to get the id of the entity you added is like this:

public int InsertEntity(Entity factor)
{
    Db.Entities.Add(factor);
    Db.SaveChanges();
    var id = factor.id;
    return id;
}

Using getline() in C++

The code is correct. The problem must lie somewhere else. Try the minimalistic example from the std::getline documentation.

main ()
{
    std::string name;

    std::cout << "Please, enter your full name: ";
    std::getline (std::cin,name);
    std::cout << "Hello, " << name << "!\n";

    return 0;
}

UTL_FILE.FOPEN() procedure not accepting path for directory?

Don't forget also that the path for the file is on the actual oracle server machine and not any local development machine that might be calling your stored procedure. This is probably very obvious but something that should be remembered.

"Input string was not in a correct format."

You have not mentioned if your textbox have values in design time or now. When form initializes text box may not hae value if you have not put it in textbox when during form design. you can put int value in form design by setting text property in desgin and this should work.

SQL Call Stored Procedure for each Row without using a cursor

This is a variation of n3rds solution above. No sorting by using ORDER BY is needed, as MIN() is used.

Remember that CustomerID (or whatever other numerical column you use for progress) must have a unique constraint. Furthermore, to make it as fast as possible CustomerID must be indexed on.

-- Declare & init
DECLARE @CustomerID INT = (SELECT MIN(CustomerID) FROM Sales.Customer); -- First ID
DECLARE @Data1 VARCHAR(200);
DECLARE @Data2 VARCHAR(200);

-- Iterate over all customers
WHILE @CustomerID IS NOT NULL
BEGIN  

  -- Get data based on ID
  SELECT @Data1 = Data1, @Data2 = Data2
    FROM Sales.Customer
    WHERE [ID] = @CustomerID ;

  -- call your sproc
  EXEC dbo.YOURSPROC @Data1, @Data2

  -- Get next customerId
  SELECT @CustomerID = MIN(CustomerID)
    FROM Sales.Customer
    WHERE CustomerID > @CustomerId 

END

I use this approach on some varchars I need to look over, by putting them in a temporary table first, to give them an ID.

Initializing a static std::map<int, int> in C++

Best way is to use a function:

#include <map>

using namespace std;

map<int,int> create_map()
{
  map<int,int> m;
  m[1] = 2;
  m[3] = 4;
  m[5] = 6;
  return m;
}

map<int,int> m = create_map();

How to get today's Date?

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));

found here

What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it?

I recently got this error. I had compiled the binary with -O3. Google told me that this means "illegal opcode", which seemed fishy to me. I then turned off all optimizations and reran. Now the error transformed to a segfault. Hence by setting -g and running valgrind I tracked the source down and fixed it. Reenabling all optimizations showed no further appearances of illegal instruction 4.

Apparently, optimizing wrong code can yield weird results.

Check if a string contains a number

I'm surprised that no-one mentionned this combination of any and map:

def contains_digit(s):
    isdigit = str.isdigit
    return any(map(isdigit,s))

in python 3 it's probably the fastest there (except maybe for regexes) is because it doesn't contain any loop (and aliasing the function avoids looking it up in str).

Don't use that in python 2 as map returns a list, which breaks any short-circuiting

Hibernate: hbm2ddl.auto=update in production?

I wouldn't risk it because you might end up losing data that should have been preserved. hbm2ddl.auto=update is purely an easy way to keep your dev database up to date.

EF LINQ include multiple and nested entities

Have you tried just adding another Include:

Course course = db.Courses
                .Include(i => i.Modules.Select(s => s.Chapters))
                .Include(i => i.Lab)
                .Single(x => x.Id == id);

Your solution fails because Include doesn't take a boolean operator

Include(i => i.Modules.Select(s => s.Chapters) &&          i.Lab)
                           ^^^                  ^             ^ 
                          list           bool operator    other list

Update To learn more, download LinqPad and look through the samples. I think it is the quickest way to get familiar with Linq and Lambda.

As a start - the difference between Select and Include is that that with a Select you decide what you want to return (aka projection). The Include is a Eager Loading function, that tells Entity Framework that you want it to include data from other tables.

The Include syntax can also be in string. Like this:

           db.Courses
            .Include("Module.Chapter")
            .Include("Lab")
            .Single(x => x.Id == id);

But the samples in LinqPad explains this better.

VarBinary vs Image SQL Server Data Type to Store Binary Data?

Since image is deprecated, you should use varbinary.

per Microsoft (thanks for the link @Christopher)

ntext , text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

Fixed and variable-length data types for storing large non-Unicode and Unicode character and binary data. Unicode data uses the UNICODE UCS-2 character set.

What strategies and tools are useful for finding memory leaks in .NET?

Are you using unmanaged code? If you are not using unmanaged code, according to Microsoft, memory leaks in the traditional sense are not possible.

Memory used by an application may not be released however, so an application's memory allocation may grow throughout the life of the application.

From How to identify memory leaks in the common language runtime at Microsoft.com

A memory leak can occur in a .NET Framework application when you use unmanaged code as part of the application. This unmanaged code can leak memory, and the .NET Framework runtime cannot address that problem.

Additionally, a project may only appear to have a memory leak. This condition can occur if many large objects (such as DataTable objects) are declared and then added to a collection (such as a DataSet). The resources that these objects own may never be released, and the resources are left alive for the whole run of the program. This appears to be a leak, but actually it is just a symptom of the way that memory is being allocated in the program.

For dealing with this type of issue, you can implement IDisposable. If you want to see some of the strategies for dealing with memory management, I would suggest searching for IDisposable, XNA, memory management as game developers need to have more predictable garbage collection and so must force the GC to do its thing.

One common mistake is to not remove event handlers that subscribe to an object. An event handler subscription will prevent an object from being recycled. Also, take a look at the using statement which allows you to create a limited scope for a resource's lifetime.

C++ pass an array by reference

Here, Erik explains every way pass an array by reference: https://stackoverflow.com/a/5724184/5090928.

Similarly, you can create an array reference variable like so:

int arr1[] = {1, 2, 3, 4, 5};
int(&arr2)[5] = arr1;

Calling onclick on a radiobutton list using javascript

To trigger the onClick event on a radio-button invoke the click() method on the DOM element:

document.getElementById("radioButton").click()

using jquery:

$("#radioButton").click()

AngularJs:

angular.element('#radioButton').trigger('click')

Android: How to get a custom View's height and width?

The difference between getHeight() and getMeasuredHeight() is that first method will return actual height of the View, the second one will return summary height of View's children. In ohter words, getHeight() returns view height, getMeasuredHeight() returns height which this view needs to show all it's elements

How to Calculate Jump Target Address and Branch Target Address?

(In the diagrams and text below, PC is the address of the branch instruction itself. PC+4 is the end of the branch instruction itself, and the start of the branch delay slot. Except in the absolute jump diagram.)

1. Branch Address Calculation

In MIPS branch instruction has only 16 bits offset to determine next instruction. We need a register added to this 16 bit value to determine next instruction and this register is actually implied by architecture. It is PC register since PC gets updated (PC+4) during the fetch cycle so that it holds the address of the next instruction.

We also limit the branch distance to -2^15 to +2^15 - 1 instruction from the (instruction after the) branch instruction. However, this is not real issue since most branches are local anyway.

So step by step :

  • Sign extend the 16 bit offset value to preserve its value.
  • Multiply resulting value with 4. The reason behind this is that If we are going to branch some address, and PC is already word aligned, then the immediate value has to be word-aligned as well. However, it makes no sense to make the immediate word-aligned because we would be wasting low two bits by forcing them to be 00.
  • Now we have a 32 bit relative offset. Add this value to PC + 4 and that is your branch address.

Branch address calculation


2. Jump Address Calculation

For Jump instruction MIPS has only 26 bits to determine Jump location. Jumps are relative to PC in MIPS. Like branch, immediate jump value needs to be word-aligned; therefore, we need to multiply 26 bit address with four.

Again step by step:

  • Multiply 26 bit value with 4.
  • Since we are jumping relative to PC+4 value, concatenate first four bits of PC+4 value to left of our jump address.
  • Resulting address is the jump value.

In other words, replace the lower 28 bits of the PC + 4 with the lower 26 bits of the fetched instruction shifted left by 2 bits.

enter image description here

Jumps are region-relative to the branch-delay slot, not necessarily the branch itself. In the diagram above, PC has already advanced to the branch delay slot before the jump calculation. (In a classic-RISC 5 stage pipeline, the BD was fetched in the same cycle the jump is decoded, so that PC+4 next instruction address is already available for jumps as well as branches, and calculating relative to the jump's own address would have required extra work to save that address.)

Source: Bilkent University CS 224 Course Slides

How to wait until an element exists?

You can try this:

const wait_until_element_appear = setInterval(() => {
    if ($(element).length !== 0) {
        // some code
        clearInterval(wait_until_element_appear);
    }
}, 0);

This solution works very good for me

explode string in jquery

if your input's id is following

<input type='text'  id='kg_row1' >

then you can get explode/split the above with the following function of split in jquery

  var kg_id = $(this).attr("id");
  var getvalues =kg_id.split("_");
  var id = getvalues[1];

How to read file from res/raw by name

Here are two approaches you can read raw resources using Kotlin.

You can get it by getting the resource id. Or, you can use string identifier in which you can programmatically change the filename with incrementation.

Cheers mate

// R.raw.data_post

this.context.resources.openRawResource(R.raw.data_post)
this.context.resources.getIdentifier("data_post", "raw", this.context.packageName)