Programs & Examples On #Uiwebviewdelegate

How to get element by classname or id

@tasseKATT's Answer is great, but if you don't want to make a directive, why not use $document?

.controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  var dumb = function (id) {
  var queryResult = $document[0].getElementById(id)
  var wrappedID = angular.element(queryResult);
  return wrappedID;
};

PLUNKR

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

SELECT * FROM TABLE
WHERE DATE BETWEEN '09/16/2010 05:00:00' and '09/21/2010 09:00:00'

How to get the class of the clicked element?

Here's a quick jQuery example that adds a click event to each "li" tag, and then retrieves the class attribute for the clicked element. Hope it helps.

$("li").click(function() {
   var myClass = $(this).attr("class");
   alert(myClass);
});

Equally, you don't have to wrap the object in jQuery:

$("li").click(function() {
   var myClass = this.className;
   alert(myClass);
});

And in newer browsers you can get the full list of class names:

$("li").click(function() {
   var myClasses = this.classList;
   alert(myClasses.length + " " + myClasses[0]);
});

You can emulate classList in older browsers using myClass.split(/\s+/);

How can I create a table with borders in Android?

I have to agree with Brad. That was an awful answer. The Android documentation states that TableLayout containers do not display border lines, so sending them to the Android site wont help them a bit. I was able to find a "dirty" solution on droidnova, which involves setting a background color for the TableLayout, then setting a different background color for the TableRow and adding layout_margin to the row. I'm not fond of this solution, but it does work for row borders. I guess you could do the same thing with the items composing each "cell" item but I haven't verified.

An example similar to the one on DroidNova:

<TableLayout android:background="#000000"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
  <TableRow android:background="#FFFFFF"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_margin="1dp">
     ...
  </TableRow>
</TableLayout>

Get paragraph text inside an element

Try this:

<li onclick="myfunction(this)">

function myfunction(li) {
    var TextInsideLi = li.getElementsByTagName('p')[0].innerHTML;
}

Live demo

How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting

For fitting y = A + B log x, just fit y against (log x).

>>> x = numpy.array([1, 7, 20, 50, 79])
>>> y = numpy.array([10, 19, 30, 35, 51])
>>> numpy.polyfit(numpy.log(x), y, 1)
array([ 8.46295607,  6.61867463])
# y ˜ 8.46 log(x) + 6.62

For fitting y = AeBx, take the logarithm of both side gives log y = log A + Bx. So fit (log y) against x.

Note that fitting (log y) as if it is linear will emphasize small values of y, causing large deviation for large y. This is because polyfit (linear regression) works by minimizing ?i (?Y)2 = ?i (YiYi)2. When Yi = log yi, the residues ?Yi = ?(log yi) ˜ ?yi / |yi|. So even if polyfit makes a very bad decision for large y, the "divide-by-|y|" factor will compensate for it, causing polyfit favors small values.

This could be alleviated by giving each entry a "weight" proportional to y. polyfit supports weighted-least-squares via the w keyword argument.

>>> x = numpy.array([10, 19, 30, 35, 51])
>>> y = numpy.array([1, 7, 20, 50, 79])
>>> numpy.polyfit(x, numpy.log(y), 1)
array([ 0.10502711, -0.40116352])
#    y ˜ exp(-0.401) * exp(0.105 * x) = 0.670 * exp(0.105 * x)
# (^ biased towards small values)
>>> numpy.polyfit(x, numpy.log(y), 1, w=numpy.sqrt(y))
array([ 0.06009446,  1.41648096])
#    y ˜ exp(1.42) * exp(0.0601 * x) = 4.12 * exp(0.0601 * x)
# (^ not so biased)

Note that Excel, LibreOffice and most scientific calculators typically use the unweighted (biased) formula for the exponential regression / trend lines. If you want your results to be compatible with these platforms, do not include the weights even if it provides better results.


Now, if you can use scipy, you could use scipy.optimize.curve_fit to fit any model without transformations.

For y = A + B log x the result is the same as the transformation method:

>>> x = numpy.array([1, 7, 20, 50, 79])
>>> y = numpy.array([10, 19, 30, 35, 51])
>>> scipy.optimize.curve_fit(lambda t,a,b: a+b*numpy.log(t),  x,  y)
(array([ 6.61867467,  8.46295606]), 
 array([[ 28.15948002,  -7.89609542],
        [ -7.89609542,   2.9857172 ]]))
# y ˜ 6.62 + 8.46 log(x)

For y = AeBx, however, we can get a better fit since it computes ?(log y) directly. But we need to provide an initialize guess so curve_fit can reach the desired local minimum.

>>> x = numpy.array([10, 19, 30, 35, 51])
>>> y = numpy.array([1, 7, 20, 50, 79])
>>> scipy.optimize.curve_fit(lambda t,a,b: a*numpy.exp(b*t),  x,  y)
(array([  5.60728326e-21,   9.99993501e-01]),
 array([[  4.14809412e-27,  -1.45078961e-08],
        [ -1.45078961e-08,   5.07411462e+10]]))
# oops, definitely wrong.
>>> scipy.optimize.curve_fit(lambda t,a,b: a*numpy.exp(b*t),  x,  y,  p0=(4, 0.1))
(array([ 4.88003249,  0.05531256]),
 array([[  1.01261314e+01,  -4.31940132e-02],
        [ -4.31940132e-02,   1.91188656e-04]]))
# y ˜ 4.88 exp(0.0553 x). much better.

comparison of exponential regression

jquery clear input default value

You may use this..

<body>
    <form method="" action="">
        <input type="text" name="email" class="input" />
        <input type="submit" value="Sign Up" class="button" />
    </form>
</body>

<script>
    $(document).ready(function() {
        $(".input").val("Email Address");
        $(".input").on("focus", function() {
            $(".input").val("");
        });
        $(".button").on("click", function(event) {
            $(".input").val("");
        });
    });
</script>

Talking of your own code, the problem is that the attr api of jquery is set by

$('.input').attr('value','Email Adress');

and not as you have done:

$('.input').attr('value') = 'Email address';

How to get error message when ifstream open fails

You can also throw a std::system_error as shown in the test code below. This method seems to produce more readable output than f.exception(...).

#include <exception> // <-- requires this
#include <fstream>
#include <iostream>

void process(const std::string& fileName) {
    std::ifstream f;
    f.open(fileName);

    // after open, check f and throw std::system_error with the errno
    if (!f)
        throw std::system_error(errno, std::system_category(), "failed to open "+fileName);

    std::clog << "opened " << fileName << std::endl;
}

int main(int argc, char* argv[]) {
    try {
        process(argv[1]);
    } catch (const std::system_error& e) {
        std::clog << e.what() << " (" << e.code() << ")" << std::endl;
    }
    return 0;
}

Example output (Ubuntu w/clang):

$ ./test /root/.profile
failed to open /root/.profile: Permission denied (system:13)
$ ./test missing.txt
failed to open missing.txt: No such file or directory (system:2)
$ ./test ./test
opened ./test
$ ./test $(printf '%0999x')
failed to open 000...000: File name too long (system:36)

What Ruby IDE do you prefer?

E Text Editor is great (TextMate compatible sort-of-clone for Windows).

html div onclick event

put your jquery function inside ready function for call click event:

$(document).ready(function() {

  $("#ancherComplaint").click(function () {
     alert($(this).attr("id"));
  });

});

What is the use of ByteBuffer in Java?

Here is a great article explaining ByteBuffer benefits. Following are the key points in the article:

  • First advantage of a ByteBuffer irrespective of whether it is direct or indirect is efficient random access of structured binary data (e.g., low-level IO as stated in one of the answers). Prior to Java 1.4, to read such data one could use a DataInputStream, but without random access.

Following are benefits specifically for direct ByteBuffer/MappedByteBuffer. Note that direct buffers are created outside of heap:

  1. Unaffected by gc cycles: Direct buffers won't be moved during garbage collection cycles as they reside outside of heap. TerraCota's BigMemory caching technology seems to rely heavily on this advantage. If they were on heap, it would slow down gc pause times.

  2. Performance boost: In stream IO, read calls would entail system calls, which require a context-switch between user to kernel mode and vice versa, which would be costly especially if file is being accessed constantly. However, with memory-mapping this context-switching is reduced as data is more likely to be found in memory (MappedByteBuffer). If data is available in memory, it is accessed directly without invoking OS, i.e., no context-switching.

Note that MappedByteBuffers are very useful especially if the files are big and few groups of blocks are accessed more frequently.

  1. Page sharing: Memory mapped files can be shared between processes as they are allocated in process's virtual memory space and can be shared across processes.

Unable to copy a file from obj\Debug to bin\Debug

I solved this by killing XDesProc which had a handle on the DLL it couldn't delete.

Best way to use PHP to encrypt and decrypt passwords?

This will only give you marginal protection. If the attacker can run arbitrary code in your application they can get at the passwords in exactly the same way your application can. You could still get some protection from some SQL injection attacks and misplaced db backups if you store a secret key in a file and use that to encrypt on the way to the db and decrypt on the way out. But you should use bindparams to completely avoid the issue of SQL injection.

If decide to encrypt, you should use some high level crypto library for this, or you will get it wrong. You'll have to get the key-setup, message padding and integrity checks correct, or all your encryption effort is of little use. GPGME is a good choice for one example. Mcrypt is too low level and you will probably get it wrong.

Unable to find the requested .Net Framework Data Provider. It may not be installed. - when following mvc3 asp.net tutorial

I had the same issue. I checked the version of System.Data.SqlServerCe in C:\Windows\assembly. It was 3.5.1.0. So I installed version 4.0.0 from below link (x86) and works fine.

http://www.microsoft.com/download/en/details.aspx?id=17876

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

You should install node.js with nvm, because that way you do not have to provide superuser privileges when installing global packages (you can simply execute "npm install -g packagename" without prepending 'sudo').

Brew is fantastic for other things, however. I tend to be biased towards Bower whenever I have the option to install something with Bower.

Django: Get list of model fields?

As most of answers are outdated I'll try to update you on Django 2.2 Here posts- your app (posts, blog, shop, etc.)

1) From model link: https://docs.djangoproject.com/en/stable/ref/models/meta/

from posts.model import BlogPost

all_fields = BlogPost._meta.fields
#or
all_fields = BlogPost._meta.get_fields()

Note that:

all_fields=BlogPost._meta.get_fields()

Will also get some relationships, which, for ex: you can not display in a view.
As in my case:

Organisation._meta.fields
(<django.db.models.fields.AutoField: id>, <django.db.models.fields.DateField: created>...

and

Organisation._meta.get_fields()
(<ManyToOneRel: crm.activity>, <django.db.models.fields.AutoField: id>, <django.db.models.fields.DateField: created>...

2) From instance

from posts.model import BlogPost

bp = BlogPost()
all_fields = bp._meta.fields

3) From parent model

Let's suppose that we have Post as the parent model and you want to see all the fields in a list, and have the parent fields to be read-only in Edit mode.

from django.contrib import admin
from posts.model import BlogPost 

@admin.register(BlogPost)
class BlogPost(admin.ModelAdmin):
    all_fields = [f.name for f in Organisation._meta.fields]
    parent_fields = BlogPost.get_deferred_fields(BlogPost)

    list_display = all_fields
    read_only = parent_fields

What is the default root pasword for MySQL 5.7

MySQL 5.7 changed the secure model: now MySQL root login requires a sudo

The simplest (and safest) solution will be create a new user and grant required privileges.

1. Connect to mysql

sudo mysql --user=root mysql

2. Create a user for phpMyAdmin

CREATE USER 'phpmyadmin'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'phpmyadmin'@'localhost' WITH GRANT OPTION;
FLUSH PRIVILEGES;

Reference - https://askubuntu.com/questions/763336/cannot-enter-phpmyadmin-as-root-mysql-5-7

How to search a string in a single column (A) in excel using VBA

Below are two methods that are superior to looping. Both handle a "no-find" case.

  1. The VBA equivalent of a normal function VLOOKUP with error-handling if the variable doesn't exist (INDEX/MATCH may be a better route than VLOOKUP, ie if your two columns A and B were in reverse order, or were far apart)
  2. VBAs FIND method (matching a whole string in column A given I use the xlWhole argument)

    Sub Method1()
    Dim strSearch As String
    Dim strOut As String
    Dim bFailed As Boolean
    
    strSearch = "trees"
    
    On Error Resume Next
    strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
    If Err.Number <> 0 Then bFailed = True
    On Error GoTo 0
    
    If Not bFailed Then
    MsgBox "corresponding value is " & vbNewLine & strOut
    Else
    MsgBox strSearch & " not found"
    End If
    End Sub
    
    Sub Method2()
        Dim rng1 As Range
        Dim strSearch As String
        strSearch = "trees"
        Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
        If Not rng1 Is Nothing Then
            MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
        Else
            MsgBox strSearch & " not found"
        End If
    End Sub
    

ReactJS - Add custom event listener to component

If you need to handle DOM events not already provided by React you have to add DOM listeners after the component is mounted:

Update: Between React 13, 14, and 15 changes were made to the API that affect my answer. Below is the latest way using React 15 and ES7. See answer history for older versions.

class MovieItem extends React.Component {

  componentDidMount() {
    // When the component is mounted, add your DOM listener to the "nv" elem.
    // (The "nv" elem is assigned in the render function.)
    this.nv.addEventListener("nv-enter", this.handleNvEnter);
  }

  componentWillUnmount() {
    // Make sure to remove the DOM listener when the component is unmounted.
    this.nv.removeEventListener("nv-enter", this.handleNvEnter);
  }

  // Use a class arrow function (ES7) for the handler. In ES6 you could bind()
  // a handler in the constructor.
  handleNvEnter = (event) => {
    console.log("Nv Enter:", event);
  }

  render() {
    // Here we render a single <div> and toggle the "aria-nv-el-current" attribute
    // using the attribute spread operator. This way only a single <div>
    // is ever mounted and we don't have to worry about adding/removing
    // a DOM listener every time the current index changes. The attrs 
    // are "spread" onto the <div> in the render function: {...attrs}
    const attrs = this.props.index === 0 ? {"aria-nv-el-current": true} : {};

    // Finally, render the div using a "ref" callback which assigns the mounted 
    // elem to a class property "nv" used to add the DOM listener to.
    return (
      <div ref={elem => this.nv = elem} aria-nv-el {...attrs} className="menu_item nv-default">
        ...
      </div>
    );
  }

}

Example on Codepen.io

Setting graph figure size

Write it as a one-liner:

figure('position', [0, 0, 200, 500])  % create new figure with specified size  

enter image description here

sql use statement with variable

I case that someone need a solution for this, this is one:

if you use a dynamic USE statement all your query need to be dynamic, because it need to be everything in the same context.

You can try with SYNONYM, is basically an ALIAS to a specific Table, this SYNONYM is inserted into the sys.synonyms table so you have access to it from any context

Look this static statement:

CREATE SYNONYM MASTER_SCHEMACOLUMNS FOR Master.INFORMATION_SCHEMA.COLUMNS
SELECT * FROM MASTER_SCHEMACOLUMNS

Now dynamic:

DECLARE @SQL VARCHAR(200)
DECLARE @CATALOG VARCHAR(200) = 'Master'

IF EXISTS(SELECT * FROM  sys.synonyms s WHERE s.name = 'CURRENT_SCHEMACOLUMNS')
BEGIN
DROP SYNONYM CURRENT_SCHEMACOLUMNS
END

SELECT @SQL = 'CREATE SYNONYM CURRENT_SCHEMACOLUMNS FOR '+ @CATALOG +'.INFORMATION_SCHEMA.COLUMNS';
EXEC sp_sqlexec @SQL

--Your not dynamic Code
SELECT * FROM CURRENT_SCHEMACOLUMNS

Now just change the value of @CATALOG and you will be able to list the same table but from different catalog.

How to check for Is not Null And Is not Empty string in SQL server?

Just check: where value > '' -- not null and not empty

-- COLUMN CONTAINS A VALUE (ie string not null and not empty) :
-- (note: "<>" gives a different result than ">")
select iif(null    > '', 'true', 'false'); -- false (null)
select iif(''      > '', 'true', 'false'); -- false (empty string)
select iif(' '     > '', 'true', 'false'); -- false (space)
select iif('    '  > '', 'true', 'false'); -- false (tab)
select iif('
'                  > '', 'true', 'false'); -- false (newline)
select iif('xxx'   > '', 'true', 'false'); -- true
--
--
-- NOTE - test that tab and newline is processed as expected:
select 'x   x' -- tab
select 'x

x' -- newline

SQL Statement with multiple SETs and WHEREs

NO!

You'll need to handle those individually

Update [table]
Set ID = 111111259
WHERE ID = 2555

Update [table]
Set ID = 111111261
WHERE ID = 2724

--...

Why does SSL handshake give 'Could not generate DH keypair' exception?

It is possible that you have incorrect Maven dependencies. You must find these libraries in Maven dependency hierarchy:

bcprov-jdk14, bcpkix-jdk14, bcmail-jdk14

If you have these dependencies that is the error, and you should do this:

Add the dependency:

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcmail-jdk15on</artifactId>
    <version>1.59</version>
</dependency>

Exclude these dependencies from the artifact that included the wrong dependencies, in my case it is:

<dependency>
    <groupId>com.lowagie</groupId>
    <artifactId>itext</artifactId>
    <version>2.1.7</version>
    <exclusions>
        <exclusion>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bctsp-jdk14</artifactId>                
        </exclusion>
        <exclusion>
            <groupId>bouncycastle</groupId>
            <artifactId>bcprov-jdk14</artifactId>               
        </exclusion>
        <exclusion>
            <groupId>bouncycastle</groupId>
            <artifactId>bcmail-jdk14</artifactId>               
        </exclusion>
    </exclusions>       
</dependency>

How to enter a formula into a cell using VBA?

I would do it like this:

Worksheets("EmployeeCosts").Range("B" & var1a).Formula = _
Replace("=SUM(H5:H{SOME_VAR})","{SOME_VAR}",var1a)

In case you have some more complex formula it will be handy

Convert a Unix timestamp to time in JavaScript

UNIX timestamp is number of seconds since 00:00:00 UTC on January 1, 1970 (according to Wikipedia).

Argument of Date object in Javascript is number of miliseconds since 00:00:00 UTC on January 1, 1970 (according to W3Schools Javascript documentation).

See code below for example:

    function tm(unix_tm) {
        var dt = new Date(unix_tm*1000);
        document.writeln(dt.getHours() + '/' + dt.getMinutes() + '/' + dt.getSeconds() + ' -- ' + dt + '<br>');

    }

tm(60);
tm(86400);

gives:

1/1/0 -- Thu Jan 01 1970 01:01:00 GMT+0100 (Central European Standard Time)
1/0/0 -- Fri Jan 02 1970 01:00:00 GMT+0100 (Central European Standard Time)

Button Width Match Parent

The size attribute can be provided using ButtonTheme with minWidth: double.infinity

ButtonTheme(
  minWidth: double.infinity,
  child: MaterialButton(
    onPressed: () {},
    child: Text('Raised Button'),
  ),
),

or after https://github.com/flutter/flutter/pull/19416 landed

MaterialButton(
  onPressed: () {},
  child: SizedBox.expand(
    width: double.infinity, 
    child: Text('Raised Button'),
  ),
),

How do I find out if the GPS of an Android device is enabled

This method will use the LocationManager service.

Source Link

//Check GPS Status true/false
public static boolean checkGPSStatus(Context context){
    LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE );
    boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    return statusOfGPS;
};

Largest and smallest number in an array

    public int MinimumValue { get; private set; }
    public int MaxmimumValue { get; private set; }

    public void num()
    {
        int[] array = { 12, 56, 89, 65, 61, 36, 45, 23 };
        MaxmimumValue = array[0];
        MinimumValue = array[0];

        foreach (int num in array)

        {

            if (num > MaxmimumValue) MaxmimumValue = num;
            if (num < MinimumValue) MinimumValue = num;
        }
        Console.WriteLine(MinimumValue);
        Console.WriteLine(MaxmimumValue);
    }

Getting cursor position in Python

sudo add-apt-repository ppa:deadsnakes
sudo apt-get update
sudo apt-get install python3.5 python3.5-tk
# or 2.7, 3.6 etc
# sudo apt-get install python2.7 python2.7-tk
# mouse_position.py
import Tkinter
p=Tkinter.Tk()
print(p.winfo_pointerxy()

Or with one-liner from the command line:

python -c "import Tkinter; p=Tkinter.Tk(); print(p.winfo_pointerxy())"
(1377, 379)

How to unlock android phone through ADB

Below commands works both when screen is on and off

To lock the screen:

adb shell input keyevent 82 && adb shell input keyevent 26 && adb shell input keyevent 26

To lock the screen and turn it off

adb shell input keyevent 82 && adb shell input keyevent 26

To unlock the screen without pass

adb shell input keyevent 82 && adb shell input keyevent 66

To unlock the screen that has pass 1234

adb shell input keyevent 82 && adb shell input text 1234 && adb shell input keyevent 66

Kill some processes by .exe file name

My solution is to use Process.GetProcess() for listing all the processes.

By filtering them to contain the processes I want, I can then run Process.Kill() method to stop them:

var chromeDriverProcesses = Process.GetProcesses().
    Where(pr => pr.ProcessName == "chromedriver"); // without '.exe'
    
foreach (var process in chromeDriverProcesses)
{
     process.Kill();
}

Update:

In case if want to use async approach with some useful recent methods from the C# 8 (Async Enumerables), then check this out:

const string processName = "chromedriver"; // without '.exe'
await Process.GetProcesses()
             .Where(pr => pr.ProcessName == processName)
             .ToAsyncEnumerable()
             .ForEachAsync(p => p.Kill());

Note: using async methods doesn't always mean code will run faster, but it will not waste the CPU time and prevent the foreground thread from hanging while doing the operations. In any case, you need to think about what version you might want.

Is it possible to decompile an Android .apk file?

Are the users able to convert the apk file of my application back to the actual code?

yes.

People can use various tools to:

  • analysis: your apk
  • decode/hack your apk
    • using FDex2 to dump out dex file
      • then using dex2jar to convert to jar
        • then using jadx to conver to java source code

If they do - is there any way to prevent this?

yes. Several (can combined) ways to prevent (certain degree) this:

  • low level: code obfuscation
    • using Android ProGuard
  • high level: use android harden scenario

More details can refer my Chinese tutorial: ??????????

How do you check if a variable is an array in JavaScript?

Something I just came up with:

if (item.length) //This is an array else //not an array

exception in initializer error in java when using Netbeans

Make sure the project does not have any errors. Delete the project from workspace(make the workspace a different directory from the git folder) and import again.

Print an integer in binary format in Java

Enter any decimal number as an input. After that we operations like modulo and division to convert the given input into binary number. Here is the source code of the Java Program to Convert Integer Values into Binary and the bits number of this binary for his decimal number. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int integer ;
        String binary = "";    //   here we count "" or null 
                               //   just String binary = null;
        System.out.print("Enter the binary Number: ");
        integer = sc.nextInt();

        while(integer>0)
        {
            int x = integer % 2;
            binary = x + binary;
            integer = integer / 2;  
        }
        System.out.println("Your binary number is : "+binary);
        System.out.println("your binary length : " + binary.length());
    }
}

How to set an image as a background for Frame in Swing GUI of java?

The Background Panel entry shows a couple of different ways depending on your requirements.

Java Object Null Check for method

public static double calculateInventoryTotal(Book[] arrayBooks) {

    final AtomicReference<BigDecimal> total = new AtomicReference<>(BigDecimal.ZERO);
    Optional.ofNullable(arrayBooks).map(Arrays::asList).ifPresent(books -> books.forEach(book -> total.accumulateAndGet(book.getPrice(), BigDecimal::add)));
    return total.get().doubleValue();

}

Get $_POST from multiple checkboxes

It's pretty simple. Pay attention and you'll get it right away! :)

You will create a html array, which will be then sent to php array. Your html code will look like this:

<input type="checkbox" name="check_list[1]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[2]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[3]" alt="Checkbox" value="checked">

Where [1] [2] [3] are the IDs of your messages, meaning that you will echo your $row['Report ID'] in their place.

Then, when you submit the form, your PHP array will look like this:

print_r($check_list)

[1] => checked [3] => checked

Depending on which were checked and which were not.

I'm sure you can continue from this point forward.

convert NSDictionary to NSString

if you like to use for URLRequest httpBody

extension Dictionary {

    func toString() -> String? {
        return (self.compactMap({ (key, value) -> String in
            return "\(key)=\(value)"
        }) as Array).joined(separator: "&")
    }

}

// print: Fields=sdad&ServiceId=1222

How do I call an Angular.js filter with multiple arguments?

If you want to call your filter inside ng-options the code will be as follows:

ng-options="productSize as ( productSize | sizeWithPrice: product )  for productSize in productSizes track by productSize.id"

where the filter is sizeWithPriceFilter and it has two parameters product and productSize

What is the iPhone 4 user-agent?

Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7

Print the contents of a DIV

I know this is an old question, but I solved this problem w jQuery.

function printContents(id) {
    var contents = $("#"+id).html();

    if ($("#printDiv").length == 0) {
      var printDiv = null;
      printDiv = document.createElement('div');
      printDiv.setAttribute('id','printDiv');
      printDiv.setAttribute('class','printable');
      $(printDiv).appendTo('body');
    }

    $("#printDiv").html(contents);

    window.print();

    $("#printDiv").remove();
}

CSS

  @media print {
    .non-printable, .fancybox-outer { display: none; }
    .printable, #printDiv { 
        display: block; 
        font-size: 26pt;
    }
  }

Add rows to CSV File in powershell

I know this is an old thread but it was the first I found when searching. The += solution did not work for me. The code that I did get to work is as below.

#this bit creates the CSV if it does not already exist
$headers = "Name", "Primary Type"
$psObject = New-Object psobject
foreach($header in $headers)
{
 Add-Member -InputObject $psobject -MemberType noteproperty -Name $header -Value ""
}
$psObject | Export-Csv $csvfile -NoTypeInformation

#this bit appends a new row to the CSV file
$bName = "My Name"
$bPrimaryType = "My Primary Type"
    $hash = @{
             "Name" =  $bName
             "Primary Type" = $bPrimaryType
              }

$newRow = New-Object PsObject -Property $hash
Export-Csv $csvfile -inputobject $newrow -append -Force

I was able to use this as a function to loop through a series of arrays and enter the contents into the CSV file.

It works in powershell 3 and above.

NuGet Package Restore Not Working

If anything else didn't work, try:

  1. Close Project.
  2. Delete packages folder in your solution folder.
  3. Open Project again and restore Nugget Packages again.

Worked for me and it's easy to try.

How to center a subview of UIView

In c# or Xamarin.ios, we can use like this

imageView.Center = new CGPoint(tempView.Frame.Size.Width / 2, tempView.Frame.Size.Height / 2);

HTML span align center not working?

Please use the following style. margin:auto normally used to center align the content. display:table is needed for span element

<span style="margin:auto; display:table; border:1px solid red;">
    This is some text in a div element!
</span>

Filter df when values matches part of a string in pyspark

Spark 2.2 onwards

df.filter(df.location.contains('google.com'))

Spark 2.2 documentation link


Spark 2.1 and before

You can use plain SQL in filter

df.filter("location like '%google.com%'")

or with DataFrame column methods

df.filter(df.location.like('%google.com%'))

Spark 2.1 documentation link

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

You will also get 'root element is missing' when the BOM strikes :). BOM = byte order mark. This is an extra character that gets added to the start of a file when it is saved with the wrong encoding.
This can happen sometimes in Visual Studio when working with XML files. You can either code something to remove it from all your files, or if you know which file it is you can force visual studio to save it with a specific encoding (utf-8 or ascii IIRC).

If you open the file in an editor other than VS (try notepad++), you will see two funny characters before the <? xml declaration.

To fix this in VS, open the file in VS and then depending on the version of VS

  • File > Advanced Save Options > choose an appropriate encoding
  • File > Save As > keep the filename, click the drop-down arrow on the right side of the save button to select an encoding

jQuery get the image src

When dealing with the HTML DOM (ie. this), the array selector [0] must be used to retrieve the jQuery element from the Javascript array.

$(this)[0].getAttribute('src');

Remove duplicates in the list using linq

This is how I was able to group by with Linq. Hope it helps.

var query = collection.GroupBy(x => x.title).Select(y => y.FirstOrDefault());

How to access the last value in a vector?

The xts package provides a last function:

library(xts)
a <- 1:100
last(a)
[1] 100

Where to place JavaScript in an HTML file?

With 100k of Javascript, you should never put it inside the file. Use an external script Javascript file. There's no chance in hell you'll only ever use this amount of code in only one HTML page. Likely you're asking where you should load the Javascript file, for this you've received satisfactory answers already.

But I'd like to point out that commonly, modern browsers accept gzipped Javascript files! Just gzip the x.js file to x.js.gz, and point to that in the src attribute. It doesn't work on the local filesystem, you need a webserver for it to work. But the savings in transferred bytes can be enormous.

I've successfully tested it in Firefox 3, MSIE 7, Opera 9, and Google Chrome. It apparently doesn't work this way in Safari 3.

For more info, see this blog post, and another very ancient page that nevertheless is useful because it points out that the webserver can detect whether a browser can accept gzipped Javascript, or not. If your server side can dynamically choose to send the gzipped or the plain text, you can make the page usable in all web browsers.

How to create many labels and textboxes dynamically depending on the value of an integer variable?

I would create a user control which holds a Label and a Text Box in it and simply create instances of that user control 'n' times. If you want to know a better way to do it and use properties to get access to the values of Label and Text Box from the user control, please let me know.

Simple way to do it would be:

int n = 4; // Or whatever value - n has to be global so that the event handler can access it

private void btnDisplay_Click(object sender, EventArgs e)
{
    TextBox[] textBoxes = new TextBox[n];
    Label[] labels = new Label[n];

    for (int i = 0; i < n; i++)
    {
        textBoxes[i] = new TextBox();
        // Here you can modify the value of the textbox which is at textBoxes[i]

        labels[i] = new Label();
        // Here you can modify the value of the label which is at labels[i]
    }

    // This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
    for (int i = 0; i < n; i++)
    {
        this.Controls.Add(textBoxes[i]);
        this.Controls.Add(labels[i]);
    }
}

The code above assumes that you have a button btnDisplay and it has a onClick event assigned to btnDisplay_Click event handler. You also need to know the value of n and need a way of figuring out where to place all controls. Controls should have a width and height specified as well.

To do it using a User Control simply do this.

Okay, first of all go and create a new user control and put a text box and label in it.

Lets say they are called txtSomeTextBox and lblSomeLabel. In the code behind add this code:

public string GetTextBoxValue() 
{ 
    return this.txtSomeTextBox.Text; 
} 

public string GetLabelValue() 
{ 
    return this.lblSomeLabel.Text; 
} 

public void SetTextBoxValue(string newText) 
{ 
    this.txtSomeTextBox.Text = newText; 
} 

public void SetLabelValue(string newText) 
{ 
    this.lblSomeLabel.Text = newText; 
}

Now the code to generate the user control will look like this (MyUserControl is the name you have give to your user control):

private void btnDisplay_Click(object sender, EventArgs e)
{
    MyUserControl[] controls = new MyUserControl[n];

    for (int i = 0; i < n; i++)
    {
        controls[i] = new MyUserControl();

        controls[i].setTextBoxValue("some value to display in text");
        controls[i].setLabelValue("some value to display in label");
        // Now if you write controls[i].getTextBoxValue() it will return "some value to display in text" and controls[i].getLabelValue() will return "some value to display in label". These value will also be displayed in the user control.
    }

    // This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
    for (int i = 0; i < n; i++)
    {
        this.Controls.Add(controls[i]);
    }
}

Of course you can create more methods in the usercontrol to access properties and set them. Or simply if you have to access a lot, just put in these two variables and you can access the textbox and label directly:

public TextBox myTextBox;
public Label myLabel;

In the constructor of the user control do this:

myTextBox = this.txtSomeTextBox;
myLabel = this.lblSomeLabel;

Then in your program if you want to modify the text value of either just do this.

control[i].myTextBox.Text = "some random text"; // Same applies to myLabel

Hope it helped :)

How do I download and save a file locally on iOS using objective C?

I would use an asynchronous access using a completion block.

This example saves the Google logo to the document directory of the device. (iOS 5+, OSX 10.7+)

NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentDir stringByAppendingPathComponent:@"GoogleLogo.png"];

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.google.com/images/srpr/logo11w.png"]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (error) {
        NSLog(@"Download Error:%@",error.description);
    }
    if (data) {
        [data writeToFile:filePath atomically:YES];
        NSLog(@"File is saved to %@",filePath);
    }
}];

How do I use WebRequest to access an SSL encrypted site using https?

This link will be of interest to you: http://msdn.microsoft.com/en-us/library/ds8bxk2a.aspx

For http connections, the WebRequest and WebResponse classes use SSL to communicate with web hosts that support SSL. The decision to use SSL is made by the WebRequest class, based on the URI it is given. If the URI begins with "https:", SSL is used; if the URI begins with "http:", an unencrypted connection is used.

SHOW PROCESSLIST in MySQL command: sleep

It's not a query waiting for connection; it's a connection pointer waiting for the timeout to terminate.

It doesn't have an impact on performance. The only thing it's using is a few bytes as every connection does.

The really worst case: It's using one connection of your pool; If you would connect multiple times via console client and just close the client without closing the connection, you could use up all your connections and have to wait for the timeout to be able to connect again... but this is highly unlikely :-)

See MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"? and https://dba.stackexchange.com/questions/1558/how-long-is-too-long-for-mysql-connections-to-sleep for more information.

Java 8 - Difference between Optional.flatMap and Optional.map

They both take a function from the type of the optional to something.

map() applies the function "as is" on the optional you have:

if (optional.isEmpty()) return Optional.empty();
else return Optional.of(f(optional.get()));

What happens if your function is a function from T -> Optional<U>?
Your result is now an Optional<Optional<U>>!

That's what flatMap() is about: if your function already returns an Optional, flatMap() is a bit smarter and doesn't double wrap it, returning Optional<U>.

It's the composition of two functional idioms: map and flatten.

Should I put #! (shebang) in Python scripts, and what form should it take?

Absolute vs Logical Path:

This is really a question about whether the path to the Python interpreter should be absolute or Logical (/usr/bin/env) in respect to portability.

Encountering other answers on this and other Stack sites which talked about the issue in a general way without supporting proofs, I've performed some really, REALLY, granular testing & analysis on this very question on the unix.stackexchange.com. Rather than paste that answer here, I'll point those interested to the comparative analysis to that answer:

https://unix.stackexchange.com/a/566019/334294

Being a Linux Engineer, my goal is always to provide the most suitable, optimized hosts for my developer clients, so the issue of Python environments was something I really needed a solid answer to. My view after the testing was that the logical path in the she-bang was the better of the (2) options.

Rest-assured. Is it possible to extract value from request json?

You can also do like this if you're only interested in extracting the "user_id":

String userId = 
given().
        contentType("application/json").
        body(requestBody).
when().
        post("/admin").
then().
        statusCode(200).
extract().
        path("user_id");

In its simplest form it looks like this:

String userId = get("/person").path("person.userId");

CURL and HTTPS, "Cannot resolve host"

I had the same problem. Coudn't resolve google.com. There was a bug somewhere in php fpm, which i am using. Restarting php-fpm solved it for me.

Python syntax for "if a or b or c but not all of them"

If you don't mind being a bit cryptic you can simly roll with 0 < (a + b + c) < 3 which will return true if you have between one and two true statements and false if all are false or none is false.

This also simplifies if you use functions to evaluate the bools as you only evaluate the variables once and which means you can write the functions inline and do not need to temporarily store the variables. (Example: 0 < ( a(x) + b(x) + c(x) ) < 3.)

Android Error [Attempt to invoke virtual method 'void android.app.ActionBar' on a null object reference]

You should try this one. I think it will work.

    Toolbar toolbar = findViewById(R.id.toolbar1);
    setSupportActionBar(toolbar);

    mDrawerLayout = findViewById(R.id.drawer_layout);
    mDrawerLayout = findViewById(R.id.drawer_layout);
    mDrawerLayout.setDrawerShadow(R.drawable.rectagle_with_black_outer,
            GravityCompat.START);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            toolbar, R.string.navigation_drawer_close,
            R.string.navigation_drawer_close) {
        public void onDrawerClosed(View view) {
            invalidateOptionsMenu();
        }

        public void onDrawerOpened(View drawerView) {
            invalidateOptionsMenu();
        }
    };

Container is running beyond memory limits

You should also properly configure the maximum memory allocations for MapReduce. From this HortonWorks tutorial:

[...]

Each machine in our cluster has 48 GB of RAM. Some of this RAM should be >reserved for Operating System usage. On each node, we’ll assign 40 GB RAM for >YARN to use and keep 8 GB for the Operating System

For our example cluster, we have the minimum RAM for a Container (yarn.scheduler.minimum-allocation-mb) = 2 GB. We’ll thus assign 4 GB for Map task Containers, and 8 GB for Reduce tasks Containers.

In mapred-site.xml:

mapreduce.map.memory.mb: 4096

mapreduce.reduce.memory.mb: 8192

Each Container will run JVMs for the Map and Reduce tasks. The JVM heap size should be set to lower than the Map and Reduce memory defined above, so that they are within the bounds of the Container memory allocated by YARN.

In mapred-site.xml:

mapreduce.map.java.opts: -Xmx3072m

mapreduce.reduce.java.opts: -Xmx6144m

The above settings configure the upper limit of the physical RAM that Map and Reduce tasks will use.

To sum it up:

  1. In YARN, you should use the mapreduce configs, not the mapred ones. EDIT: This comment is not applicable anymore now that you've edited your question.
  2. What you are configuring is actually how much you want to request, not what is the max to allocate.
  3. The max limits are configured with the java.opts settings listed above.

Finally, you may want to check this other SO question that describes a similar problem (and solution).

java.lang.IllegalStateException: Fragment not attached to Activity

This error can happen if you are instantiating a fragment that somehow can't be instantiated:

Fragment myFragment = MyFragment.NewInstance();


public classs MyFragment extends Fragment {
  public void onCreate() {
   // Some error here, or anywhere inside the class is preventing it from being instantiated
  }
}

In my case, i have met this when i tried to use:

private String loading = getString(R.string.loading);

Running a cron job on Linux every six hours

Try:

0 */6 * * * command

. * has to

Parsing JSON giving "unexpected token o" error

Response is already parsed, you don't need to parse it again. if you parse it again it will give you "unexpected token o". if you need to get it as string, you could use JSON.stringify()

Change background color of R plot

I use abline() with extremely wide vertical lines to fill the plot space:

abline(v = xpoints, col = "grey90", lwd = 80)

You have to create the frame, then the ablines, and then plot the points so they are visible on top. You can even use a second abline() statement to put thin white or black lines over the grey, if desired.

Example:

xpoints = 1:20
y = rnorm(20)
plot(NULL,ylim=c(-3,3),xlim=xpoints)
abline(v=xpoints,col="gray90",lwd=80)
abline(v=xpoints,col="white")
abline(h = 0, lty = 2) 
points(xpoints, y, pch = 16, cex = 1.2, col = "red")

Can anyone explain what JSONP is, in layman terms?

Say you had some URL that gave you JSON data like:

{'field': 'value'}

...and you had a similar URL except it used JSONP, to which you passed the callback function name 'myCallback' (usually done by giving it a query parameter called 'callback', e.g. http://example.com/dataSource?callback=myCallback). Then it would return:

myCallback({'field':'value'})

...which is not just an object, but is actually code that can be executed. So if you define a function elsewhere in your page called myFunction and execute this script, it will be called with the data from the URL.

The cool thing about this is: you can create a script tag and use your URL (complete with callback parameter) as the src attribute, and the browser will run it. That means you can get around the 'same-origin' security policy (because browsers allow you to run script tags from sources other than the domain of the page).

This is what jQuery does when you make an ajax request (using .ajax with 'jsonp' as the value for the dataType property). E.g.

$.ajax({
  url: 'http://example.com/datasource',
  dataType: 'jsonp',
  success: function(data) {
    // your code to handle data here
  }
});

Here, jQuery takes care of the callback function name and query parameter - making the API identical to other ajax calls. But unlike other types of ajax requests, as mentioned, you're not restricted to getting data from the same origin as your page.

Install mysql-python (Windows)

Just Download mysqlclient from here https://www.lfd.uci.edu/~gohlke/pythonlibs/ be careful while downloading the right version depending on your your python version installed. Then proceed with the import. It worked for me because in my case the error was telling to install Visual Studio C++ 14.0 something which wasted my time and occupied around 10GB of space in my C drive. So recommending installing mysqlclient using pip install mysqlclient

How to make an unaware datetime timezone aware in python

In general, to make a naive datetime timezone-aware, use the localize method:

import datetime
import pytz

unaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0)
aware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0, pytz.UTC)

now_aware = pytz.utc.localize(unaware)
assert aware == now_aware

For the UTC timezone, it is not really necessary to use localize since there is no daylight savings time calculation to handle:

now_aware = unaware.replace(tzinfo=pytz.UTC)

works. (.replace returns a new datetime; it does not modify unaware.)

How can I change the color of a Google Maps marker?

MapIconMaker: a library for Google Maps v2

One way is to use the MapIconMaker(deadlink). There's an example here(deadlink). Google Maps default icons are 20px width and 34px height, so you could use something like this to emulate:

var newIcon = MapIconMaker.createMarkerIcon({width: 20, height: 34, primaryColor: "#0000FF", cornercolor:"#0000FF"});
var marker = new GMarker(map.getCenter(), {icon: newIcon});

You could even wrap it in some function to make things even easier on yourself:

function getIcon(color) {
    return MapIconMaker.createMarkerIcon({width: 20, height: 34, primaryColor: color, cornercolor:color});
}

That's what I personally use for all markers I create. I prefer to have the option to change colors of a whim.

Update: The Hex color of the default icon is "#FE7569". Also, you can setImage on a Marker rather than creating a new Marker with a new icon. So if you want a function to highlight you could go with something like this, using the function above:

function highlightMarker(marker, highlight) {
    var color = "#FE7569";
    if (highlight) {
        color = "#0000FF";
    }
    marker.setImage(getIcon(color).image);
}

StyledMarker: a library for Google Maps v3

Since V2 was replaced by V3 sometime ago I thought I should update this answer. I created a library for custom markers that can be found on the V3 Utility Library here(deadlink). It allows for different colors and shapes, and you can place text on the marker as well. It works by using the Google Charts API which has methods for creating Google Maps type markers. Feel free to look at the source code if you'd rather use the Google Charts API directly.

The thing about that library, however, is that it takes care of defining the clickable regions of these marker images for you, so, for instance, the longer bubble with text will have the clickable regions one expects, like this example(deadlink).

Show only two digit after decimal

Here i will demonstrate you that how to make your decimal number short. Here i am going to make it short upto 4 value after decimal.

  double value = 12.3457652133
  value =Double.parseDouble(new DecimalFormat("##.####").format(value));

How do I configure the proxy settings so that Eclipse can download new plugins?

Manual + disable SOCKS didn't work for me (still tried to use SOCKS and my company proxy refused it),
Native + changed eclipse.ini worked for me

-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient
-Dhttp.proxyHost=myproxy
-Dhttp.proxyPort=8080
-Dhttp.proxyUser=mydomain\myusername
-Dhttp.proxyPassword=mypassword
-Dhttp.nonProxyHosts=localhost|127.0.0.1

These settings require IDE restart (sometimes with -clean -refresh command line options).
https://bugs.eclipse.org/bugs/show_bug.cgi?id=281472


Java8, Eclipse Neon3, slow proxy server:

-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient4
-Dhttp.proxyHost=<proxy>
-Dhttp.proxyPort=8080
-Dhttps.proxyHost=<proxy>
-Dhttps.proxyPort=8080
-DsocksProxyHost=
-DsocksProxyPort=
-Dhttp.proxyUser=<user>
-Dhttp.proxyPassword=<pass>
-Dhttp.nonProxyHosts=localhost|127.0.0.1
-Dorg.eclipse.equinox.p2.transport.ecf.retry=5
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.connectTimeout=15000
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.readTimeout=1000
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.retryAttempts=20
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.closeTimeout=1000
-Dorg.eclipse.ecf.provider.filetransfer.browse.connectTimeout=3000
-Dorg.eclipse.ecf.provider.filetransfer.browse.readTimeout=1000

Android: Getting a file URI from a content URI?

This is an old answer with deprecated and hacky way of overcoming some specific content resolver pain points. Take it with some huge grains of salt and use the proper openInputStream API if at all possible.

You can use the Content Resolver to get a file:// path from the content:// URI:

String filePath = null;
Uri _uri = data.getData();
Log.d("","URI = "+ _uri);                                       
if (_uri != null && "content".equals(_uri.getScheme())) {
    Cursor cursor = this.getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
    cursor.moveToFirst();   
    filePath = cursor.getString(0);
    cursor.close();
} else {
    filePath = _uri.getPath();
}
Log.d("","Chosen path = "+ filePath);

Given final block not properly padded

If you try to decrypt PKCS5-padded data with the wrong key, and then unpad it (which is done by the Cipher class automatically), you most likely will get the BadPaddingException (with probably of slightly less than 255/256, around 99.61%), because the padding has a special structure which is validated during unpad and very few keys would produce a valid padding.

So, if you get this exception, catch it and treat it as "wrong key".

This also can happen when you provide a wrong password, which then is used to get the key from a keystore, or which is converted into a key using a key generation function.

Of course, bad padding can also happen if your data is corrupted in transport.

That said, there are some security remarks about your scheme:

  • For password-based encryption, you should use a SecretKeyFactory and PBEKeySpec instead of using a SecureRandom with KeyGenerator. The reason is that the SecureRandom could be a different algorithm on each Java implementation, giving you a different key. The SecretKeyFactory does the key derivation in a defined manner (and a manner which is deemed secure, if you select the right algorithm).

  • Don't use ECB-mode. It encrypts each block independently, which means that identical plain text blocks also give always identical ciphertext blocks.

    Preferably use a secure mode of operation, like CBC (Cipher block chaining) or CTR (Counter). Alternatively, use a mode which also includes authentication, like GCM (Galois-Counter mode) or CCM (Counter with CBC-MAC), see next point.

  • You normally don't want only confidentiality, but also authentication, which makes sure the message is not tampered with. (This also prevents chosen-ciphertext attacks on your cipher, i.e. helps for confidentiality.) So, add a MAC (message authentication code) to your message, or use a cipher mode which includes authentication (see previous point).

  • DES has an effective key size of only 56 bits. This key space is quite small, it can be brute-forced in some hours by a dedicated attacker. If you generate your key by a password, this will get even faster. Also, DES has a block size of only 64 bits, which adds some more weaknesses in chaining modes. Use a modern algorithm like AES instead, which has a block size of 128 bits, and a key size of 128 bits (for the standard variant).

How to remove whitespace from a string in typescript?

Problem

The trim() method removes whitespace from both sides of a string.

Source

Solution

You can use a Javascript replace method to remove white space like

"hello world".replace(/\s/g, "");

Example

_x000D_
_x000D_
var out = "hello world".replace(/\s/g, "");_x000D_
console.log(out);
_x000D_
_x000D_
_x000D_

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

Your code is correct. Kindly mark small correction.

#rightcolumn {
     width: 750px;
     background-color: #777;
     display: block;
     **float: left;(wrong)**
     **float: right; (corrected)**
     border: 1px solid white;
}

Regex Email validation

Why not use EF6 attribute based e-mail validation?

As you can see above, Regex validation for e-mail always has some hole in it. If you are using EF6 data annotations, you can easily achieve reliable and stronger e-mail validation with EmailAddress data annotation attribute available for that. I had to remove the regex validation I used before for e-mail when I got mobile device specific regex failure on e-mail input field. When the data annotation attribute used for e-mail validation, the issue on mobile was resolved.

public class LoginViewModel
{
    [EmailAddress(ErrorMessage = "The email format is not valid")]
    public string Email{ get; set; }

Vertically centering Bootstrap modal window

For those who are using angular-ui bootstrap can add the below classes based on above info:

Note: No other changes are needed and it shall resolve all modals.

// The 3 below classes have been placed to make the modal vertically centered
.modal-open .modal{
    display:table !important;
    height: 100%;
    width: 100%;
    pointer-events:none; /* This makes sure that we can still click outside of the modal to close it */
}

.modal-dialog{
    display: table-cell;
    vertical-align: middle;
    pointer-events: none;
}

.modal-content {
    /* Bootstrap sets the size of the modal in the modal-dialog class, we need to inherit it */
    width:inherit;
    height:inherit;
    /* To center horizontally */
    margin: 0 auto;
    pointer-events: all;
}

Shell script to capture Process ID and kill it if exist

Actually the easiest way to do that would be to pass kill arguments like below:

ps -ef | grep your_process_name | grep -v grep | awk '{print $2}' | xargs kill

Hope it helps.

What's the difference between Html.Label, Html.LabelFor and Html.LabelForModel

Html.Label gives you a label for an input whose name matches the specified input text (more specifically, for the model property matching the string expression):

// Model
public string Test { get; set; }

// View
@Html.Label("Test")

// Output
<label for="Test">Test</label>

Html.LabelFor gives you a label for the property represented by the provided expression (typically a model property):

// Model
public class MyModel
{
    [DisplayName("A property")]
    public string Test { get; set; }
}

// View
@model MyModel
@Html.LabelFor(m => m.Test)

// Output
<label for="Test">A property</label>

Html.LabelForModel is a bit trickier. It returns a label whose for value is that of the parameter represented by the model object. This is useful, in particular, for custom editor templates. For example:

// Model
public class MyModel
{
    [DisplayName("A property")]
    public string Test { get; set; }
}

// Main view
@Html.EditorFor(m => m.Test)

// Inside editor template
@Html.LabelForModel()

// Output
<label for="Test">A property</label>

How to check if a file contains a specific string using Bash

Shortest (correct) version:

grep -q "something" file; [ $? -eq 0 ] && echo "yes" || echo "no"

can be also written as

grep -q "something" file; test $? -eq 0 && echo "yes" || echo "no"

but you dont need to explicitly test it in this case, so the same with:

grep -q "something" file && echo "yes" || echo "no"

how to call a function from another function in Jquery

wrap you shared code into another function:

<script>
  function myFun () {
      //do something
  }

  $(document).ready(function(){
    //Load City by State
    $(document).on('change', '#billing_state_id', function() {
       myFun ();
    });   
    $(document).on('click', '#click_me', function() {
       //do something
       myFun();
    });   
  });
</script>

How to create a 100% screen width div inside a container in bootstrap?

2019's answer as this is still actively seen today

You should likely change the .container to .container-fluid, which will cause your container to stretch the entire screen. This will allow any div's inside of it to naturally stretch as wide as they need.

original hack from 2015 that still works in some situations

You should pull that div outside of the container. You're asking a div to stretch wider than its parent, which is generally not recommended practice.

If you cannot pull it out of the div for some reason, you should change the position style with this css:

.full-width-div {
    position: absolute;
    width: 100%;
    left: 0;
}

Instead of absolute, you could also use fixed, but then it will not move as you scroll.

How to install mcrypt extension in xampp

Right from the PHP Docs: PHP 5.3 Windows binaries uses the static version of the MCrypt library, no DLL are needed.

http://php.net/manual/en/mcrypt.requirements.php

But if you really want to download it, just go to the mcrypt sourceforge page

http://sourceforge.net/projects/mcrypt/files/?source=navbar

Markdown and including multiple files

I'm actually surprised that no one in this page has offered any HTML solutions. As far I have understood MarkDown files can include wide portion (if not all) of HTML tags. So follow these steps:

  1. From here: put your MarkDown files in <span style="display:block"> ... </span> tags to be sure they will be rendered as markdown. You have a whole lot of other style properties you can add. The one I like is the text-align:justify.

  2. From here: Include the files in your main file using the <iframe src="/path/to/file.md" seamless></iframe>

P.S.1. this solution does not work on all MarkDown engines / renders. For example Typora did render the files correctly but Visual Studio Code didn't. It would be great if others could share their experience with other platforms. Specially I would like to hear about GitHub and GitLab ...

P.S.2. On further investigation there seems to be major incompatibility issues leading to this not being properly rendered on many platforms, including Typora, GitHub and Visual Studio code. Please do not use this till I resolve them. I will not delete the answer just for the sake of discussion and if maybe you can share your opinions.

P.S.3. To further investigate this issue I have asked this questions here on StackOverflow and here on Reddit.

P.S.4. After some through study, I came to the conclusion that for the moment AsciiDoc is a better option for documentation. It comes with built-in include functionality, it is rendered by GitHub, and major code editors like Atom and vscode have extensions for live preview. One can use Pandoc or other tools to automatically convert existing MarkDown Code to AsciiDoc with minor changes.

P.S.5. Another lightweight markup language with built-in include functionality is reStructuredText. It comes with .. include:: inclusion.txt syntax by standard. There is ReText editor with live preview as well.

Prepend text to beginning of string

ES6:

let after = 'something after';
let text = `before text ${after}`;

Getting a list of values from a list of dicts

A very simple way to do it is:

list1=['']
j=0
for i in com_list:
    if j==0:
        list1[0]=(i['value'])
    else:
        list1.append(i['value'])
    j+=1

Output:

['apple', 'banana', 'cars']

Could not resolve all dependencies for configuration ':classpath'

I was facing the same issue, it was because of the cache. You just need to follow these Steps:

  1. Go to File -> Invalidate Caches / Restart
  2. After restarting Android Studio, connect your PC to a good network.
  3. Go to build and choose rebuild, and Android Studio will automatically download the missing files for the project

Sublime Text 2 - View whitespace characters

I use Unicode Character Highlighter, can show whitespaces and some other special characters.

Add this by, Package Control

Install packages, unicode ...

IOPub data rate exceeded in Jupyter notebook (when viewing image)

Removing print statements can also fix the problem.

Apart from loading images, this error also happens when your code is printing continuously at a high rate, which is causing the error "IOPub data rate exceeded". E.g. if you have a print statement in a for loop somewhere that is being called over 1000 times.

iOS 7 - Failing to instantiate default view controller

I have experienced this with my Tab Bar Controller not appearing in the Simulator along with a black screen. I did the following in order for my app to appear in the Simulator.

  1. Go to Main.storyboard.
  2. Check the Is Initial View Controller under the Attributes inspector tab.

Is Initial View Controller in the Attributes Inspector.

If you accidentally deleted that view controller, or otherwise made it not the default, then you’ll see the error “Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the designated entry point is not set?” when your app launches, along with a plain black screen.

To fix the problem, open your Main.storyboard file and find whichever view controller you want to be shown when your app first runs. When it’s selected, go to the attributes inspector and check the box marked “Is Initial View Controller”. You should see a right-facing arrow appear to the left of that view controller, showing that it’s your storyboard’s entry point.

How to get the current time in Google spreadsheet using script editor?

use the JavaScript Date() object. There are a number of ways to get the time, date, timestamps, etc from the object. (Reference)

function myFunction() {
  var d = new Date();
  var timeStamp = d.getTime();  // Number of ms since Jan 1, 1970

  // OR:

  var currentTime = d.toLocaleTimeString(); // "12:35 PM", for instance
}

What does the term "canonical form" or "canonical representation" in Java mean?

I believe there are two related uses of canonical: forms and instances.

A canonical form means that values of a particular type of resource can be described or represented in multiple ways, and one of those ways is chosen as the favored canonical form. (That form is canonized, like books that made it into the bible, and the other forms are not.) A classic example of a canonical form is paths in a hierarchical file system, where a single file can be referenced in a number of ways:

myFile.txt                                   # in current working dir
../conf/myFile.txt                           # relative to the CWD
/apps/tomcat/conf/myFile.txt                 # absolute path using symbolic links
/u1/local/apps/tomcat-5.5.1/conf/myFile.txt  # absolute path with no symlinks

The classic definition of the canonical representation of that file would be the last path. With local or relative paths you cannot globally identify the resource without contextual information. With absolute paths you can identify the resource, but cannot tell if two paths refer to the same entity. With two or more paths converted to their canonical forms, you can do all the above, plus determine if two resources are the same or not, if that is important to your application (solve the aliasing problem).

Note that the canonical form of a resource is not a quality of that particular form itself; there can be multiple possible canonical forms for a given type like file paths (say, lexicographically first of all possible absolute paths). One form is just selected as the canonical form for a particular application reason, or maybe arbitrarily so that everyone speaks the same language.

Forcing objects into their canonical instances is the same basic idea, but instead of determining one "best" representation of a resource, it arbitrarily chooses one instance of a class of instances with the same "content" as the canonical reference, then converts all references to equivalent objects to use the one canonical instance.

This can be used as a technique for optimizing both time and space. If there are multiple instances of equivalent objects in an application, then by forcing them all to be resolved as the single canonical instance of a particular value, you can eliminate all but one of each value, saving space and possibly time since you can now compare those values with reference identity (==) as opposed to object equivalence (equals() method).

A classic example of optimizing performance with canonical instances is collapsing strings with the same content. Calling String.intern() on two strings with the same character sequence is guaranteed to return the same canonical String object for that text. If you pass all your strings through that canonicalizer, you know equivalent strings are actually identical object references, i.e., aliases

The enum types in Java 5.0+ force all instances of a particular enum value to use the same canonical instance within a VM, even if the value is serialized and deserialized. That is why you can use if (day == Days.SUNDAY) with impunity in java if Days is an enum type. Doing this for your own classes is certainly possible, but takes care. Read Effective Java by Josh Bloch for details and advice.

Where is the Java SDK folder in my computer? Ubuntu 12.04

$ whereis java

java: /usr/bin/java /usr/lib/java /usr/bin/X11/java /usr/share/java /usr/share/man/man1/java.1.gz

CSS to keep element at "fixed" position on screen

Make sure your content is kept in a div, say divfix.

<div id="divfix">Your Code goes here</div>

CSS :

#divfix {
       bottom: 0;
       right: 0;
       position: fixed;
       z-index: 3000;
}

Hope ,It will help you..

How to loop through all the properties of a class?

Use Reflection:

Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();

foreach (PropertyInfo property in properties)
{
    Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(obj, null));
}

for Excel - what tools/reference item must be added to gain access to BindingFlags, as there is no "System.Reflection" entry in the list

Edit: You can also specify a BindingFlags value to type.GetProperties():

BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = type.GetProperties(flags);

That will restrict the returned properties to public instance properties (excluding static properties, protected properties, etc).

You don't need to specify BindingFlags.GetProperty, you use that when calling type.InvokeMember() to get the value of a property.

Comparing two integer arrays in Java

You can check array equality with the Apache Commons ArrayUtils#isEquals() method.

adb connection over tcp not working now

Try to do port forwarding,

adb forward tcp:<PC port> tcp:<device port>.

like:

adb forward tcp:5555 tcp:5555.

sounds like 5555 port is captured so use other one. As I know 7612 is empty

[Edit]

C:\Users\m>adb forward tcp:7612 tcp:7612

C:\Users\m>adb tcpip 7612
restarting in TCP mode port: 7612

C:\Users\m>adb connect 192.168.1.12
connected to 192.168.1.12:7612

Be sure that you connect to the right IP address. (You can download Network Info 2 to check your IP)

ES6 class variable alternatives

In your example:

class MyClass {
    const MY_CONST = 'string';
    constructor(){
        this.MY_CONST;
    }
}

Because of MY_CONST is primitive https://developer.mozilla.org/en-US/docs/Glossary/Primitive we can just do:

class MyClass {
    static get MY_CONST() {
        return 'string';
    }
    get MY_CONST() {
        return this.constructor.MY_CONST;
    }
    constructor() {
        alert(this.MY_CONST === this.constructor.MY_CONST);
    }
}
alert(MyClass.MY_CONST);
new MyClass

// alert: string ; true

But if MY_CONST is reference type like static get MY_CONST() {return ['string'];} alert output is string, false. In such case delete operator can do the trick:

class MyClass {
    static get MY_CONST() {
        delete MyClass.MY_CONST;
        return MyClass.MY_CONST = 'string';
    }
    get MY_CONST() {
        return this.constructor.MY_CONST;
    }
    constructor() {
        alert(this.MY_CONST === this.constructor.MY_CONST);
    }
}
alert(MyClass.MY_CONST);
new MyClass

// alert: string ; true

And finally for class variable not const:

class MyClass {
    static get MY_CONST() {
        delete MyClass.MY_CONST;
        return MyClass.MY_CONST = 'string';
    }
    static set U_YIN_YANG(value) {
      delete MyClass.MY_CONST;
      MyClass.MY_CONST = value;
    }
    get MY_CONST() {
        return this.constructor.MY_CONST;
    }
    set MY_CONST(value) {
        this.constructor.MY_CONST = value;
    }
    constructor() {
        alert(this.MY_CONST === this.constructor.MY_CONST);
    }
}
alert(MyClass.MY_CONST);
new MyClass
// alert: string, true
MyClass.MY_CONST = ['string, 42']
alert(MyClass.MY_CONST);
new MyClass
// alert: string, 42 ; true

How to make <label> and <input> appear on the same line on an HTML form?

aaa##HTML I would suggest you wrap them in a div, since you will likely end up floating them in certain contexts.

<div class="input-w">
    <label for="your-input">Your label</label>
    <input type="text" id="your-input" />
</div>

CSS

Then within that div, you can make each piece inline-block so that you can use vertical-align to center them - or set baseline etc. (your labels and input might change sizes in the future...

.input-w label, .input-w input {
    float: none; /* if you had floats before? otherwise inline-block will behave differently */
    display: inline-block;
    vertical-align: middle;    
}

jsFiddle

UPDATE: mid 2016 + with mobile-first media queries and flex-box

This is how I do things these days.

HTML

<label class='input-w' for='this-input-name'>
  <span class='label'>Your label</span>
  <input class='input' type='text' id='this-input-name' placeholder='hello'>
</label>

<label class='input-w' for='this-other-input-name'>
  <span class='label'>Your label</span>
  <input class='input' type='text' id='this-other-input-name' placeholder='again'>
</label>

SCSS

html { // https://www.paulirish.com/2012/box-sizing-border-box-ftw/
  box-sizing: border-box;
  *, *:before, *:after {
    box-sizing: inherit;
  }
} // if you don't already reset your box-model, read about it

.input-w {
  display: block;
  width: 100%; // should be contained by a form or something
  margin-bottom: 1rem;
  @media (min-width: 500px) {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
  .label, .input {
    display: block;
    width: 100%;
    border: 1px solid rgba(0,0,0,.1);
    @media (min-width: 500px) {
      width: auto;
      display: flex;
    }
  }
  .label {
    font-size: 13px;
    @media (min-width: 500px) {
      /* margin-right: 1rem; */
      min-width: 100px; // maybe to match many?
    }
  }
  .input {
    padding: .5rem;
    font-size: 16px;
    @media (min-width: 500px) {
      flex-grow: 1;
      max-width: 450px; // arbitrary
    }
  }
}

jsFiddle

Display current date and time without punctuation

Without punctuation (as @Burusothman has mentioned):

current_date_time="`date +%Y%m%d%H%M%S`";
echo $current_date_time;

O/P:

20170115072120

With punctuation:

current_date_time="`date "+%Y-%m-%d %H:%M:%S"`";
echo $current_date_time;

O/P:

2017-01-15 07:25:33

git recover deleted file where no commit was made after the delete

The output tells you what you need to do. git reset HEAD cc.properties etc.

This will unstage the rm operation. After that, running a git status again will tell you that you need to do a git checkout -- cc.properties to get the file back.

Update: I have this in my config file

$ git config alias.unstage
reset HEAD

which I usually use to unstage stuff.

Removing all script tags from html with JS Regular Expression

Attempting to remove HTML markup using a regular expression is problematic. You don't know what's in there as script or attribute values. One way is to insert it as the innerHTML of a div, remove any script elements and return the innerHTML, e.g.

  function stripScripts(s) {
    var div = document.createElement('div');
    div.innerHTML = s;
    var scripts = div.getElementsByTagName('script');
    var i = scripts.length;
    while (i--) {
      scripts[i].parentNode.removeChild(scripts[i]);
    }
    return div.innerHTML;
  }

alert(
 stripScripts('<span><script type="text/javascript">alert(\'foo\');<\/script><\/span>')
);

Note that at present, browsers will not execute the script if inserted using the innerHTML property, and likely never will especially as the element is not added to the document.

What is a practical, real world example of the Linked List?

Look at a linked list :

[A]=> [B]=> [C]=> [D]=>

It's a ... Train ! Each railroad car contain something and is attached to another railroad car (or nothing for the last one). You can only add a railroad car at the end and if you want to get rid of one you must attach the previous one with the next one.

Find number of decimal places in decimal value regardless of culture

As a decimal extension method that takes into account:

  • Different cultures
  • Whole numbers
  • Negative numbers
  • Trailing set zeros on the decimal place (e.g. 1.2300M will return 2 not 4)
public static class DecimalExtensions
{
    public static int GetNumberDecimalPlaces(this decimal source)
    {
        var parts = source.ToString(CultureInfo.InvariantCulture).Split('.');

        if (parts.Length < 2)
            return 0;

        return parts[1].TrimEnd('0').Length;
    }
}

jQuery how to find an element based on a data-attribute value?

Without JQuery, ES6

document.querySelectorAll(`[data-slide='${current}']`);

I know the question is about JQuery, but readers may want a pure JS method.

How to stop an animation (cancel() does not work)

To stop animation you may set such objectAnimator that do nothing, e.g.

first when manual flipping there is animation left to right:

flipper.setInAnimation(leftIn);
flipper.setOutAnimation(rightOut);

then when switching to auto flipping there's no animation

flipper.setInAnimation(doNothing);
flipper.setOutAnimation(doNothing);

doNothing = ObjectAnimator.ofFloat(flipper, "x", 0f, 0f).setDuration(flipperSwipingDuration);

What's the difference between select_related and prefetch_related in Django ORM?

Both methods achieve the same purpose, to forego unnecessary db queries. But they use different approaches for efficiency.

The only reason to use either of these methods is when a single large query is preferable to many small queries. Django uses the large query to create models in memory preemptively rather than performing on demand queries against the database.

select_related performs a join with each lookup, but extends the select to include the columns of all joined tables. However this approach has a caveat.

Joins have the potential to multiply the number of rows in a query. When you perform a join over a foreign key or one-to-one field, the number of rows won't increase. However, many-to-many joins do not have this guarantee. So, Django restricts select_related to relations that won't unexpectedly result in a massive join.

The "join in python" for prefetch_related is a little more alarming then it should be. It creates a separate query for each table to be joined. It filters each of these table with a WHERE IN clause, like:

SELECT "credential"."id",
       "credential"."uuid",
       "credential"."identity_id"
FROM   "credential"
WHERE  "credential"."identity_id" IN
    (84706, 48746, 871441, 84713, 76492, 84621, 51472);

Rather than performing a single join with potentially too many rows, each table is split into a separate query.

ImportError: No module named sklearn.cross_validation

train_test_split is part of the module sklearn.model_selection, hence, you may need to import the module from model_selection

Code:

from sklearn.model_selection import train_test_split

Can vue-router open a link in a new tab?

I think that you can do something like this:

let routeData = this.$router.resolve({name: 'routeName', query: {data: "someData"}});
window.open(routeData.href, '_blank');

It worked for me.

Sort objects in ArrayList by date?

All the answers here I found to be un-neccesarily complex for a simple problem (at least to an experienced java developer, which I am not). I had a similar problem and chanced upon this (and other) solutions, and though they provided a pointer, for a beginner I found as stated above. My solution, depends on where in the the Object your Date is, in this case, the date is the first element of the Object[] where dataVector is the ArrayList containing your Objects.

Collections.sort(dataVector, new Comparator<Object[]>() {
    public int compare(Object[] o1, Object[] o2) {
        return ((Date)o1[0]).compareTo(((Date)o2[0]));
    }
});

TypeScript sorting an array

I wrote this one today while trying to recreate _.sortBy in TypeScript, and thought I would leave it for anyone in need.

// ** Credits for getKeyValue at the bottom **
export const getKeyValue = <T extends {}, U extends keyof T>(key: U) => (obj: T) => obj[key] 

export const sortBy = <T extends {}>(index: string, list: T[]): T[] => {
    return list.sort((a, b): number => {
        const _a = getKeyValue<keyof T, T>(index)(a)
        const _b = getKeyValue<keyof T, T>(index)(b)
        if (_a < _b) return -1
        if (_a > _b) return 1
        return 0
    })
}

Usage:

It expects an array of generic type T, hence the cast for <T extends {}>, as well as typing the parameter and function return type with T[]

const x = [{ label: 'anything' }, { label: 'goes'}]
const sorted = sortBy('label', x)

** getByKey fn found here

How do I pass JavaScript variables to PHP?

You can use JQuery Ajax and POST method:

var obj;

                
$(document).ready(function(){
            $("#button1").click(function(){
                var username=$("#username").val();
                var password=$("#password").val();
  $.ajax({
    url: "addperson.php",
    type: "POST", 
    async: false,
    data: {
        username: username,
        password: password
    }
})
.done (function(data, textStatus, jqXHR) { 
    
   obj = JSON.parse(data);
   
})
.fail (function(jqXHR, textStatus, errorThrown) { 
    
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) { 
    
});
  
 
            });
        });

To take a response back from the php script JSON parse the the respone in .done() method. Here is the php script you can modify to your needs:

<?php
     $username1 = isset($_POST["username"]) ? $_POST["username"] : '';
    
     $password1 = isset($_POST["password"]) ? $_POST["password"] : '';

$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO user (username, password)
VALUES ('$username1', '$password1' )";

    ;  
    
    
   

if ($conn->query($sql) === TRUE) {
    
   echo json_encode(array('success' => 1));
} else{
    
    
  echo json_encode(array('success' => 0));
}





$conn->close();
?>

Good MapReduce examples

Map reduce is a framework that was developed to process massive amounts of data efficiently. For example, if we have 1 million records in a dataset, and it is stored in a relational representation - it is very expensive to derive values and perform any sort of transformations on these.

For Example In SQL, Given the Date of Birth, to find out How many people are of age > 30 for a million records would take a while, and this would only increase in order of magnitute when the complexity of the query increases. Map Reduce provides a cluster based implementation where data is processed in a distributed manner

Here is a wikipedia article explaining what map-reduce is all about

Another good example is Finding Friends via map reduce can be a powerful example to understand the concept, and a well used use-case.

Personally, found this link quite useful to understand the concept

Copying the explanation provided in the blog (In case the link goes stale)

Finding Friends

MapReduce is a framework originally developed at Google that allows for easy large scale distributed computing across a number of domains. Apache Hadoop is an open source implementation.

I'll gloss over the details, but it comes down to defining two functions: a map function and a reduce function. The map function takes a value and outputs key:value pairs. For instance, if we define a map function that takes a string and outputs the length of the word as the key and the word itself as the value then map(steve) would return 5:steve and map(savannah) would return 8:savannah. You may have noticed that the map function is stateless and only requires the input value to compute it's output value. This allows us to run the map function against values in parallel and provides a huge advantage. Before we get to the reduce function, the mapreduce framework groups all of the values together by key, so if the map functions output the following key:value pairs:

3 : the
3 : and
3 : you
4 : then
4 : what
4 : when
5 : steve
5 : where
8 : savannah
8 : research

They get grouped as:

3 : [the, and, you]
4 : [then, what, when]
5 : [steve, where]
8 : [savannah, research]

Each of these lines would then be passed as an argument to the reduce function, which accepts a key and a list of values. In this instance, we might be trying to figure out how many words of certain lengths exist, so our reduce function will just count the number of items in the list and output the key with the size of the list, like:

3 : 3
4 : 3
5 : 2
8 : 2

The reductions can also be done in parallel, again providing a huge advantage. We can then look at these final results and see that there were only two words of length 5 in our corpus, etc...

The most common example of mapreduce is for counting the number of times words occur in a corpus. Suppose you had a copy of the internet (I've been fortunate enough to have worked in such a situation), and you wanted a list of every word on the internet as well as how many times it occurred.

The way you would approach this would be to tokenize the documents you have (break it into words), and pass each word to a mapper. The mapper would then spit the word back out along with a value of 1. The grouping phase will take all the keys (in this case words), and make a list of 1's. The reduce phase then takes a key (the word) and a list (a list of 1's for every time the key appeared on the internet), and sums the list. The reducer then outputs the word, along with it's count. When all is said and done you'll have a list of every word on the internet, along with how many times it appeared.

Easy, right? If you've ever read about mapreduce, the above scenario isn't anything new... it's the "Hello, World" of mapreduce. So here is a real world use case (Facebook may or may not actually do the following, it's just an example):

Facebook has a list of friends (note that friends are a bi-directional thing on Facebook. If I'm your friend, you're mine). They also have lots of disk space and they serve hundreds of millions of requests everyday. They've decided to pre-compute calculations when they can to reduce the processing time of requests. One common processing request is the "You and Joe have 230 friends in common" feature. When you visit someone's profile, you see a list of friends that you have in common. This list doesn't change frequently so it'd be wasteful to recalculate it every time you visited the profile (sure you could use a decent caching strategy, but then I wouldn't be able to continue writing about mapreduce for this problem). We're going to use mapreduce so that we can calculate everyone's common friends once a day and store those results. Later on it's just a quick lookup. We've got lots of disk, it's cheap.

Assume the friends are stored as Person->[List of Friends], our friends list is then:

A -> B C D
B -> A C D E
C -> A B D E
D -> A B C E
E -> B C D

Each line will be an argument to a mapper. For every friend in the list of friends, the mapper will output a key-value pair. The key will be a friend along with the person. The value will be the list of friends. The key will be sorted so that the friends are in order, causing all pairs of friends to go to the same reducer. This is hard to explain with text, so let's just do it and see if you can see the pattern. After all the mappers are done running, you'll have a list like this:

For map(A -> B C D) :

(A B) -> B C D
(A C) -> B C D
(A D) -> B C D

For map(B -> A C D E) : (Note that A comes before B in the key)

(A B) -> A C D E
(B C) -> A C D E
(B D) -> A C D E
(B E) -> A C D E
For map(C -> A B D E) :

(A C) -> A B D E
(B C) -> A B D E
(C D) -> A B D E
(C E) -> A B D E
For map(D -> A B C E) :

(A D) -> A B C E
(B D) -> A B C E
(C D) -> A B C E
(D E) -> A B C E
And finally for map(E -> B C D):

(B E) -> B C D
(C E) -> B C D
(D E) -> B C D
Before we send these key-value pairs to the reducers, we group them by their keys and get:

(A B) -> (A C D E) (B C D)
(A C) -> (A B D E) (B C D)
(A D) -> (A B C E) (B C D)
(B C) -> (A B D E) (A C D E)
(B D) -> (A B C E) (A C D E)
(B E) -> (A C D E) (B C D)
(C D) -> (A B C E) (A B D E)
(C E) -> (A B D E) (B C D)
(D E) -> (A B C E) (B C D)

Each line will be passed as an argument to a reducer. The reduce function will simply intersect the lists of values and output the same key with the result of the intersection. For example, reduce((A B) -> (A C D E) (B C D)) will output (A B) : (C D) and means that friends A and B have C and D as common friends.

The result after reduction is:

(A B) -> (C D)
(A C) -> (B D)
(A D) -> (B C)
(B C) -> (A D E)
(B D) -> (A C E)
(B E) -> (C D)
(C D) -> (A B E)
(C E) -> (B D)
(D E) -> (B C)

Now when D visits B's profile, we can quickly look up (B D) and see that they have three friends in common, (A C E).

Just what is an IntPtr exactly?

Here's an example:

I'm writing a C# program that interfaces with a high-speed camera. The camera has its own driver that acquires images and loads them into the computer's memory for me automatically.

So when I'm ready to bring the latest image into my program to work with, the camera driver provides me with an IntPtr to where the image is ALREADY stored in physical memory, so I don't have to waste time/resources creating another block of memory to store an image that's in memory already. The IntPtr just shows me where the image already is.

ReactNative: how to center text?

You can use two approaches for this...

  1. To make text align center horizontally, apply this Property (textAlign:"center"). Now to make the text align vertically, first check direction of flex. If flexDirection is column apply property (justifyContent:"center") and if flexDirection is row is row apply property (alignItems : "center") .

  2. To Make text align center apply same property (textAlign:"center"). Now to make it align vertically make the hieght of the <Text> </Text> equal to view and then apply property (textAlignVertical: "center")...

Most Probably it will Work...

Windows-1252 to UTF-8 encoding

iconv -f WINDOWS-1252 -t UTF-8 filename.txt

Finding local maxima/minima with Numpy in a 1D numpy array

Another one:


def local_maxima_mask(vec):
    """
    Get a mask of all points in vec which are local maxima
    :param vec: A real-valued vector
    :return: A boolean mask of the same size where True elements correspond to maxima. 
    """
    mask = np.zeros(vec.shape, dtype=np.bool)
    greater_than_the_last = np.diff(vec)>0  # N-1
    mask[1:] = greater_than_the_last
    mask[:-1] &= ~greater_than_the_last
    return mask

How can I hide the Android keyboard using JavaScript?

I found a simpler solution that requires neither adding element nor a special class. found it there: http://www.sencha.com/forum/archive/index.php/t-141560.html

And converted the code to jquery :

function hideKeyboard(element) {
    element.attr('readonly', 'readonly'); // Force keyboard to hide on input field.
    element.attr('disabled', 'true'); // Force keyboard to hide on textarea field.
    setTimeout(function() {
        element.blur();  //actually close the keyboard
        // Remove readonly attribute after keyboard is hidden.
        element.removeAttr('readonly');
        element.removeAttr('disabled');
    }, 100);
}

You call the function by passing it the input from which the keyboard was opened, or just passing $('input') should also work.

Is there a better jQuery solution to this.form.submit();?

I have found that using jQuery the best solution is

$(this.form).submit()

Using this statement jquery plugins (e.g. jquery form plugin) works correctly and jquery DOM traversing overhead is minimized.

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

As Ponies says in a comment, you cannot mix OLAP functions with aggregate functions.

Perhaps it's easier to get the last completion date for each employee, and join that to a dataset containing the last completion date for each of the three targeted courses.

This is an untested idea that should hopefully put you down the right path:

  SELECT employee_number,
         course_code,
         MAX(course_completion_date) AS max_date,
         lcc.LAST_COURSE_COMPLETED
    FROM employee_course_completion ecc
         LEFT JOIN (
             SELECT employee_number,
                    MAX(course_completion_date) AS LAST_COURSE_COMPLETED
               FROM employee_course_completion
              WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
         ) lcc
         ON lcc.employee_number = ecc.employee_number
   WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code, lcc.LAST_COURSE_COMPLETED

BackgroundWorker vs background Thread

What's perplexing to me is that the visual studio designer only allows you to use BackgroundWorkers and Timers that don't actually work with the service project.

It gives you neat drag and drop controls onto your service but... don't even try deploying it. Won't work.

Services: Only use System.Timers.Timer System.Windows.Forms.Timer won't work even though it's available in the toolbox

Services: BackgroundWorkers will not work when it's running as a service Use System.Threading.ThreadPools instead or Async calls

Sort JavaScript object by key

It's 2019 and we have a 2019 way to solve this :)

Object.fromEntries(Object.entries({b: 3, a:8, c:1}).sort())

How to escape comma and double quote at same time for CSV file?

You could also look at how Python writes Excel-compatible csv files.

I believe the default for Excel is to double-up for literal quote characters - that is, literal quotes " are written as "".

How to find Oracle Service Name

Connect to the server as "system" using SID. Execute this query:

select value from v$parameter where name like '%service_name%';

It worked for me.

How to get the list of properties of a class?

Based on @MarcGravell's answer, here's a version that works in Unity C#.

ObjectsClass foo = this;
foreach(var prop in foo.GetType().GetProperties()) {
    Debug.Log("{0}={1}, " + prop.Name + ", " + prop.GetValue(foo, null));
}

Spring @Transactional - isolation, propagation

PROPAGATION_REQUIRED = 0; If DataSourceTransactionObject T1 is already started for Method M1. If for another Method M2 Transaction object is required, no new Transaction object is created. Same object T1 is used for M2.

PROPAGATION_MANDATORY = 2; method must run within a transaction. If no existing transaction is in progress, an exception will be thrown.

PROPAGATION_REQUIRES_NEW = 3; If DataSourceTransactionObject T1 is already started for Method M1 and it is in progress (executing method M1). If another method M2 start executing then T1 is suspended for the duration of method M2 with new DataSourceTransactionObject T2 for M2. M2 run within its own transaction context.

PROPAGATION_NOT_SUPPORTED = 4; If DataSourceTransactionObject T1 is already started for Method M1. If another method M2 is run concurrently. Then M2 should not run within transaction context. T1 is suspended till M2 is finished.

PROPAGATION_NEVER = 5; None of the methods run in transaction context.


An isolation level: It is about how much a transaction may be impacted by the activities of other concurrent transactions. It a supports consistency leaving the data across many tables in a consistent state. It involves locking rows and/or tables in a database.

The problem with multiple transaction

Scenario 1. If T1 transaction reads data from table A1 that was written by another concurrent transaction T2. If on the way T2 is rollback, the data obtained by T1 is invalid one. E.g. a=2 is original data. If T1 read a=1 that was written by T2. If T2 rollback then a=1 will be rollback to a=2 in DB. But, now, T1 has a=1 but in DB table it is changed to a=2.

Scenario2. If T1 transaction reads data from table A1. If another concurrent transaction (T2) update data on table A1. Then the data that T1 has read is different from table A1. Because T2 has updated the data on table A1. E.g. if T1 read a=1 and T2 updated a=2. Then a!=b.

Scenario 3. If T1 transaction reads data from table A1 with certain number of rows. If another concurrent transaction (T2) inserts more rows on table A1. The number of rows read by T1 is different from rows on table A1.

Scenario 1 is called Dirty reads.

Scenario 2 is called Non-repeatable reads.

Scenario 3 is called Phantom reads.

So, isolation level is the extend to which Scenario 1, Scenario 2, Scenario 3 can be prevented. You can obtain complete isolation level by implementing locking. That is preventing concurrent reads and writes to the same data from occurring. But it affects performance. The level of isolation depends upon application to application how much isolation is required.

ISOLATION_READ_UNCOMMITTED: Allows to read changes that haven’t yet been committed. It suffer from Scenario 1, Scenario 2, Scenario 3.

ISOLATION_READ_COMMITTED: Allows reads from concurrent transactions that have been committed. It may suffer from Scenario 2 and Scenario 3. Because other transactions may be updating the data.

ISOLATION_REPEATABLE_READ: Multiple reads of the same field will yield the same results untill it is changed by itself. It may suffer from Scenario 3. Because other transactions may be inserting the data.

ISOLATION_SERIALIZABLE: Scenario 1, Scenario 2, Scenario 3 never happen. It is complete isolation. It involves full locking. It affects performace because of locking.

You can test using:

public class TransactionBehaviour {
   // set is either using xml Or annotation
    DataSourceTransactionManager manager=new DataSourceTransactionManager();
    SimpleTransactionStatus status=new SimpleTransactionStatus();
   ;
  
    
    public void beginTransaction()
    {
        DefaultTransactionDefinition Def = new DefaultTransactionDefinition();
        // overwrite default PROPAGATION_REQUIRED and ISOLATION_DEFAULT
        // set is either using xml Or annotation
        manager.setPropagationBehavior(XX);
        manager.setIsolationLevelName(XX);
       
        status = manager.getTransaction(Def);
    
    }

    public void commitTransaction()
    {
       
      
            if(status.isCompleted()){
                manager.commit(status);
        } 
    }

    public void rollbackTransaction()
    {
       
            if(!status.isCompleted()){
                manager.rollback(status);
        }
    }
    Main method{
        beginTransaction()
        M1();
        If error(){
            rollbackTransaction()
        }
         commitTransaction();
    }
   
}

You can debug and see the result with different values for isolation and propagation.

How to configure CORS in a Spring Boot + Spring Security application?

I had the same problem on a methood that returns the status of the server. The application is deployed on multiple servers. So the easiest I found is to add

@CrossOrigin(origins = "*")
@RequestMapping(value="/schedulerActive")
public String isSchedulerActive(){
  //code goes here
}

This method is not secure but you can add allowCredentials for that.

best way to get the key of a key/value javascript object

Object.keys() The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

var arr1 = Object.keys(obj);

Object.values() The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

var arr2 = Object.values(obj);

For more please go here

How to initialize a list of strings (List<string>) with many string values

List<string> animals= new List<string>();
animals.Add("dog");
animals.Add("tiger");

Matplotlib: "Unknown projection '3d'" error

Just to add to Joe Kington's answer (not enough reputation for a comment) there is a good example of mixing 2d and 3d plots in the documentation at http://matplotlib.org/examples/mplot3d/mixed_subplots_demo.html which shows projection='3d' working in combination with the Axes3D import.

from mpl_toolkits.mplot3d import Axes3D
...
ax = fig.add_subplot(2, 1, 1)
...
ax = fig.add_subplot(2, 1, 2, projection='3d')

In fact as long as the Axes3D import is present the line

from mpl_toolkits.mplot3d import Axes3D
...
ax = fig.gca(projection='3d')

as used by the OP also works. (checked with matplotlib version 1.3.1)

Get product id and product type in magento?

<?php if( $_product->getTypeId() == 'simple' ): ?>
//your code for simple products only
<?php endif; ?>

<?php if( $_product->getTypeId() == 'grouped' ): ?>
//your code for grouped products only
<?php endif; ?>

So on. It works! Magento 1.6.1, place in the view.phtml

UTF-8 in Windows 7 CMD

This question has been already answered in Unicode characters in Windows command line - how?

You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.

Java 8 lambda get and remove element from list

As others have suggested, this might be a use case for loops and iterables. In my opinion, this is the simplest approach. If you want to modify the list in-place, it cannot be considered "real" functional programming anyway. But you could use Collectors.partitioningBy() in order to get a new list with elements which satisfy your condition, and a new list of those which don't. Of course with this approach, if you have multiple elements satisfying the condition, all of those will be in that list and not only the first.

HTTP status code 0 - Error Domain=NSURLErrorDomain?

A status code of 0 in an NSHTTPURLResponse object generally means there was no response, and can occur for various reasons. The server will never return a status of 0 as this is not a valid HTTP status code.

In your case, you are appearing to get a status code of 0 because the request is timing out and 0 is just the default value for the property. The timeout itself could be for various reasons, such as the server simply not responding in time, being blocked by a firewall, or your entire network connection being down. Usually in the case of the latter though the phone is smart enough to know it doesn't have a network connection and will fail immediately. However, it will still fail with an apparent status code of 0.

Note that in cases where the status code is 0, the real error is captured in the returned NSError object, not the NSHTTPURLResponse.

HTTP status 408 is pretty uncommon in my experience. I've never encountered one myself. But it is apparently used in cases where the client needs to maintain an active socket connection to the server, and the server is waiting on the client to send more data over the open socket, but it doesn't in a given amount of time and the server ends the connection with a 408 status code, essentially telling the client "you took too long".

Why Would I Ever Need to Use C# Nested Classes

Maybe this is a good example of when to use nested classes?

// ORIGINAL
class ImageCacheSettings { }
class ImageCacheEntry { }
class ImageCache
{
    ImageCacheSettings mSettings;
    List<ImageCacheEntry> mEntries;
}

And:

// REFACTORED
class ImageCache
{
    Settings mSettings;
    List<Entry> mEntries;

    class Settings {}
    class Entry {}
}

PS: I've not taken into account which access modifiers should be applied (private, protected, public, internal)

How do you easily create empty matrices javascript?

With ES6 spread operator: Array(9).fill([...Array(9)])

How to force a UIViewController to Portrait orientation in iOS 6

Not to be dull here, but would you be so kind to share your subclass? Thank you.

edit: well, I finally did it, the subclass was dead simple to do. I just had to declare the navigationController in the AppDelegate as UINavigationControllerSubclass instead of the default UINavigationController, then modified your subclass with:

- (BOOL)shouldAutorotate {
    return _shouldRotate;
}

so I can set any view I want to rotate or not by calling at viewDidLoad

_navController = (UINavigationController *)self.navigationController;
[_navController setShouldRotate : YES / NO]

Hope this tweak will help others as well, thanks for your tip!

Tip: Make use of

- (NSUInteger)supportedInterfaceOrientations

in your view controllers, so you don't end up by having a portrait desired view in landscape or vice versa.

Replace a character at a specific index in a string?

First thing I should have noticed is that charAt is a method and assigning value to it using equal sign won't do anything. If a string is immutable, charAt method, to make change to the string object must receive an argument containing the new character. Unfortunately, string is immutable. To modify the string, I needed to use StringBuilder as suggested by Mr. Petar Ivanov.

Redirect pages in JSP?

Hello there: If you need more control on where the link should redirect to, you could use this solution.

Ie. If the user is clicking in the CHECKOUT link, but you want to send him/her to checkout page if its registered(logged in) or registration page if he/she isn't.

You could use JSTL core LIKE:

<!--include the library-->
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>

<%--create a var to store link--%>
<core:set var="linkToRedirect">
  <%--test the condition you need--%>
  <core:choose>
    <core:when test="${USER IS REGISTER}">
      checkout.jsp
    </core:when>
    <core:otherwise>
      registration.jsp
    </core:otherwise>
  </core:choose>
</core:set>

EXPLAINING: is the same as...

 //pseudo code
 if(condition == true)
   set linkToRedirect = checkout.jsp
 else
   set linkToRedirect = registration.jsp

THEN: in simple HTML...

<a href="your.domain.com/${linkToRedirect}">CHECKOUT</a>

Regex for remove everything after | (with | )

If you want to get everything after | excluding set character use this code.

[^|]*$

Others solutions \|.*$

Results : | mypcworld

This one [^|]*$

Results : mypcworld

http://regexr.com/3elkd

How can I remove leading and trailing quotes in SQL Server?

Try this:

SELECT left(right(cast(SampleText as nVarchar),LEN(cast(sampleText as nVarchar))-1),LEN(cast(sampleText as nVarchar))-2)
  FROM TableName

Javascript : calling function from another file

Why don't you take a look to this answer

Including javascript files inside javascript files

In short you can load the script file with AJAX or put a script tag on the HTML to include it( before the script that uses the functions of the other script). The link I posted is a great answer and has multiple examples and explanations of both methods.

WCF named pipe minimal example

Check out my highly simplified Echo example: It is designed to use basic HTTP communication, but it can easily be modified to use named pipes by editing the app.config files for the client and server. Make the following changes:

Edit the server's app.config file, removing or commenting out the http baseAddress entry and adding a new baseAddress entry for the named pipe (called net.pipe). Also, if you don't intend on using HTTP for a communication protocol, make sure the serviceMetadata and serviceDebug is either commented out or deleted:

<configuration>
    <system.serviceModel>
        <services>
            <service name="com.aschneider.examples.wcf.services.EchoService">
                <host>
                    <baseAddresses>
                        <add baseAddress="net.pipe://localhost/EchoService"/>
                    </baseAddresses>
                </host>
            </service>
        </services>
        <behaviors>
            <serviceBehaviors></serviceBehaviors>
        </behaviors>
    </system.serviceModel>
</configuration>

Edit the client's app.config file so that the basicHttpBinding is either commented out or deleted and a netNamedPipeBinding entry is added. You will also need to change the endpoint entry to use the pipe:

<configuration>
    <system.serviceModel>
        <bindings>
            <netNamedPipeBinding>
                <binding name="NetNamedPipeBinding_IEchoService"/>
            </netNamedPipeBinding>
        </bindings>
        <client>
            <endpoint address              = "net.pipe://localhost/EchoService"
                      binding              = "netNamedPipeBinding"
                      bindingConfiguration = "NetNamedPipeBinding_IEchoService"
                      contract             = "EchoServiceReference.IEchoService"
                      name                 = "NetNamedPipeBinding_IEchoService"/>
        </client>
    </system.serviceModel>
</configuration>

The above example will only run with named pipes, but nothing is stopping you from using multiple protocols to run your service. AFAIK, you should be able to have a server run a service using both named pipes and HTTP (as well as other protocols).

Also, the binding in the client's app.config file is highly simplified. There are many different parameters you can adjust, aside from just specifying the baseAddress...

How to pass a function as a parameter in Java?

Lambda Expressions

To add on to jk.'s excellent answer, you can now pass a method more easily using Lambda Expressions (in Java 8). First, some background. A functional interface is an interface that has one and only one abstract method, although it can contain any number of default methods (new in Java 8) and static methods. A lambda expression can quickly implement the abstract method, without all the unnecessary syntax needed if you don't use a lambda expression.

Without lambda expressions:

obj.aMethod(new AFunctionalInterface() {
    @Override
    public boolean anotherMethod(int i)
    {
        return i == 982
    }
});

With lambda expressions:

obj.aMethod(i -> i == 982);

Here is an excerpt from the Java tutorial on Lambda Expressions:

Syntax of Lambda Expressions

A lambda expression consists of the following:

  • A comma-separated list of formal parameters enclosed in parentheses. The CheckPerson.test method contains one parameter, p, which represents an instance of the Person class.

    Note: You can omit the data type of the parameters in a lambda expression. In addition, you can omit the parentheses if there is only one parameter. For example, the following lambda expression is also valid:

    p -> p.getGender() == Person.Sex.MALE 
        && p.getAge() >= 18
        && p.getAge() <= 25
    
  • The arrow token, ->

  • A body, which consists of a single expression or a statement block. This example uses the following expression:

    p.getGender() == Person.Sex.MALE 
        && p.getAge() >= 18
        && p.getAge() <= 25
    

    If you specify a single expression, then the Java runtime evaluates the expression and then returns its value. Alternatively, you can use a return statement:

    p -> {
        return p.getGender() == Person.Sex.MALE
            && p.getAge() >= 18
            && p.getAge() <= 25;
    }
    

    A return statement is not an expression; in a lambda expression, you must enclose statements in braces ({}). However, you do not have to enclose a void method invocation in braces. For example, the following is a valid lambda expression:

    email -> System.out.println(email)
    

Note that a lambda expression looks a lot like a method declaration; you can consider lambda expressions as anonymous methods—methods without a name.


Here is how you can "pass a method" using a lambda expression:

Note: this uses a new standard functional interface, java.util.function.IntConsumer.

class A {
    public static void methodToPass(int i) { 
        // do stuff
    }
}
import java.util.function.IntConsumer;

class B {
    public void dansMethod(int i, IntConsumer aMethod) {
        /* you can now call the passed method by saying aMethod.accept(i), and it
        will be the equivalent of saying A.methodToPass(i) */
    }
}
class C {
    B b = new B();

    public C() {
        b.dansMethod(100, j -> A.methodToPass(j));   //Lambda Expression here
    }
}

The above example can be shortened even more using the :: operator.

public C() {
    b.dansMethod(100, A::methodToPass);
}

Batch Renaming of Files in a Directory

I've written a python script on my own. It takes as arguments the path of the directory in which the files are present and the naming pattern that you want to use. However, it renames by attaching an incremental number (1, 2, 3 and so on) to the naming pattern you give.

import os
import sys

# checking whether path and filename are given.
if len(sys.argv) != 3:
    print "Usage : python rename.py <path> <new_name.extension>"
    sys.exit()

# splitting name and extension.
name = sys.argv[2].split('.')
if len(name) < 2:
    name.append('')
else:
    name[1] = ".%s" %name[1]

# to name starting from 1 to number_of_files.
count = 1

# creating a new folder in which the renamed files will be stored.
s = "%s/pic_folder" % sys.argv[1]
try:
    os.mkdir(s)
except OSError:
    # if pic_folder is already present, use it.
    pass

try:
    for x in os.walk(sys.argv[1]):
        for y in x[2]:
            # creating the rename pattern.
            s = "%spic_folder/%s%s%s" %(x[0], name[0], count, name[1])
            # getting the original path of the file to be renamed.
            z = os.path.join(x[0],y)
            # renaming.
            os.rename(z, s)
            # incrementing the count.
            count = count + 1
except OSError:
    pass

Hope this works for you.

make: *** [ ] Error 1 error

In my case there was a static variable which was not initialized. When I initialized it, the error was removed. I don't know the logic behind it but worked for me. I know its a little late but other people with similar problem might get some help.

WPF TemplateBinding vs RelativeSource TemplatedParent

They are used in a similar way but they have a few differences. Here is a link to the TemplateBinding documentation: http://msdn.microsoft.com/en-us/library/ms742882.aspx

displaying a string on the textview when clicking a button in android

You can do like this:

 String hello;
public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.main);
    super.onCreate(savedInstanceState);

    mybtn = (Button)findViewById(R.id.mybtn);
    txtView=(TextView)findViewById(R.id.txtView);
    txtwidth = (TextView)findViewById(R.id.viewwidth);
    hello="This is my first project";


    mybtn.setOnClickListener(this);
}
public void onClick(View view){
    txtView.setText(hello);
}

Check your textview names. Both are same . You must use different object names and you have mentioned that textview object which is not available in your xml layout file. Hope this will help you.

Python: list of lists

Time traveller here

List_of_list =[([z for z in range(x-2,x+1) if z >= 0],y) for y in range(10) for x in range(10)]

This should do the trick. And the output is this:

[([0], 0), ([0, 1], 0), ([0, 1, 2], 0), ([1, 2, 3], 0), ([2, 3, 4], 0),  ([3, 4, 5], 0), ([4, 5, 6], 0), ([5, 6, 7], 0), ([6, 7, 8], 0), ([7, 8, 9], 0), ([0], 1), ([0, 1], 1), ([0, 1, 2], 1), ([1, 2, 3], 1), ([2, 3, 4], 1), ([3, 4, 5], 1), ([4, 5, 6], 1), ([5, 6, 7], 1), ([6, 7, 8], 1), ([7, 8, 9], 1), ([0], 2), ([0, 1], 2), ([0, 1, 2], 2), ([1, 2, 3], 2), ([2, 3, 4], 2), ([3, 4, 5], 2), ([4, 5, 6], 2), ([5, 6, 7], 2), ([6, 7, 8], 2), ([7, 8, 9], 2), ([0], 3), ([0, 1], 3), ([0, 1, 2], 3), ([1, 2, 3], 3), ([2, 3, 4], 3), ([3, 4, 5], 3), ([4, 5, 6], 3), ([5, 6, 7], 3), ([6, 7, 8], 3), ([7, 8, 9], 3), ([0], 4), ([0, 1], 4), ([0, 1, 2], 4), ([1, 2, 3], 4), ([2, 3, 4], 4), ([3, 4, 5], 4), ([4, 5, 6], 4), ([5, 6, 7], 4), ([6, 7, 8], 4), ([7, 8, 9], 4), ([0], 5), ([0, 1], 5), ([0, 1, 2], 5), ([1, 2, 3], 5), ([2, 3, 4], 5), ([3, 4, 5], 5), ([4, 5, 6], 5), ([5, 6, 7], 5), ([6, 7, 8], 5), ([7, 8, 9], 5), ([0], 6), ([0, 1], 6), ([0, 1, 2], 6), ([1, 2, 3], 6), ([2, 3, 4], 6), ([3, 4, 5], 6), ([4, 5, 6], 6), ([5, 6, 7], 6), ([6, 7, 8], 6), ([7, 8, 9], 6), ([0], 7), ([0, 1], 7), ([0, 1, 2], 7), ([1, 2, 3], 7), ([2, 3, 4], 7), ([3, 4, 5], 7), ([4, 5, 6], 7), ([5, 6, 7], 7), ([6, 7, 8], 7), ([7, 8, 9], 7), ([0], 8), ([0, 1], 8), ([0, 1, 2], 8), ([1, 2, 3], 8), ([2, 3, 4], 8), ([3, 4, 5], 8), ([4, 5, 6], 8), ([5, 6, 7], 8), ([6, 7, 8], 8), ([7, 8, 9], 8), ([0], 9), ([0, 1], 9), ([0, 1, 2], 9), ([1, 2, 3], 9), ([2, 3, 4], 9), ([3, 4, 5], 9), ([4, 5, 6], 9), ([5, 6, 7], 9), ([6, 7, 8], 9), ([7, 8, 9], 9)]    

This is done by list comprehension(which makes looping elements in a list via one line code possible). The logic behind this one-line code is the following:

(1) for x in range(10) and for y in range(10) are employed for two independent loops inside a list

(2) (a list, y) is the general term of the loop, which is why it is placed before two for's in (1)

(3) the length of the list in (2) cannot exceed 3, and the list depends on x, so

[z for z in range(x-2,x+1)] 

is used

(4) because z starts from zero but range(x-2,x+1) starts from -2 which isn't what we want, so a conditional statement if z >= 0 is placed at the end of the list in (2)

[z for z in range(x-2,x+1) if z >= 0] 

How to round float numbers in javascript?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

Use Async/Await with Axios in React.js

Async/Await with axios 

  useEffect(() => {     
    const getData = async () => {  
      await axios.get('your_url')  
      .then(res => {  
        console.log(res)  
      })  
      .catch(err => {  
        console.log(err)  
      });  
    }  
    getData()  
  }, [])

Resize font-size according to div size

I found a way of resizing font size according to div size, without any JavaScript. I don't know how much efficient it's, but it nicely gets the job done.

Embed a SVG element inside the required div, and then use a foreignObject tag inside which you can use HTML elements. A sample code snippet that got my job done is given below.

<!-- The SVG element given below should be place inside required div tag -->
<svg viewBox='0 2 108.5 29' xmlns='http://www.w3.org/2000/svg'>
    <!-- The below tag allows adding HTML elements inside SVG tag -->
    <foreignObject x='5' y='0' width='93.5%' height='100%'>
        <!-- The below tag can be styled using CSS classes or style attributes -->
        <div xmlns='http://www.w3.org/1999/xhtml' style='text-overflow: ellipsis; overflow: hidden; white-space: nowrap;'>
            Required text goes here            
        </div>
    </foreignObject>
</svg>

All the viewBox, x, y, width and height values can be changed according to requirement.

Text can be defined inside the SVG element itself, but when the text overflows, ellipsis can't be added to SVG text. So, HTML element(s) are defined inside a foreignObject element, and text-overflow styles are added to that/those element(s).

Array of an unknown length in C#

You can create an array with the size set to a variable, i.e.

int size = 50;
string[] words = new string[size]; // contains 50 strings

However, that size can't change later on, if you decide you need 100 words. If you need the size to be really dynamic, you'll need to use a different sort of data structure. Try List.

How to make google spreadsheet refresh itself every 1 minute?

GOOGLEFINANCE can have a 20 minutes delay, so refreshing every minute would not really help.

Instead of GOOGLEFINANCE you can use different source. I'm using this RealTime stock prices(I tried a couple but this is the easiest by-far to implement. They have API that retuen JSON { Name: CurrentPrice }

Here's a little script you can use in Google Sheets(Tools->Script Editor)

function GetStocksPrice() {      
   var url = 'https://financialmodelingprep.com/api/v3/stock/real-time- 
   price/AVP,BAC,CHK,CY,GE,GPRO,HIMX,IMGN,MFG,NIO,NMR,SSSS,UCTT,UMC,ZNGA';
   var response = UrlFetchApp.fetch(url);

   // convert json string to json object
   var jsonSignal = JSON.parse(response);    

  // define an array of all the object keys
  var headerRow = Object.keys(jsonSignal);
  // define an array of all the object values
  var values = headerRow.map(function(key){ return jsonSignal[key]});   
  var data = values[0];

  // get sheet by ID -  
  // you can get the sheet unqiue ID from the your current sheet url
  var jsonSheet = SpreadsheetApp.openById("Your Sheet UniqueID");  
  //var name = jsonSheet.getName();

  var sheet = jsonSheet.getSheetByName('Sheet1'); 

  // the column to put the data in -> Y
  var letter = "F";

  // start from line 
  var index = 4;
  data.forEach(function( row, index2 ) { 

     var keys = Object.keys(row);
     var value2 = row[keys[1]];            

     // set value loction
     var cellXY = letter +  index;      
     sheet.getRange(cellXY).setValue(value2);  
  
     index = index + 1;    
 });  
}

Now you need to add a trigger that will execute every minute.

  1. Go to Project Triggers -> click on the Watch icon next to the Save icon
  2. Add Trigger
  3. In -> Choose which function to run -> GetStocksPrice
  4. In -> Select event source -> Time-driven
  5. In -> Select type of time based trigger -> Minutes timer
  6. In -> Select minute interval -> Every minute

And your set :)

How to loop through an array of objects in swift

Your userPhotos array is option-typed, you should retrieve the actual underlying object with ! (if you want an error in case the object isn't there) or ? (if you want to receive nil in url):

let userPhotos = currentUser?.photos

for var i = 0; i < userPhotos!.count ; ++i {
    let url = userPhotos![i].url
}

But to preserve safe nil handling, you better use functional approach, for instance, with map, like this:

let urls = userPhotos?.map{ $0.url }

Select default option value from typescript angular 6

i manage this by doing like this =>

<select class="form-control" 
        [(ngModel)]="currentUserID"
        formControlName="users">
        <option value='-1'>{{"select a user" | translate}}</option>
            <option 
            *ngFor="let user of users"
            value="{{user.id}}">
            {{user.firstname}}
   </option>
</select>

MySQL: Fastest way to count number of rows

Perhaps you may want to consider doing a SELECT max(Id) - min(Id) + 1. This will only work if your Ids are sequential and rows are not deleted. It is however very fast.

Visual studio equivalent of java System.out

Use Either Debug.WriteLine() or Trace.WriteLine(). If in release mode, only the latter will appear in the output window, in debug mode, both will.

Make just one slide different size in Powerpoint

if you want to shrink one slide for instance, add shapes to hide the unwanted background margins. you can set the shape color filling as the background (gray or black). It's "ugly" but it works

Javascript Regex: How to put a variable inside a regular expression?

It's only necessary to prepare the string variable first and then convert it to the RegEx.

for example:

You want to add minLength and MaxLength with the variable to RegEx:

function getRegEx() {
    const minLength = "5"; // for exapmle: min is 5
    const maxLength = "12"; // for exapmle: man is 12

    var regEx = "^.{" + minLength + ","+ maxLength +"}$"; // first we make a String variable of our RegEx
    regEx = new RegExp(regEx, "g"); // now we convert it to RegEx

    return regEx; // In the end, we return the RegEx
}

now if you change value of MaxLength or MinLength, It will change in all RegExs.

Hope to be useful. Also sorry about my English.

Mutex example / tutorial?

For those looking for the shortex mutex example:

#include <mutex>

int main() {
    std::mutex m;

    m.lock();
    // do thread-safe stuff
    m.unlock();
}

How to get everything after a certain character?

I use strrchr(). For instance to find the extension of a file I use this function:

$string = 'filename.jpg';
$extension = strrchr( $string, '.'); //returns ".jpg"

Is there a simple way to delete a list element by value?

To remove an element's first occurrence in a list, simply use list.remove:

>>> a = ['a', 'b', 'c', 'd']
>>> a.remove('b')
>>> print(a)
['a', 'c', 'd']

Mind that it does not remove all occurrences of your element. Use a list comprehension for that.

>>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]
>>> a = [x for x in a if x != 20]
>>> print(a)
[10, 30, 40, 30, 40, 70]

"while :" vs. "while true"

from manual:

: [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned.

As this returns always zero therefore is is similar to be used as true

Check out this answer: What Is the Purpose of the `:' (colon) GNU Bash Builtin?

How to let PHP to create subdomain automatically for each user?

I just wanted to add, that if you use CloudFlare (free), you can use their API to manage your dns with ease.

Why would we call cin.clear() and cin.ignore() after reading input?

use cin.ignore(1000,'\n') to clear all of chars of the previous cin.get() in the buffer and it will choose to stop when it meet '\n' or 1000 chars first.

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

According to MSDN, it's 260 characters. It includes "<NUL>" -the invisible terminating null character, so the actual length is 259.

But read the article, it's a bit more complicated.

Which header file do you include to use bool type in c in linux?

Try this header file in your code

stdbool.h

This must work

get current date and time in groovy?

Date has the time as well, just add HH:mm:ss to the date format:

import java.text.SimpleDateFormat
def date = new Date()
def sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
println sdf.format(date)

In case you are using JRE 8 you can use LoaclDateTime:

import java.time.*

LocalDateTime t = LocalDateTime.now();
return t as String

SELECT only rows that contain only alphanumeric characters in MySQL

Try this:

REGEXP '^[a-z0-9]+$'

As regexp is not case sensitive except for binary fields.

How to resolve the C:\fakepath?

Hy there , in my case i am using asp.net development environment, so i was want to upload those data in asynchronus ajax request , in [webMethod] you can not catch the file uploader since it is not static element , so i had to make a turnover for such solution by fixing the path , than convert the wanted image into bytes to save it in DB .

Here is my javascript function , hope it helps you:

function FixPath(Path)
         {
             var HiddenPath = Path.toString();
             alert(HiddenPath.indexOf("FakePath"));

             if (HiddenPath.indexOf("FakePath") > 1)
             {
                 var UnwantedLength = HiddenPath.indexOf("FakePath") + 7;
                 MainStringLength = HiddenPath.length - UnwantedLength;
                 var thisArray =[];
                 var i = 0;
                 var FinalString= "";
                 while (i < MainStringLength)
                 {
                     thisArray[i] = HiddenPath[UnwantedLength + i + 1];
                     i++;
                 }
                 var j = 0;
                 while (j < MainStringLength-1)
                 {
                     if (thisArray[j] != ",")
                     {
                         FinalString += thisArray[j];
                     }
                     j++;
                 }
                 FinalString = "~" + FinalString;
                 alert(FinalString);
                 return FinalString;
             }
             else
             {
                 return HiddenPath;
             }
         }

here only for testing :

 $(document).ready(function () {
             FixPath("hakounaMatata:/7ekmaTa3mahaLaziz/FakePath/EnsaLmadiLiYghiz");
         });
// this will give you : ~/EnsaLmadiLiYghiz

When creating a service with sc.exe how to pass in context parameters?

I use to just create it without parameters, and then edit the registry HKLM\System\CurrentControlSet\Services\[YourService].

The type or namespace cannot be found (are you missing a using directive or an assembly reference?)

I get this error when my project .net framework version does not match the framework version of the DLL I am linking to. In my case, I was getting:

"The type or namespace name 'UserVoice' could not be found (are you missing a using directive or an assembly reference?).

UserVoice was .Net 4.0, and my project properties were set to ".Net 4.0 Client Profile". Changing to .Net 4.0 on the project cleared the error. I hope this helps someone.

How to "test" NoneType in python?

It can also be done with isinstance as per Alex Hall's answer :

>>> NoneType = type(None)
>>> x = None
>>> type(x) == NoneType
True
>>> isinstance(x, NoneType)
True

isinstance is also intuitive but there is the complication that it requires the line

NoneType = type(None)

which isn't needed for types like int and float.

Alternating Row Colors in Bootstrap 3 - No Table

Since you are using bootstrap and you want alternating row colors for every screen sizes you need to write separate style rules for all the screen sizes.

/* For small screen */
.row :nth-child(even){
  background-color: #dcdcdc;
}
.row :nth-child(odd){
  background-color: #aaaaaa;
}

/* For medium screen */    
@media (min-width: 768px) {
    .row :nth-child(4n), .row :nth-child(4n-1) {
        background: #dcdcdc;
    }
    .row :nth-child(4n-2), .row :nth-child(4n-3) {
        background: #aaaaaa;
    }
}

/* For large screen */
@media (min-width: 992px) {
    .row :nth-child(6n), .row :nth-child(6n-1), .row :nth-child(6n-2) {
        background: #dcdcdc;
    }
    .row :nth-child(6n-3), .row :nth-child(6n-4), .row :nth-child(6n-5) {
        background: #aaaaaa;
    }
}

Working FIDDLE
I have also included the bootstrap CSS here.

Text Editor which shows \r\n?

Sublime Text 3 has a plugin called RawLineEdit that will display line endings and allow the insertion of arbitrary line-ending type:

https://github.com/facelessuser/RawLineEdit

npm install error - unable to get local issuer certificate

Anyone gets this error when 'npm install' is trying to fetch a package from HTTPS server with a self-signed or invalid certificate.

Quick and insecure solution:

npm config set strict-ssl false

Why this solution is insecure? The above command tells npm to connect and fetch module from server even server do not have valid certificate and server identity is not verified. So if there is a proxy server between npm client and actual server, it provided man in middle attack opportunity to an intruder.

Secure solution:

If any module in your package.json is hosted on a server with self-signed CA certificate then npm is unable to identify that server with an available system CA certificates. So you need to provide CA certificate for server validation with the explicit configuration in .npmrc. In .npmrc you need to provide cafile, please refer more detail about cafile configuration here

cafile=./ca-certs.pem

In ca-certs file, you can add any number of CA certificates(public) that you required to identify servers. The certificate should be in “Base-64 encoded X.509 (.CER)(PEM)” format.

For example,

# cat ca-certs.pem 
DigiCert Global Root CA
=======================
-----BEGIN CERTIFICATE-----
CAUw7C29C79Fv1C5qfPrmAE.....
-----END CERTIFICATE-----

VeriSign Class 3 Public Primary Certification Authority - G5
========================================
-----BEGIN CERTIFICATE-----
MIIE0zCCA7ugAwIBAgIQ......
-----END CERTIFICATE-----

Note: once you provide cafile configuration in .npmrc, npm try to identify all server using CA certificate(s) provided in cafile only, it won't check system CA certificate bundles then. If someone wants all well-known public CA authority certificat bundle then can get from here.

One other situation when you get this error:

If you have mentioned Git URL as a dependency in package.json and git is on invalid/self-signed certificate then also npm throws a similar error. You can fix it with following configuration for git client

git config --global http.sslVerify false 

Objective-C : BOOL vs bool

From the definition in objc.h:

#if (TARGET_OS_IPHONE && __LP64__)  ||  TARGET_OS_WATCH
typedef bool BOOL;
#else
typedef signed char BOOL; 
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C" 
// even if -funsigned-char is used.
#endif

#define YES ((BOOL)1)
#define NO  ((BOOL)0)

So, yes, you can assume that BOOL is a char. You can use the (C99) bool type, but all of Apple's Objective-C frameworks and most Objective-C/Cocoa code uses BOOL, so you'll save yourself headache if the typedef ever changes by just using BOOL.

What do Clustered and Non clustered index actually mean?

Clustered Index: Primary Key constraint creates clustered Index automatically if no clustered Index already exists on the table. Actual data of clustered index can be stored at leaf level of Index.

Non Clustered Index: Actual data of non clustered index is not directly found at leaf node, instead it has to take an additional step to find because it has only values of row locators pointing towards actual data. Non clustered Index can't be sorted as clustered index. There can be multiple non clustered indexes per table, actually it depends on the sql server version we are using. Basically Sql server 2005 allows 249 Non Clustered Indexes and for above versions like 2008, 2016 it allows 999 Non Clustered Indexes per table.

How to write to Console.Out during execution of an MSTest test

I found a solution of my own. I know that Andras answer is probably the most consistent with MSTEST, but I didn't feel like refactoring my code.

[TestMethod]
public void OneIsOne()
{
    using (ConsoleRedirector cr = new ConsoleRedirector())
    {
        Assert.IsFalse(cr.ToString().Contains("New text"));
        /* call some method that writes "New text" to stdout */
        Assert.IsTrue(cr.ToString().Contains("New text"));
    }
}

The disposable ConsoleRedirector is defined as:

internal class ConsoleRedirector : IDisposable
{
    private StringWriter _consoleOutput = new StringWriter();
    private TextWriter _originalConsoleOutput;
    public ConsoleRedirector()
    {
        this._originalConsoleOutput = Console.Out;
        Console.SetOut(_consoleOutput);
    }
    public void Dispose()
    {
        Console.SetOut(_originalConsoleOutput);
        Console.Write(this.ToString());
        this._consoleOutput.Dispose();
    }
    public override string ToString()
    {
        return this._consoleOutput.ToString();
    }
}

Returning a value even if no result

Do search with LEFT OUTER JOIN. I don't know if MySQL allows inline VALUES in join clauses but you can have predefined table for this purposes.

Getting json body in aws Lambda via API gateway

I think there are a few things to understand when working with API Gateway integration with Lambda.

Lambda Integration vs Lambda Proxy Integration

There used to be only Lambda Integration which requires mapping templates. I suppose this is why still seeing many examples using it.

As of September 2017, you no longer have to configure mappings to access the request body.

Lambda Proxy Integration, If you enable it, API Gateway will map every request to JSON and pass it to Lambda as the event object. In the Lambda function you’ll be able to retrieve query string parameters, headers, stage variables, path parameters, request context, and the body from it.

Without enabling Lambda Proxy Integration, you’ll have to create a mapping template in the Integration Request section of API Gateway and decide how to map the HTTP request to JSON yourself. And you’d likely have to create an Integration Response mapping if you were to pass information back to the client.

Before Lambda Proxy Integration was added, users were forced to map requests and responses manually, which was a source of consternation, especially with more complex mappings.

Words need to navigate the thinking. To get the terminologies straight.

  • Lambda Proxy Integration = Pass through
    Simply pass the HTTP request through to lambda.

  • Lambda Integration = Template transformation
    Go through a transformation process using the Apache Velocity template and you need to write the template by yourself.

body is escaped string, not JSON

Using Lambda Proxy Integration, the body in the event of lambda is a string escaped with backslash, not a JSON.

"body": "{\"foo\":\"bar\"}" 

If tested in a JSON formatter.

Parse error on line 1:
{\"foo\":\"bar\"}
-^
Expecting 'STRING', '}', got 'undefined'

The document below is about response but it should apply to request.

The body field, if you are returning JSON, must be converted to a string or it will cause further problems with the response. You can use JSON.stringify to handle this in Node.js functions; other runtimes will require different solutions, but the concept is the same.

For JavaScript to access it as a JSON object, need to convert it back into JSON object with json.parse in JapaScript, json.dumps in Python.

Strings are useful for transporting but you’ll want to be able to convert them back to a JSON object on the client and/or the server side.

The AWS documentation shows what to do.

if (event.body !== null && event.body !== undefined) {
    let body = JSON.parse(event.body)
    if (body.time) 
        time = body.time;
}
...
var response = {
    statusCode: responseCode,
    headers: {
        "x-custom-header" : "my custom header value"
    },
    body: JSON.stringify(responseBody)
};
console.log("response: " + JSON.stringify(response))
callback(null, response);

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();

Delete rows with foreign key in PostgreSQL

You can't delete a foreign key if it still references another table. First delete the reference

delete from kontakty
where id_osoby = 1;

DELETE FROM osoby 
WHERE id_osoby = 1;

Flexbox: 4 items per row

Here's another way without using calc().

// 4 PER ROW
// 100 divided by 4 is 25. Let's use 21% for width, and the remainder 4% for left & right margins...
.child {
  margin: 0 2% 0 2%;
  width: 21%;
}

// 3 PER ROW
// 100 divided by 3 is 33.3333... Let's use 30% for width, and remaining 3.3333% for sides (hint: 3.3333 / 2 = 1.66666)
.child {
  margin: 0 1.66666% 0 1.66666%;
  width: 30%;
}

// and so on!

That's all there is to it. You can get fancy with the dimensions to get a more aesthetic sizes but this is the idea.

How does String.Index work in Swift

Create a UITextView inside of a tableViewController. I used function: textViewDidChange and then checked for return-key-input. then if it detected return-key-input, delete the input of return key and dismiss keyboard.

func textViewDidChange(_ textView: UITextView) {
    tableView.beginUpdates()
    if textView.text.contains("\n"){
        textView.text.remove(at: textView.text.index(before: textView.text.endIndex))
        textView.resignFirstResponder()
    }
    tableView.endUpdates()
}

Capture keyboardinterrupt in Python without try-except

An alternative to setting your own signal handler is to use a context-manager to catch the exception and ignore it:

>>> class CleanExit(object):
...     def __enter__(self):
...             return self
...     def __exit__(self, exc_type, exc_value, exc_tb):
...             if exc_type is KeyboardInterrupt:
...                     return True
...             return exc_type is None
... 
>>> with CleanExit():
...     input()    #just to test it
... 
>>>

This removes the try-except block while preserving some explicit mention of what is going on.

This also allows you to ignore the interrupt only in some portions of your code without having to set and reset again the signal handlers everytime.

How do I add an image to a JButton

This code work for me:

    BufferedImage image = null;
    try {
        URL file = getClass().getResource("water.bmp");
        image = ImageIO.read(file);
    } catch (IOException ioex) {
        System.err.println("load error: " + ioex.getMessage());
    }
    ImageIcon icon = new ImageIcon(image);
    JButton quitButton = new JButton(icon);

how to get value of selected item in autocomplete

To answer the question more generally, the answer is:

select: function( event , ui ) {
    alert( "You selected: " + ui.item.label );
}

Complete example :

_x000D_
_x000D_
$('#test').each(function(i, el) {_x000D_
    var that = $(el);_x000D_
    that.autocomplete({_x000D_
        source: ['apple','banana','orange'],_x000D_
        select: function( event , ui ) {_x000D_
            alert( "You selected: " + ui.item.label );_x000D_
        }_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>_x000D_
_x000D_
Type a fruit here: <input type="text" id="test" />
_x000D_
_x000D_
_x000D_

How can I create an error 404 in PHP?

In the Drupal or Wordpress CMS (and likely others), if you are trying to make some custom php code appear not to exist (unless some condition is met), the following works well by making the CMS's 404 handler take over:

<?php
  if(condition){
    do stuff;
  } else {
    include('index.php');
  }
?>

NumPy array is not JSON serializable

Store as JSON a numpy.ndarray or any nested-list composition.

class NumpyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape)
json_dump = json.dumps({'a': a, 'aa': [2, (2, 3, 4), a], 'bb': [2]}, cls=NumpyEncoder)
print(json_dump)

Will output:

(2, 3)
{"a": [[1, 2, 3], [4, 5, 6]], "aa": [2, [2, 3, 4], [[1, 2, 3], [4, 5, 6]]], "bb": [2]}

To restore from JSON:

json_load = json.loads(json_dump)
a_restored = np.asarray(json_load["a"])
print(a_restored)
print(a_restored.shape)

Will output:

[[1 2 3]
 [4 5 6]]
(2, 3)

Gson and deserializing an array of objects with arrays in it

Use your bean class like this, if your JSON data starts with an an array object. it helps you.

Users[] bean = gson.fromJson(response,Users[].class);

Users is my bean class.

Response is my JSON data.

Random date in C#

private Random gen = new Random();
DateTime RandomDay()
{
    DateTime start = new DateTime(1995, 1, 1);
    int range = (DateTime.Today - start).Days;           
    return start.AddDays(gen.Next(range));
}

For better performance if this will be called repeatedly, create the start and gen (and maybe even range) variables outside of the function.

switch case statement error: case expressions must be constant expression

Simple solution for this problem is :

Click on the switch and then press CTL+1, It will change your switch to if-else block statement, and will resolve your problem