Programs & Examples On #Lotus domino

Domino is the server component of IBM Lotus Software Messaging and Collaboration offerings. A typical Domino server supports a variety of applications and protocols that clients can use to access those applications. Applications out-of-the-box include E Mail, Calendaring and other Personal Information Management, Discussions, Teamrooms and many others. Protocols supported are include HTTP, HTTPS, SMTP, POP3, IMAP, as well as the RPC protocol for Notes.

Not able to pip install pickle in python 3.6

You can pip install pickle by running command pip install pickle-mixin. Proceed to import it using import pickle. This can be then used normally.

How to retrieve GET parameters from JavaScript

This solution handles URL decoding:

var params = function() {
    function urldecode(str) {
        return decodeURIComponent((str+'').replace(/\+/g, '%20'));
    }

    function transformToAssocArray( prmstr ) {
        var params = {};
        var prmarr = prmstr.split("&");
        for ( var i = 0; i < prmarr.length; i++) {
            var tmparr = prmarr[i].split("=");
            params[tmparr[0]] = urldecode(tmparr[1]);
        }
        return params;
    }

    var prmstr = window.location.search.substr(1);
    return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}();

Usage:

console.log('someParam GET value is', params['someParam']);

python global name 'self' is not defined

The self name is used as the instance reference in class instances. It is only used in class method definitions. Don't use it in functions.

You also cannot reference local variables from other functions or methods with it. You can only reference instance or class attributes using it.

How to define constants in Visual C# like #define in C?

public const int NUMBER = 9;

You'd need to put it in a class somewhere, and the usage would be ClassName.NUMBER

Getting all names in an enum as a String[]

Another ways :

First one

Arrays.asList(FieldType.values())
            .stream()
            .map(f -> f.toString())
            .toArray(String[]::new);

Other way

Stream.of(FieldType.values()).map(f -> f.toString()).toArray(String[]::new);

Have a fixed position div that needs to scroll if content overflows

Leaving an answer for anyone looking to do something similar but in a horizontal direction, like I wanted to.

Tweaking @strider820's answer like below will do the magic:

.fixed-content {        //comments showing what I replaced.
    left:0;             //top: 0;
    right:0;            //bottom:0;
    position:fixed;
    overflow-y:hidden;  //overflow-y:scroll;
    overflow-x:auto;    //overflow-x:hidden;
}

That's it. Also check this comment where @train explained using overflow:auto over overflow:scroll.

How do I properly escape quotes inside HTML attributes?

If you are using Javascript and Lodash, then you can use _.escape(), which escapes ", ', <, >, and &.

See here: https://lodash.com/docs/#escape

getting "No column was specified for column 2 of 'd'" in sql server cte?

Quite an intuitive error message - just need to give the columns in d names

Change to either this

d as 
 (
  select                 
     [duration] = month(clothdeliverydate),                 
     [bkdqty] = SUM(CONVERT(INT, deliveredqty))             
  FROM                 
     barcodetable            
  where                 
     month(clothdeliverydate) is not null                
  group by month(clothdeliverydate)           
 ) 

Or you can explicitly declare the fields in the definition of the cte:

d ([duration], [bkdqty]) as 
 (
  select                 
     month(clothdeliverydate),                 
     SUM(CONVERT(INT, deliveredqty))             
  FROM                 
     barcodetable            
  where                 
     month(clothdeliverydate) is not null                
  group by month(clothdeliverydate)           
 ) 

Elegant Python function to convert CamelCase to snake_case?

There's an inflection library in the package index that can handle these things for you. In this case, you'd be looking for inflection.underscore():

>>> inflection.underscore('CamelCase')
'camel_case'

Error inflating class android.support.design.widget.NavigationView

As Parag Naik correctly mentions (and L?ng Hoàng expands on), the problem arises when setting textColorPrimary to something other than a color state list. So you could set textColorPrimary as a state list. There is an issue in the android bug tracker about colorPrimary being a state list with only one color: https://code.google.com/p/android/issues/detail?id=172353

So for your theme in styles.xml:

<style name="Base.Theme.Hopster" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="colorAccent">@color/accent</item>

    <item name="android:textColorPrimary">@color/primary_color_statelist</item>
</style>

And the actual primary_color_statelist.xml file:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- This is used when the Navigation Item is checked -->
    <item android:color="@color/primary_text_selected" android:state_checked="true" />
    <!-- This is the default text color -->
    <item android:color="@color/primary_text" />
</selector>

How can I perform static code analysis in PHP?

I have tried using php -l and a couple of other tools.

However, the best one in my experience (your mileage may vary, of course) is scheck of pfff toolset. I heard about pfff on Quora (Is there a good PHP lint / static analysis tool?).

You can compile and install it. There are no nice packages (on my Linux Mint Debian system, I had to install the libpcre3-dev, ocaml, libcairo-dev, libgtk-3-dev and libgimp2.0-dev dependencies first) but it should be worth an install.

The results are reported like

$ ~/sw/pfff/scheck ~/code/github/sc/
login-now.php:7:4: CHECK: Unused Local variable $title
go-automatic.php:14:77: CHECK: Use of undeclared variable $goUrl.

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

How to get directory size in PHP

This is the simplest possible algorithm to find out directory size irrespective of the programming language you are using. For PHP specific implementation. go to: Calculate Directory Size in PHP | Explained with Algorithm | Working Code

Query to display all tablespaces in a database and datafiles

Neither databases, nor tablespaces nor data files belong to any user. Are you coming to this from an MS SQL background?

select tablespace_name, 
       file_name
from dba_tablespaces
order by tablespace_name, 
         file_name;

How to create a oracle sql script spool file

This will spool the output from the anonymous block into a file called output_<YYYYMMDD>.txt located in the root of the local PC C: drive where <YYYYMMDD> is the current date:

SET SERVEROUTPUT ON FORMAT WRAPPED
SET VERIFY OFF

SET FEEDBACK OFF
SET TERMOUT OFF

column date_column new_value today_var
select to_char(sysdate, 'yyyymmdd') date_column
  from dual
/
DBMS_OUTPUT.ENABLE(1000000);

SPOOL C:\output_&today_var..txt

DECLARE
   ab varchar2(10) := 'Raj';
   cd varchar2(10);
   a  number := 10;
   c  number;
   d  number; 
BEGIN
   c := a+10;
   --
   SELECT ab, c 
     INTO cd, d 
     FROM dual;
   --
   DBMS_OUTPUT.put_line('cd: '||cd);
   DBMS_OUTPUT.put_line('d: '||d);
END; 

SPOOL OFF

SET TERMOUT ON
SET FEEDBACK ON
SET VERIFY ON

PROMPT
PROMPT Done, please see file C:\output_&today_var..txt
PROMPT

Hope it helps...

EDIT:

After your comment to output a value for every iteration of a cursor (I realise each value will be the same in this example but you should get the gist of what i'm doing):

BEGIN
   c := a+10;
   --
   FOR i IN 1 .. 10
   LOOP
      c := a+10;
      -- Output the value of C
      DBMS_OUTPUT.put_line('c: '||c);
   END LOOP;
   --
END; 

Difference between onStart() and onResume()

Hopefully a simple explanation : -

onStart() -> called when the activity becomes visible, but might not be in the foreground (e.g. an AlertFragment is on top or any other possible use case).

onResume() -> called when the activity is in the foreground, or the user can interact with the Activity.

How can I select all options of multi-select select box on click?

try

$('#select_all').click( function() {
    $('#countries option').each(function(){
        $(this).attr('selected', 'selected');
    });
});

this will give you more scope in the future to write things like

$('#select_all').click( function() {
    $('#countries option').each(function(){
        if($(this).attr('something') != 'omit parameter')
        {
            $(this).attr('selected', 'selected');
        }
    });
});

Basically allows for you to do a select all EU members or something if required later down the line

Put buttons at bottom of screen with LinearLayout?

Create Relative layout and inside that layout create your button with this line

android:layout_alignParentBottom="true"

How to terminate a process in vbscript

The Win32_Process class provides access to both 32-bit and 64-bit processes when the script is run from a 64-bit command shell.

If this is not an option for you, you can try using the taskkill command:

Dim oShell : Set oShell = CreateObject("WScript.Shell")

' Launch notepad '
oShell.Run "notepad"
WScript.Sleep 3000

' Kill notepad '
oShell.Run "taskkill /im notepad.exe", , True

LaTeX: Multiple authors in a two-column article

What about using a tabular inside \author{}, just like in IEEE macros:

\documentclass{article}
\begin{document}
\title{Hello, World}
\author{
\begin{tabular}[t]{c@{\extracolsep{8em}}c} 
I. M. Author  & M. Y. Coauthor \\
My Department & Coauthor Department \\ 
My Institute & Coauthor Institute \\
email, address & email, address
\end{tabular}
}
\maketitle    
\end{document}

This will produce two columns authors with any documentclass.

Results:

enter image description here

How to add a linked source folder in Android Studio?

The right answer is:

android {
    ....
    ....

    sourceSets {
        main.java.srcDirs += 'src/main/<YOUR DIRECTORY>'
    }
}

Furthermore, if your external source directory is not under src/main, you could use a relative path like this:

sourceSets {
    main.java.srcDirs += 'src/main/../../../<YOUR DIRECTORY>'
}

Trying to pull files from my Github repository: "refusing to merge unrelated histories"

While I'm all for unblocking people's work issues, I don't think "push --force" or "--allow_unrelated_histories" should be taught to new users as general solutions because they can cause real havoc to a repository when one uses them without understand why things aren't working in the first place.

When you have a situation like this where you started with a local repository, and want to make a remote on GitHub to share your work with, there is something to watch out for.

When you create the new online repository, there's an option "Initialize this repository with a README". If you read the fine print, it says "Skip this step if you’re importing an existing repository."

You may have checked that box. Or similarly, you made an add/commit online before you attempted an initial push. What happens is you create a unique commit history in each place and they can't be reconciled without the special allowance mentioned in Nevermore's answer (because git doesn't want you to operate that way). You can follow some of the advice mentioned here, or more simply just don't check that option next time you want to link some local files to a brand new remote; keeping the remote clean for that initial push.

Reference: my first experience with git + hub was to run into this same problem and do a lot of learning to understand what had happened and why.

Delete all rows in table

You can rename the table in question, create a table with an identical schema, and then drop the original table at your leisure.

See the MySQL 5.1 Reference Manual for the [RENAME TABLE][1] and [CREATE TABLE][2] commands.

RENAME TABLE tbl TO tbl_old;

CREATE TABLE tbl LIKE tbl_old;

DROP TABLE tbl_old; -- at your leisure

This approach can help minimize application downtime.

Windows command for file size only

This is not exactly what you were asking about and it can only be used from the command line (and may be useless in a batch file), but one quick way to check file size is just to use dir:

> dir Microsoft.WindowsAzure.Storage.xml

Results in:

Directory of C:\PathToTheFile

08/10/2015  10:57 AM         2,905,897 Microsoft.WindowsAzure.Storage.xml
               1 File(s)      2,905,897 bytes
               0 Dir(s)  759,192,064,000 bytes free

How can I link to a specific glibc version?

You are correct in that glibc uses symbol versioning. If you are curious, the symbol versioning implementation introduced in glibc 2.1 is described here and is an extension of Sun's symbol versioning scheme described here.

One option is to statically link your binary. This is probably the easiest option.

You could also build your binary in a chroot build environment, or using a glibc-new => glibc-old cross-compiler.

According to the http://www.trevorpounds.com blog post Linking to Older Versioned Symbols (glibc), it is possible to to force any symbol to be linked against an older one so long as it is valid by using the same .symver pseudo-op that is used for defining versioned symbols in the first place. The following example is excerpted from the blog post.

The following example makes use of glibc’s realpath, but makes sure it is linked against an older 2.2.5 version.

#include <limits.h>
#include <stdlib.h>
#include <stdio.h>

__asm__(".symver realpath,realpath@GLIBC_2.2.5");
int main()
{
    const char* unresolved = "/lib64";
    char resolved[PATH_MAX+1];

    if(!realpath(unresolved, resolved))
        { return 1; }

    printf("%s\n", resolved);

    return 0;
}

Prevent text selection after double click

Old thread, but I came up with a solution that I believe is cleaner since it does not disable every even bound to the object, and only prevent random and unwanted text selections on the page. It is straightforward, and works well for me. Here is an example; I want to prevent text-selection when I click several time on the object with the class "arrow-right":

$(".arrow-right").hover(function(){$('body').css({userSelect: "none"});}, function(){$('body').css({userSelect: "auto"});});

HTH !

Efficiently convert rows to columns in sql server

There are several ways that you can transform data from multiple rows into columns.

Using PIVOT

In SQL Server you can use the PIVOT function to transform the data from rows to columns:

select Firstname, Amount, PostalCode, LastName, AccountNumber
from
(
  select value, columnname
  from yourtable
) d
pivot
(
  max(value)
  for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;

See Demo.

Pivot with unknown number of columnnames

If you have an unknown number of columnnames that you want to transpose, then you can use dynamic SQL:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName) 
                    from yourtable
                    group by ColumnName, id
                    order by id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = N'SELECT ' + @cols + N' from 
             (
                select value, ColumnName
                from yourtable
            ) x
            pivot 
            (
                max(value)
                for ColumnName in (' + @cols + N')
            ) p '

exec sp_executesql @query;

See Demo.

Using an aggregate function

If you do not want to use the PIVOT function, then you can use an aggregate function with a CASE expression:

select
  max(case when columnname = 'FirstName' then value end) Firstname,
  max(case when columnname = 'Amount' then value end) Amount,
  max(case when columnname = 'PostalCode' then value end) PostalCode,
  max(case when columnname = 'LastName' then value end) LastName,
  max(case when columnname = 'AccountNumber' then value end) AccountNumber
from yourtable

See Demo.

Using multiple joins

This could also be completed using multiple joins, but you will need some column to associate each of the rows which you do not have in your sample data. But the basic syntax would be:

select fn.value as FirstName,
  a.value as Amount,
  pc.value as PostalCode,
  ln.value as LastName,
  an.value as AccountNumber
from yourtable fn
left join yourtable a
  on fn.somecol = a.somecol
  and a.columnname = 'Amount'
left join yourtable pc
  on fn.somecol = pc.somecol
  and pc.columnname = 'PostalCode'
left join yourtable ln
  on fn.somecol = ln.somecol
  and ln.columnname = 'LastName'
left join yourtable an
  on fn.somecol = an.somecol
  and an.columnname = 'AccountNumber'
where fn.columnname = 'Firstname'

C# DataRow Empty-check

I did it like this:

var listOfRows = new List<DataRow>();
foreach (var row in resultTable.Rows.Cast<DataRow>())
{
    var isEmpty = row.ItemArray.All(x => x == null || (x!= null && string.IsNullOrWhiteSpace(x.ToString())));
    if (!isEmpty)
    {
        listOfRows.Add(row);
    }
}

Sorting int array in descending order

For primitive array types, you would have to write a reverse sort algorithm:

Alternatively, you can convert your int[] to Integer[] and write a comparator:

public class IntegerComparator implements Comparator<Integer> {

    @Override
    public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
    }
}

or use Collections.reverseOrder() since it only works on non-primitive array types.

and finally,

Integer[] a2 = convertPrimitiveArrayToBoxableTypeArray(a1);
Arrays.sort(a2, new IntegerComparator()); // OR
// Arrays.sort(a2, Collections.reverseOrder());

//Unbox the array to primitive type
a1 = convertBoxableTypeArrayToPrimitiveTypeArray(a2);

Why is there no ForEach extension method on IEnumerable?

No one has yet pointed out that ForEach<T> results in compile time type checking where the foreach keyword is runtime checked.

Having done some refactoring where both methods were used in the code, I favor .ForEach, as I had to hunt down test failures / runtime failures to find the foreach problems.

Convert datetime to Unix timestamp and convert it back in python

For working with UTC timezones:

time_stamp = calendar.timegm(dt.timetuple())

datetime.utcfromtimestamp(time_stamp)

Turn off warnings and errors on PHP and MySQL

PHP error_reporting reference:

// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

Wrapping text inside input type="text" element HTML/CSS

To create a text input in which the value under the hood is a single line string but is presented to the user in a word-wrapped format you can use the contenteditable attribute on a <div> or other element:

_x000D_
_x000D_
const el = document.querySelector('div[contenteditable]');_x000D_
_x000D_
// Get value from element on input events_x000D_
el.addEventListener('input', () => console.log(el.textContent));_x000D_
_x000D_
// Set some value_x000D_
el.textContent = 'Lorem ipsum curae magna venenatis mattis, purus luctus cubilia quisque in et, leo enim aliquam consequat.'
_x000D_
div[contenteditable] {_x000D_
  border: 1px solid black;_x000D_
  width: 200px;_x000D_
}
_x000D_
<div contenteditable></div>
_x000D_
_x000D_
_x000D_

Cross origin requests are only supported for HTTP but it's not cross-domain

It works best this way. Make sure that both files are on the server. When calling the html page, make use of the web address like: http:://localhost/myhtmlfile.html, and not, C::///users/myhtmlfile.html. Make usre as well that the url passed to the json is a web address as denoted below:

$(function(){
                $('#typeahead').typeahead({
                    source: function(query, process){
                        $.ajax({
                            url: 'http://localhost:2222/bootstrap/source.php',
                            type: 'POST',
                            data: 'query=' +query,
                            dataType: 'JSON',
                            async: true,
                            success: function(data){
                                process(data);
                            }
                        });
                    }
                });
            });

Bootstrap 3 grid with no gap

Generalizing on martinedwards and others' ideas, you can glue a bunch of columns together (not just a pair) by adjusting padding of even and odd column children. Adding this definition of a class, .no-gutter, and placing it on your .row element

.row.no-gutter > [class*='col-']:nth-child(2n+1) {
    padding-right: 0;
 } 

.row.no-gutter > [class*='col-']:nth-child(2n) {
    padding-left: 0;
}

Or in SCSS:

.no-gutter  {
    > [class*='col-'] {
        &:nth-child(2n+1) {
            padding-right: 0;
        }
        &:nth-child(2n) {
            padding-left: 0;
        }
    }
}

How can I use Ruby to colorize the text output to a terminal?

You can use ANSI escape sequences to do this on the console. I know this works on Linux and OSX, I'm not sure if the Windows console (cmd) supports ANSI.

I did it in Java, but the ideas are the same.

//foreground color
public static final String BLACK_TEXT()   { return "\033[30m";}
public static final String RED_TEXT()     { return "\033[31m";}
public static final String GREEN_TEXT()   { return "\033[32m";}
public static final String BROWN_TEXT()   { return "\033[33m";}
public static final String BLUE_TEXT()    { return "\033[34m";}
public static final String MAGENTA_TEXT() { return "\033[35m";}
public static final String CYAN_TEXT()    { return "\033[36m";}
public static final String GRAY_TEXT()    { return "\033[37m";}

//background color
public static final String BLACK_BACK()   { return "\033[40m";}
public static final String RED_BACK()     { return "\033[41m";}
public static final String GREEN_BACK()   { return "\033[42m";}
public static final String BROWN_BACK()   { return "\033[43m";}
public static final String BLUE_BACK()    { return "\033[44m";}
public static final String MAGENTA_BACK() { return "\033[45m";}
public static final String CYAN_BACK()    { return "\033[46m";}
public static final String WHITE_BACK()   { return "\033[47m";}

//ANSI control chars
public static final String RESET_COLORS() { return "\033[0m";}
public static final String BOLD_ON()      { return "\033[1m";}
public static final String BLINK_ON()     { return "\033[5m";}
public static final String REVERSE_ON()   { return "\033[7m";}
public static final String BOLD_OFF()     { return "\033[22m";}
public static final String BLINK_OFF()    { return "\033[25m";}
public static final String REVERSE_OFF()  { return "\033[27m";}

How to print instances of a class using print()?

As Chris Lutz mentioned, this is defined by the __repr__ method in your class.

From the documentation of repr():

For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.

Given the following class Test:

class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return "<Test a:%s b:%s>" % (self.a, self.b)

    def __str__(self):
        return "From str method of Test: a is %s, b is %s" % (self.a, self.b)

..it will act the following way in the Python shell:

>>> t = Test(123, 456)
>>> t
<Test a:123 b:456>
>>> print repr(t)
<Test a:123 b:456>
>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456

If no __str__ method is defined, print(t) (or print(str(t))) will use the result of __repr__ instead

If no __repr__ method is defined then the default is used, which is pretty much equivalent to..

def __repr__(self):
    return "<%s instance at %s>" % (self.__class__.__name__, id(self))

How to force IE10 to render page in IE9 document mode

Do you mean you want to tell your copy of IE 10 to render the pages it views in IE 9 mode?

Or do you mean you want your website to force IE 10 to render it in IE 9 mode?

For the former:

To force a webpage you are viewing in Internet Explorer 10 into a particular document compatibility mode, first open F12 Tools by pressing the F12 key. Then, on the Browser Mode menu, click Internet Explorer 10, and on the Document Mode menu, click Standards.

http://msdn.microsoft.com/en-gb/library/ie/hh920756(v=vs.85).aspx

For the latter, the other answers are correct, but I wouldn't advise doing that. IE 10 is more standards-compliant (i.e. more similar to other browsers) than IE 9.

What's the easiest way to escape HTML in Python?

There is also the excellent markupsafe package.

>>> from markupsafe import Markup, escape
>>> escape("<script>alert(document.cookie);</script>")
Markup(u'&lt;script&gt;alert(document.cookie);&lt;/script&gt;')

The markupsafe package is well engineered, and probably the most versatile and Pythonic way to go about escaping, IMHO, because:

  1. the return (Markup) is a class derived from unicode (i.e. isinstance(escape('str'), unicode) == True
  2. it properly handles unicode input
  3. it works in Python (2.6, 2.7, 3.3, and pypy)
  4. it respects custom methods of objects (i.e. objects with a __html__ property) and template overloads (__html_format__).

How to see tomcat is running or not

open your browser,check whether Tomcat homepage is visible by below command.

http://ipaddress:portnumber

also check this

How to do scanf for single char in C

neither fgets nor getchar works to solve the problem. the only workaround is keeping a space before %c while using scanf scanf(" %c",ch); // will only work

In the follwing fgets also not work..

char line[256];
char ch;
int i;

printf("Enter a num : ");
scanf("%d",&i);
printf("Enter a char : ");

if (fgets(line, sizeof line, stdin) == NULL) {
    printf("Input error.\n");
    exit(1);
}

ch = line[0];
printf("Character read: %c\n", ch);

How to export datagridview to excel using vb.net?

Regarding your need to 'print directly from datagridview', check out this article on CodeProject:

The DataGridViewPrinter Class

There are a number of similar articles but I've had luck with the one I linked.

Java RegEx meta character (.) and ordinary dot?

Perl-style regular expressions (which the Java regex engine is more or less based upon) treat the following characters as special characters:

.^$|*+?()[{\ have special meaning outside of character classes,

]^-\ have special meaning inside of character classes ([...]).

So you need to escape those (and only those) symbols depending on context (or, in the case of character classes, place them in positions where they can't be misinterpreted).

Needlessly escaping other characters may work, but some regex engines will treat this as syntax errors, for example \_ will cause an error in .NET.

Some others will lead to false results, for example \< is interpreted as a literal < in Perl, but in egrep it means "word boundary".

So write -?\d+\.\d+\$ to match 1.50$, -2.00$ etc. and [(){}[\]] for a character class that matches all kinds of brackets/braces/parentheses.

If you need to transform a user input string into a regex-safe form, use java.util.regex.Pattern.quote.

Further reading: Jan Goyvaert's blog RegexGuru on escaping metacharacters

How to set NODE_ENV to production/development in OS X

In order to have multiple environments you need all of the answers before (NODE_ENV parameter and export it), but I use a very simple approach without the need of installing anything. In your package.json just put a script for each env you need, like this:

...
"scripts": {
    "start-dev": "export NODE_ENV=dev && ts-node-dev --respawn --transpileOnly ./src/app.ts",
    "start-prod": "export NODE_ENV=prod && ts-node-dev --respawn --transpileOnly ./src/app.ts"
  }
 ...

Then, to start the app instead of using npm start use npm run script-prod.

In the code you can access the current environment with process.env.NODE_ENV.

Voila.

Error message 'java.net.SocketException: socket failed: EACCES (Permission denied)'

If you are using an emulator for testing then you must use <uses-permission android:name="android.permission.INTERNET" />only and ignore <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />.It's work for me.

How to hide TabPage from TabControl

Well, if you don't want to mess up existing code and just want to hide a tab, you could modify the compiler generated code to comment the line which adds the tab to the tabcontrol.

For example: The following line adds a tab named "readformatcardpage" to a Tabcontrol named "tabcontrol"

this.tabcontrol.Controls.Add(this.readformatcardpage);

The following will prevent addition of the tab to the tabcontrol

//this.tabcontrol.Controls.Add(this.readformatcardpage);

SQL query for extracting year from a date

How about this one?

SELECT TO_CHAR(ASOFDATE, 'YYYY') FROM PSASOFDATE

How to get the nvidia driver version from the command line?

Windows version:

cd \Program Files\NVIDIA Corporation\NVSMI

nvidia-smi

Android: Tabs at the BOTTOM

There are two ways to display tabs at the bottom of a tab activity.

  1. Using relative layout
  2. Using Layout_weight attribute

Please check the link for more details.

Converting Integer to Long

((Number) intOrLongOrSomewhat).longValue()

Fastest way to set all values of an array?

I have a minor improvement on Ross Drew's answer.

For a small array, a simple loop is faster than the System.arraycopy approach, because of the overhead associated with setting up System.arraycopy. Therefore, it's better to fill the first few bytes of the array using a simple loop, and only move to System.arraycopy when the filled array has a certain size.

The optimal size of the initial loop will be JVM specific and system specific of course.

private static final int SMALL = 16;

public static void arrayFill(byte[] array, byte value) {
  int len = array.length;
  int lenB = len < SMALL ? len : SMALL;

  for (int i = 0; i < lenB; i++) {
    array[i] = value;
  }

  for (int i = SMALL; i < len; i += i) {
    System.arraycopy(array, 0, array, i, len < i + i ? len - i : i);
  }
}

Cannot uninstall angular-cli

While uninstalling Angular CLI I got the same message (as it had some permission issues):

Unable to delete .Staging folder

I tried deleting the .staging folder manually, but still got the same error. I logged in from my administrator account and tried deleting the staging folder again manually, but to no avail.

I tried this (run as Administrator):

npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli.

Then I tried creating the project from my normal user account and it worked.

Octave/Matlab: Adding new elements to a vector

Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:

big = 1e5;
tic;
x = rand(big,1);
toc

x = zeros(big,1);
tic;
for ii = 1:big
    x(ii) = rand;
end
toc

x = []; 
tic; 
for ii = 1:big
    x(end+1) = rand; 
end; 
toc 

x = []; 
tic; 
for ii = 1:big
    x = [x rand]; 
end; 
toc

   Elapsed time is 0.004611 seconds.
   Elapsed time is 0.016448 seconds.
   Elapsed time is 0.034107 seconds.
   Elapsed time is 12.341434 seconds.

I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get

Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.

So I guess the speed advantage only applies to more recent versions of Matlab

Choose File Dialog

You just need to override onCreateDialog in an Activity.

//In an Activity
private String[] mFileList;
private File mPath = new File(Environment.getExternalStorageDirectory() + "//yourdir//");
private String mChosenFile;
private static final String FTYPE = ".txt";    
private static final int DIALOG_LOAD_FILE = 1000;

private void loadFileList() {
    try {
        mPath.mkdirs();
    }
    catch(SecurityException e) {
        Log.e(TAG, "unable to write on the sd card " + e.toString());
    }
    if(mPath.exists()) {
        FilenameFilter filter = new FilenameFilter() {

            @Override
            public boolean accept(File dir, String filename) {
                File sel = new File(dir, filename);
                return filename.contains(FTYPE) || sel.isDirectory();
            }

        };
        mFileList = mPath.list(filter);
    }
    else {
        mFileList= new String[0];
    }
}

protected Dialog onCreateDialog(int id) {
    Dialog dialog = null;
    AlertDialog.Builder builder = new Builder(this);

    switch(id) {
        case DIALOG_LOAD_FILE:
            builder.setTitle("Choose your file");
            if(mFileList == null) {
                Log.e(TAG, "Showing file picker before loading the file list");
                dialog = builder.create();
                return dialog;
            }
            builder.setItems(mFileList, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    mChosenFile = mFileList[which];
                    //you can do stuff with the file here too
                }
            });
            break;
    }
    dialog = builder.show();
    return dialog;
}

How to check for an empty object in an AngularJS view

You have to just check that the object is null or not. AngularJs provide inbuilt directive ng-if. An example is given below.

<tr ng-repeat="key in object" ng-if="object != 'null'" >
    <td>{{object.key}}</td>
    <td>{{object.key}}</td>
</tr>

How do I get just the date when using MSSQL GetDate()?

SELECT CONVERT(DATETIME, CONVERT(varchar(10), GETDATE(), 101))

Block Comments in a Shell Script

You could use Vi/Vim's Visual Block mode which is designed for stuff like this:

Ctrl-V  
Highlight first element in rows you want commented  
Shift-i  
#  
esc  

Uncomment would be:

Ctrl-V  
Highlight #'s  
d  
l  

This is vi's interactive way of doing this sort of thing rather than counting or reading line numbers.

Lastly, in Gvim you use ctrl-q to get into Visual Block mode rather than ctrl-v (because that's the shortcut for paste).

What is the difference between #include <filename> and #include "filename"?

GCC documentation says the following about the difference between the two:

Both user and system header files are included using the preprocessing directive ‘#include’. It has two variants:

#include <file>

This variant is used for system header files. It searches for a file named file in a standard list of system directories. You can prepend directories to this list with the -I option (see Invocation).

#include "file"

This variant is used for header files of your own program. It searches for a file named file first in the directory containing the current file, then in the quote directories and then the same directories used for <file>. You can prepend directories to the list of quote directories with the -iquote option. The argument of ‘#include’, whether delimited with quote marks or angle brackets, behaves like a string constant in that comments are not recognized, and macro names are not expanded. Thus, #include <x/*y> specifies inclusion of a system header file named x/*y.

However, if backslashes occur within file, they are considered ordinary text characters, not escape characters. None of the character escape sequences appropriate to string constants in C are processed. Thus,#include "x\n\\y"specifies a filename containing three backslashes. (Some systems interpret ‘\’ as a pathname separator. All of these also interpret ‘/’ the same way. It is most portable to use only ‘/’.)

It is an error if there is anything (other than comments) on the line after the file name.

Comparing two arrays & get the values which are not common

Collection

$a = 1..5
$b = 4..8

$Yellow = $a | Where {$b -NotContains $_}

$Yellow contains all the items in $a except the ones that are in $b:

PS C:\> $Yellow
1
2
3

$Blue = $b | Where {$a -NotContains $_}

$Blue contains all the items in $b except the ones that are in $a:

PS C:\> $Blue
6
7
8

$Green = $a | Where {$b -Contains $_}

Not in question, but anyways; Green contains the items that are in both $a and $b.

PS C:\> $Green
4
5

Note: Where is an alias of Where-Object. Alias can introduce possible problems and make scripts hard to maintain.


Addendum 12 October 2019

As commented by @xtreampb and @mklement0: although not shown from the example in the question, the task that the question implies (values "not in common") is the symmetric difference between the two input sets (the union of yellow and blue).

Union

The symmetric difference between the $a and $b can be literally defined as the union of $Yellow and $Blue:

$NotGreen = $Yellow + $Blue

Which is written out:

$NotGreen = ($a | Where {$b -NotContains $_}) + ($b | Where {$a -NotContains $_})

Performance

As you might notice, there are quite some (redundant) loops in this syntax: all items in list $a iterate (using Where) through items in list $b (using -NotContains) and visa versa. Unfortunately the redundancy is difficult to avoid as it is difficult to predict the result of each side. A Hash Table is usually a good solution to improve the performance of redundant loops. For this, I like to redefine the question: Get the values that appear once in the sum of the collections ($a + $b):

$Count = @{}
$a + $b | ForEach-Object {$Count[$_] += 1}
$Count.Keys | Where-Object {$Count[$_] -eq 1}

By using the ForEach statement instead of the ForEach-Object cmdlet and the Where method instead of the Where-Object you might increase the performance by a factor 2.5:

$Count = @{}
ForEach ($Item in $a + $b) {$Count[$Item] += 1}
$Count.Keys.Where({$Count[$_] -eq 1})

LINQ

But Language Integrated Query (LINQ) will easily beat any native PowerShell and native .Net methods (see also High Performance PowerShell with LINQ and mklement0's answer for Can the following Nested foreach loop be simplified in PowerShell?:

To use LINQ you need to explicitly define the array types:

[Int[]]$a = 1..5
[Int[]]$b = 4..8

And use the [Linq.Enumerable]:: operator:

$Yellow   = [Int[]][Linq.Enumerable]::Except($a, $b)
$Blue     = [Int[]][Linq.Enumerable]::Except($b, $a)
$Green    = [Int[]][Linq.Enumerable]::Intersect($a, $b)
$NotGreen = [Int[]]([Linq.Enumerable]::Except($a, $b) + [Linq.Enumerable]::Except($b, $a))

Benchmark

Benchmark results highly depend on the sizes of the collections and how many items there are actually shared, as a "average", I am presuming that half of each collection is shared with the other.

Using             Time
Compare-Object    111,9712
NotContains       197,3792
ForEach-Object    82,8324
ForEach Statement 36,5721
LINQ              22,7091

To get a good performance comparison, caches should be cleared by e.g. starting a fresh PowerShell session.

$a = 1..1000
$b = 500..1500

(Measure-Command {
    Compare-Object -ReferenceObject $a -DifferenceObject $b  -PassThru
}).TotalMilliseconds
(Measure-Command {
    ($a | Where {$b -NotContains $_}), ($b | Where {$a -NotContains $_})
}).TotalMilliseconds
(Measure-Command {
    $Count = @{}
    $a + $b | ForEach-Object {$Count[$_] += 1}
    $Count.Keys | Where-Object {$Count[$_] -eq 1}
}).TotalMilliseconds

(Measure-Command {
    $Count = @{}
    ForEach ($Item in $a + $b) {$Count[$Item] += 1}
    $Count.Keys.Where({$Count[$_] -eq 1})
}).TotalMilliseconds

[Int[]]$a = $a
[Int[]]$b = $b
(Measure-Command {
    [Int[]]([Linq.Enumerable]::Except($a, $b) + [Linq.Enumerable]::Except($b, $a))
}).TotalMilliseconds

C# Clear Session

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

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

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

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

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

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

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

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

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

...

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

So back to the differences:

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

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

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

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

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

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

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

Question

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

Answer

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

How to auto adjust the <div> height according to content in it?

simply set the height to auto, that should fix the problem, because div are block elements so they stretch out to full width and height of any element contained in it. if height set to auto not working then simple don't add the height, it should adjust and make sure that the div is not inheriting any height from it's parent element as well...

Create a hexadecimal colour based on a string with JavaScript

I convert this for Java.

Tanks for all.

public static int getColorFromText(String text)
    {
        if(text == null || text.length() < 1)
            return Color.BLACK;

        int hash = 0;

        for (int i = 0; i < text.length(); i++)
        {
            hash = text.charAt(i) + ((hash << 5) - hash);
        }

        int c = (hash & 0x00FFFFFF);
        c = c - 16777216;

        return c;
    }

Can I make dynamic styles in React Native?

Yes you can and actually, you should use StyleSheet.create to create your styles.

import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View
} from 'react-native';    

class Header extends Component {
    constructor(props){
        super(props);
    }    

    render() {
        const { title, style } = this.props;
        const { header, text } = defaultStyle;
        const combineStyles = StyleSheet.flatten([header, style]);    

        return (
            <View style={ combineStyles }>
                <Text style={ text }>
                    { title }
                </Text>
            </View>
        );
    }
}    

const defaultStyle = StyleSheet.create({
    header: {
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#fff',
        height: 60,
        paddingTop: 15,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 3 },
        shadowOpacity: 0.4,
        elevation: 2,
        position: 'relative'
    },
    text: {
        color: '#0d4220',
        fontSize: 16
    }
});    

export default Header;

And then:

<Header title="HOME" style={ {backgroundColor: '#10f1f0'} } />

How to export data to an excel file using PHPExcel

If you've copied this directly, then:

->setCellValue('B2', Ackermann') 

should be

->setCellValue('B2', 'Ackermann') 

In answer to your question:

Get the data that you want from limesurvey, and use setCellValue() to store those data values in the cells where you want to store it.

The Quadratic.php example file in /Tests might help as a starting point: it takes data from an input form and sets it to cells in an Excel workbook.

EDIT

An extremely simplistic example:

// Create your database query
$query = "SELECT * FROM myDataTable";  

// Execute the database query
$result = mysql_query($query) or die(mysql_error());

// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel(); 
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0); 
// Initialise the Excel row number
$rowCount = 1; 
// Iterate through each result from the SQL query in turn
// We fetch each database result row into $row in turn
while($row = mysql_fetch_array($result)){ 
    // Set cell An to the "name" column from the database (assuming you have a column called name)
    //    where n is the Excel row number (ie cell A1 in the first row)
    $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['name']); 
    // Set cell Bn to the "age" column from the database (assuming you have a column called age)
    //    where n is the Excel row number (ie cell A1 in the first row)
    $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['age']); 
    // Increment the Excel row counter
    $rowCount++; 
} 

// Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter->save('some_excel_file.xlsx'); 

EDIT #2

Using your existing code as the basis

// Instantiate a new PHPExcel object 
$objPHPExcel = new PHPExcel();  
// Set the active Excel worksheet to sheet 0 
$objPHPExcel->setActiveSheetIndex(0);  
// Initialise the Excel row number 
$rowCount = 1;  

//start of printing column names as names of MySQL fields  
$column = 'A';
for ($i = 1; $i < mysql_num_fields($result); $i++)  
{
    $objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, mysql_field_name($result,$i));
    $column++;
}
//end of adding column names  

//start while loop to get data  
$rowCount = 2;  
while($row = mysql_fetch_row($result))  
{  
    $column = 'A';
    for($j=1; $j<mysql_num_fields($result);$j++)  
    {  
        if(!isset($row[$j]))  
            $value = NULL;  
        elseif ($row[$j] != "")  
            $value = strip_tags($row[$j]);  
        else  
            $value = "";  

        $objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, $value);
        $column++;
    }  
    $rowCount++;
} 


// Redirect output to a client’s web browser (Excel5) 
header('Content-Type: application/vnd.ms-excel'); 
header('Content-Disposition: attachment;filename="Limesurvey_Results.xls"'); 
header('Cache-Control: max-age=0'); 
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); 
$objWriter->save('php://output');

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

If you want to use valueChangeListener, you need to submit the form every time a new option is chosen. Something like this:

<p:selectOneMenu value="#{mymb.employee}" onchange="submit()"
                 valueChangeListener="#{mymb.handleChange}" >
    <f:selectItems value="#{mymb.employeesList}" var="emp"
                   itemLabel="#{emp.employeeName}" itemValue="#{emp.employeeID}" />
</p:selectOneMenu>

public void handleChange(ValueChangeEvent event){  
    System.out.println("New value: " + event.getNewValue());
}

Or else, if you want to use <p:ajax>, it should look like this:

<p:selectOneMenu value="#{mymb.employee}" >
    <p:ajax listener="#{mymb.handleChange}" />
    <f:selectItems value="#{mymb.employeesList}" var="emp"
                   itemLabel="#{emp.employeeName}" itemValue="#{emp.employeeID}" />
</p:selectOneMenu>

private String employeeID;

public void handleChange(){  
    System.out.println("New value: " + employee);
}

One thing to note is that in your example code, I saw that the value attribute of your <p:selectOneMenu> is #{mymb.employeesList} which is the same as the value of <f:selectItems>. The value of your <p:selectOneMenu> should be similar to my examples above which point to a single employee, not a list of employees.

Android emulator shows nothing except black screen and adb devices shows "device offline"

I had the same problem in win10 64bit, too. After a lot of searching, I found this solution.(If you're using an intel system(CPU, GPU, Motherboard, etc.)) Hope it work for you, too.

step 1: Make sure virtualization is enabled on your device:

Reboot your computer and then press F2 for BIOS setup. You should find Virtualization tag and make sure it is marked as enabled. If it's not enabled, no virtual devices can run on your device.

step 2: Install/Update Intel Hardware Accelerated Execution Manager(Intel HAXM) on your device:

This software should be installed or updated for any AVDs to run. You can download the latest version by googling "HAXM". After download, install .exe file and reboot your computer.

jQuery function after .append

I'm surprised at all the answers here...

Try this:

window.setTimeout(function() { /* your stuff */ }, 0);

Note the 0 timeout. It's not an arbitrary number... as I understand (though my understanding might be a bit shaky), there's two javascript event queues - one for macro events and one for micro events. The "larger" scoped queue holds tasks that update the UI (and DOM), while the micro queue performs quick-task type operations.

Also realize that setting a timeout doesn't guarantee that the code performs exactly at that specified value. What this does is essentially puts the function into the higher queue (the one that handles the UI/DOM), and does not run it before the specified time.

This means that setting a timeout of 0 puts it into the UI/DOM-portion of javascript's event queue, to be run at the next possible chance.

This means that the DOM gets updated with all previous queue items (such as inserted via $.append(...);, and when your code runs, the DOM is fully available.

(p.s. - I learned this from Secrects of the JavaScript Ninja - an excellent book: https://www.manning.com/books/secrets-of-the-javascript-ninja )

CSS Font "Helvetica Neue"

You can use http://www.fontsquirrel.com/fontface/generator to encode any font for websites. It'll generate the code to include the font.

I don't really use it for fonts over 30px. They look much better as an image (because images are anti-aliased, and some browsers don't anti-alias fonts in the browser).

See: http://www.truetype-typography.com/ttalias.htm

Hope that helps...

What is System, out, println in System.out.println() in Java

The first answer you posted (System is a built-in class...) is pretty spot on.

You can add that the System class contains large portions which are native and that is set up by the JVM during startup, like connecting the System.out printstream to the native output stream associated with the "standard out" (console).

Insert array into MySQL database with PHP

The simplest method to escape and insert:

global $connection;
$columns = implode(", ",array_keys($array_data));
$func = function($value) {
    global $connection;
    return mysqli_real_escape_string($connection, $value);
};
$escaped_values = array_map($func, array_values($array_data));
$values  = implode(", ", $escaped_values);
$result = mysqli_query($connection, "INSERT INTO $table_name ($columns) VALUES ($values)");

Specifying row names when reading in a file

See ?read.table. Basically, when you use read.table, you specify a number indicating the column:

##Row names in the first column
read.table(filname.txt, row.names=1)

C# Sort and OrderBy comparison

I think it's important to note another difference between Sort and OrderBy:

Suppose there exists a Person.CalculateSalary() method, which takes a lot of time; possibly more than even the operation of sorting a large list.

Compare

// Option 1
persons.Sort((p1, p2) => Compare(p1.CalculateSalary(), p2.CalculateSalary()));
// Option 2
var query = persons.OrderBy(p => p.CalculateSalary()); 

Option 2 may have superior performance, because it only calls the CalculateSalary method n times, whereas the Sort option might call CalculateSalary up to 2n log(n) times, depending on the sort algorithm's success.

Embedding Windows Media Player for all browsers

The following works for me in Firefox and Internet Explorer:

<object id="mediaplayer" classid="clsid:22d6f312-b0f6-11d0-94ab-0080c74c7e95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#version=5,1,52,701" standby="loading microsoft windows media player components..." type="application/x-oleobject" width="320" height="310">
<param name="filename" value="./test.wmv">
     <param name="animationatstart" value="true">
     <param name="transparentatstart" value="true">
     <param name="autostart" value="true">
     <param name="showcontrols" value="true">
     <param name="ShowStatusBar" value="true">
     <param name="windowlessvideo" value="true">
     <embed src="./test.wmv" autostart="true" showcontrols="true" showstatusbar="1" bgcolor="white" width="320" height="310">
</object>

Windows batch script to move files

This is exactly how it worked for me. For some reason the above code failed.

This one runs a check every 3 minutes for any files in there and auto moves it to the destination folder. If you need to be prompted for conflicts then change the /y to /-y

:backup
move /y "D:\Dropbox\Dropbox\Camera Uploads\*.*" "D:\Archive\Camera Uploads\"
timeout 360
goto backup

Easiest way to detect Internet connection on iOS?

EDIT: This will not work for network URLs (see comments)

As of iOS 5, there is a new NSURL instance method:

- (BOOL)checkResourceIsReachableAndReturnError:(NSError **)error

Point it to the website you care about or point it to apple.com; I think it is the new one-line call to see if the internet is working on your device.

Angular JS update input field after change

I wrote a directive you can use to bind an ng-model to any expression you want. Whenever the expression changes the model is set to the new value.

 module.directive('boundModel', function() {
      return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ngModel) {
          var boundModel$watcher = scope.$watch(attrs.boundModel, function(newValue, oldValue) {
            if(newValue != oldValue) {
              ngModel.$setViewValue(newValue);
              ngModel.$render();
            }
          });

          // When $destroy is fired stop watching the change.
          // If you don't, and you come back on your state
          // you'll have two watcher watching the same properties
          scope.$on('$destroy', function() {
              boundModel$watcher();
          });
        }
    });

You can use it in your templates like this:

 <li>Total<input type="text" ng-model="total" bound-model="one * two"></li>      

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

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

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

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

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

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

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

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

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

How can I get a uitableViewCell by indexPath?

[(UITableViewCell *)[(UITableView *)self cellForRowAtIndexPath:nowIndex]

will give you uitableviewcell. But I am not sure what exactly you are asking for! Because you have this code and still you asking how to get uitableviewcell. Some more information will help to answer you :)

ADD: Here is an alternate syntax that achieves the same thing without the cast.

UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:nowIndex];

How can I store and retrieve images from a MySQL database using PHP?

First you create a MySQL table to store images, like for example:

create table testblob (
    image_id        tinyint(3)  not null default '0',
    image_type      varchar(25) not null default '',
    image           blob        not null,
    image_size      varchar(25) not null default '',
    image_ctgy      varchar(25) not null default '',
    image_name      varchar(50) not null default ''
);

Then you can write an image to the database like:

/***
 * All of the below MySQL_ commands can be easily
 * translated to MySQLi_ with the additions as commented
 ***/ 
$imgData = file_get_contents($filename);
$size = getimagesize($filename);
mysql_connect("localhost", "$username", "$password");
mysql_select_db ("$dbname");
// mysqli 
// $link = mysqli_connect("localhost", $username, $password,$dbname); 
$sql = sprintf("INSERT INTO testblob
    (image_type, image, image_size, image_name)
    VALUES
    ('%s', '%s', '%d', '%s')",
    /***
     * For all mysqli_ functions below, the syntax is:
     * mysqli_whartever($link, $functionContents); 
     ***/
    mysql_real_escape_string($size['mime']),
    mysql_real_escape_string($imgData),
    $size[3],
    mysql_real_escape_string($_FILES['userfile']['name'])
    );
mysql_query($sql);

You can display an image from the database in a web page with:

$link = mysql_connect("localhost", "username", "password");
mysql_select_db("testblob");
$sql = "SELECT image FROM testblob WHERE image_id=0";
$result = mysql_query("$sql");
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
mysql_close($link);

g++ undefined reference to typeinfo

Possible solutions for code that deal with RTTI and non-RTTI libraries:

a) Recompile everything with either -frtti or -fno-rtti
b) If a) is not possible for you, try the following:

Assume libfoo is built without RTTI. Your code uses libfoo and compiles with RTTI. If you use a class (Foo) in libfoo that has virtuals, you're likely to run into a link-time error that says: missing typeinfo for class Foo.

Define another class (e.g. FooAdapter) that has no virtual and will forward calls to Foo that you use.

Compile FooAdapter in a small static library that doesn't use RTTI and only depends on libfoo symbols. Provide a header for it and use that instead in your code (which uses RTTI). Since FooAdapter has no virtual function it won't have any typeinfo and you'll be able to link your binary. If you use a lot of different classes from libfoo, this solution may not be convenient, but it's a start.

How can I keep Bootstrap popovers alive while being hovered?

I know I'm kinda late to the party but I was looking for a solution for this..and I bumped into this post. Here is my take on this, maybe it will help some of you.

The html part:

<button type="button" class="btn btn-lg btn-danger" data-content="test" data-placement="right" data-toggle="popover" title="Popover title" >Hover to toggle popover</button><br>
// with custom html stored in a separate element, using "data-target"
<button type="button" class="btn btn-lg btn-danger" data-target="#custom-html" data-placement="right" data-toggle="popover" >Hover to toggle popover</button>

<div id="custom-html" style="display: none;">
    <strong>Helloooo!!</strong>
</div>

The js part:

$(function () {
        let popover = '[data-toggle="popover"]';

        let popoverId = function(element) {
            return $(element).popover().data('bs.popover').tip.id;
        }

        $(popover).popover({
            trigger: 'manual',
            html: true,
            animation: false
        })
        .on('show.bs.popover', function() {
            // hide all other popovers  
            $(popover).popover("hide");
        })
        .on("mouseenter", function() {
            // add custom html from element
            let target = $(this).data('target');
            $(this).popover().data('bs.popover').config.content = $(target).html();

            // show the popover
            $(this).popover("show");
            
            $('#' + popoverId(this)).on("mouseleave", () => {
               $(this).popover("hide");
            });

        }).on("mouseleave", function() {
            setTimeout(() => {
                if (!$("#" + popoverId(this) + ":hover").length) {
                    $(this).popover("hide");
                }
            }, 100);
        });
    })

Is Django for the frontend or backend?

It seems you're actually talking about an MVC (Model-View-Controller) pattern, where logic is separated into various "tiers". Django, as a framework, follows MVC (loosely). You have models that contain your business logic and relate directly to tables in your database, views which in effect act like the controller, handling requests and returning responses, and finally, templates which handle presentation.

Django isn't just one of these, it is a complete framework for application development and provides all the tools you need for that purpose.

Frontend vs Backend is all semantics. You could potentially build a Django app that is entirely "backend", using its built-in admin contrib package to manage the data for an entirely separate application. Or, you could use it solely for "frontend", just using its views and templates but using something else entirely to manage the data. Most usually, it's used for both. The built-in admin (the "backend"), provides an easy way to manage your data and you build apps within Django to present that data in various ways. However, if you were so inclined, you could also create your own "backend" in Django. You're not forced to use the default admin.

pycharm running way slow

1. Change the inspection level

Current PyCharm versions allows you to change the type of static code analysis it performs, and also features a Power/CPU Saving feature (Click on the icon at the bottom right, next to the lock):

enter image description here

2. Change indexed directories
Exclude directories from being indexed which are set in the project paths but not actually required to be searched and indexed. Press ALT+CTRL+S and search for project.

3. Do memory sweeps
There is another interesting feature:

Go into the settings (File/Settings) and search for memory. In IDE Settings>Appearance -> tick Show memory indicator. A memory bar will be shown at the bottom right corner (see the picture below). Click this bar to run a garbage collection / memory sweep.

enter image description here

Bootstrap Columns Not Working

Try this:

DEMO

<div class="container-fluid"> <!-- If Needed Left and Right Padding in 'md' and 'lg' screen means use container class -->
            <div class="row">
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <a href="#">About</a>
                </div>
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <img src="image.png" />
                </div>
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <a href="#myModal1" data-toggle="modal">SHARE</a>
                </div>
            </div>
        </div>

android:drawableLeft margin and/or padding

You can use android:drawableLeft="@drawable/your_icon" to set the drawable to be shown on the left side. In order to set a padding for the drawable you should use the android:paddingLeft or android:paddingRight to set the left/right padding respectively.

android:paddingRight="10dp"
android:paddingLeft="20dp"
android:drawableRight="@drawable/ic_app_manager"

Could not load file or assembly '***.dll' or one of its dependencies

I ran into this recently. It turned out that the old DLL was compiled with a previous version (Visual Studio 2008) and was referencing that version of the dynamic runtime libraries. I was trying to run it on a system that only had .NET 4.0 on it and I'd never installed any dynamic runtime libraries. The solution? I recompiled the DLL to link the static runtime libraries.

Check your application error log in Event Viewer (EVENTVWR.EXE). It will give you more information on the error and will probably point you at the real cause of the problem.

Centering the pagination in bootstrap

Using laravel with bootstrap 4, the solution that worked:

<div class="d-flex">
    <div class="mx-auto">
        {{$products->links("pagination::bootstrap-4")}}
    </div>
</div>

Using an image caption in Markdown Jekyll

For Kramdown, you can use {:refdef: style="text-align: center;"} to align center

{:refdef: style="text-align: center;"}
![example](https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg){: width="50%" .shadow}
{: refdef}
{:refdef: style="text-align: center;"}
*Fig.1: This is an example image. [Source](https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg)*
{: refdef}

TypeError: 'undefined' is not an object

I'm not sure how you could just check if something isn't undefined and at the same time get an error that it is undefined. What browser are you using?

You could check in the following way (extra = and making length a truthy evaluation)

if (typeof(sub.from) !== 'undefined' && sub.from.length) {

[update]

I see that you reset sub and thereby reset sub.from but fail to re check if sub.from exist:

for (var i = 0; i < sub.from.length; i++) {//<== assuming sub.from.exist
            mainid = sub.from[i]['id'];
            var sub = afcHelper_Submissions[mainid]; // <== re setting sub

My guess is that the error is not on the if statement but on the for(i... statement. In Firebug you can break automatically on an error and I guess it'll break on that line (not on the if statement).

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

Anderscc has got it correct. Thanks. It worked for me but not 100%.

I had to set

$mail->SMTPDebug = 0;

Setting it to 1, can cause errors especially if you are passing some data as json to next page. Example - Performing verification if mail is sent, using json to pass data through ajax.

I had to lower my gmail account security settings to get rid of errors: " SMTP connect() failed " and " SMTP ERROR: Password command failed "

Solution: This problem can be caused by either 'less secure' applications trying to use the email account (this is according to google help, not sure how they judge what is secure and what is not) OR if you are trying to login several time in a row OR if you change countries (for example use VPN, move code to different server or actually try to login from different part of the world).

Links that fix the problem (you must be logged into google account):

Note: You can go to the following stackoverflow answer link for more detailed reference.

https://stackoverflow.com/a/25175234

How To Accept a File POST

I used Mike Wasson's answer before I updated all the NuGets in my webapi mvc4 project. Once I did, I had to re-write the file upload action:

    public Task<HttpResponseMessage> Upload(int id)
    {
        HttpRequestMessage request = this.Request;
        if (!request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
        }

        string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
        var provider = new MultipartFormDataStreamProvider(root);

        var task = request.Content.ReadAsMultipartAsync(provider).
            ContinueWith<HttpResponseMessage>(o =>
            {
                FileInfo finfo = new FileInfo(provider.FileData.First().LocalFileName);

                string guid = Guid.NewGuid().ToString();

                File.Move(finfo.FullName, Path.Combine(root, guid + "_" + provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", "")));

                return new HttpResponseMessage()
                {
                    Content = new StringContent("File uploaded.")
                };
            }
        );
        return task;
    }

Apparently BodyPartFileNames is no longer available within the MultipartFormDataStreamProvider.

How to implement class constants?

Constants can be declare outside of classes and use within your class. Otherwise the get property is a nice workaround

const MY_CONSTANT: string = "wazzup";

export class MyClass {

    public myFunction() {

        alert(MY_CONSTANT);
    }
}

How to extract multiple JSON objects from one file?

Use a json array, in the format:

[
{"ID":"12345","Timestamp":"20140101", "Usefulness":"Yes",
  "Code":[{"event1":"A","result":"1"},…]},
{"ID":"1A35B","Timestamp":"20140102", "Usefulness":"No",
  "Code":[{"event1":"B","result":"1"},…]},
{"ID":"AA356","Timestamp":"20140103", "Usefulness":"No",
  "Code":[{"event1":"B","result":"0"},…]},
...
]

Then import it into your python code

import json

with open('file.json') as json_file:

    data = json.load(json_file)

Now the content of data is an array with dictionaries representing each of the elements.

You can access it easily, i.e:

data[0]["ID"]

How to add leading zeros?

Here is another alternative for adding leading to 0s to strings such as CUSIPs which can sometimes look like a number and which many applications such as Excel will corrupt and remove the leading 0s or convert them to scientific notation.

When I tried the answer provided by @metasequoia the vector returned had leading spaces and not 0s. This was the same problem mentioned by @user1816679 -- and removing the quotes around the 0 or changing from %d to %s did not make a difference either. FYI, I am using RStudio Server running on an Ubuntu Server. This little two-step solution worked for me:

gsub(pattern = " ", replacement = "0", x = sprintf(fmt = "%09s", ids[,CUSIP]))

using the %>% pipe function from the magrittr package it could look like this:

sprintf(fmt = "%09s", ids[,CUSIP]) %>% gsub(pattern = " ", replacement = "0", x = .)

I'd prefer a one-function solution, but it works.

How to extract HTTP response body from a Python requests call?


import requests

site_request = requests.get("https://abhiunix.in")

site_response = str(site_request.content)

print(site_response)

You can do it either way.

What is the default database path for MongoDB?

I have version 2.0.7 installed on Ubuntu and it defaulted to /var/lib/mongodb/ and that is also what was placed into my /etc/mongodb.conf file.

ReCaptcha API v2 Styling

You can recreate recaptcha , wrap it in a container and only let the checkbox visible. My main problem was that I couldn't take the full width so now it expands to the container width. The only problem is the expiration you can see a flick but as soon it happens I reset it.

See this demo http://codepen.io/alejandrolechuga/pen/YpmOJX

enter image description here

_x000D_
_x000D_
function recaptchaReady () {_x000D_
  grecaptcha.render('myrecaptcha', {_x000D_
  'sitekey': '6Lc7JBAUAAAAANrF3CJaIjt7T9IEFSmd85Qpc4gj',_x000D_
  'expired-callback': function () {_x000D_
    grecaptcha.reset();_x000D_
    console.log('recatpcha');_x000D_
  }_x000D_
});_x000D_
}
_x000D_
.recaptcha-wrapper {_x000D_
    height: 70px;_x000D_
  overflow: hidden;_x000D_
  background-color: #F9F9F9;_x000D_
  border-radius: 3px;_x000D_
  box-shadow: 0px 0px 4px 1px rgba(0,0,0,0.08);_x000D_
  -webkit-box-shadow: 0px 0px 4px 1px rgba(0,0,0,0.08);_x000D_
  -moz-box-shadow: 0px 0px 4px 1px rgba(0,0,0,0.08);_x000D_
  height: 70px;_x000D_
  position: relative;_x000D_
  margin-top: 17px;_x000D_
  border: 1px solid #d3d3d3;_x000D_
  color: #000;_x000D_
}_x000D_
_x000D_
.recaptcha-info {_x000D_
  background-size: 32px;_x000D_
  height: 32px;_x000D_
  margin: 0 13px 0 13px;_x000D_
  position: absolute;_x000D_
  right: 8px;_x000D_
  top: 9px;_x000D_
  width: 32px;_x000D_
  background-image: url(https://www.gstatic.com/recaptcha/api2/logo_48.png);_x000D_
  background-repeat: no-repeat;_x000D_
}_x000D_
.rc-anchor-logo-text {_x000D_
  color: #9b9b9b;_x000D_
  cursor: default;_x000D_
  font-family: Roboto,helvetica,arial,sans-serif;_x000D_
  font-size: 10px;_x000D_
  font-weight: 400;_x000D_
  line-height: 10px;_x000D_
  margin-top: 5px;_x000D_
  text-align: center;_x000D_
  position: absolute;_x000D_
  right: 10px;_x000D_
  top: 37px;_x000D_
}_x000D_
.rc-anchor-checkbox-label {_x000D_
  font-family: Roboto,helvetica,arial,sans-serif;_x000D_
  font-size: 14px;_x000D_
  font-weight: 400;_x000D_
  line-height: 17px;_x000D_
  left: 50px;_x000D_
  top: 26px;_x000D_
  position: absolute;_x000D_
  color: black;_x000D_
}_x000D_
.rc-anchor .rc-anchor-normal .rc-anchor-light {_x000D_
  border: none;_x000D_
}_x000D_
.rc-anchor-pt {_x000D_
  color: #9b9b9b;_x000D_
  font-family: Roboto,helvetica,arial,sans-serif;_x000D_
  font-size: 8px;_x000D_
  font-weight: 400;_x000D_
  right: 10px;_x000D_
  top: 53px;_x000D_
  position: absolute;_x000D_
  a:link {_x000D_
    color: #9b9b9b;_x000D_
    text-decoration: none;_x000D_
  }_x000D_
}_x000D_
_x000D_
g-recaptcha {_x000D_
  // transform:scale(0.95);_x000D_
  // -webkit-transform:scale(0.95);_x000D_
  // transform-origin:0 0;_x000D_
  // -webkit-transform-origin:0 0;_x000D_
_x000D_
}_x000D_
_x000D_
.g-recaptcha {_x000D_
  width: 41px;_x000D_
_x000D_
  /* border: 1px solid red; */_x000D_
  height: 38px;_x000D_
  overflow: hidden;_x000D_
  float: left;_x000D_
  margin-top: 16px;_x000D_
  margin-left: 6px;_x000D_
  _x000D_
    > div {_x000D_
    width: 46px;_x000D_
    height: 30px;_x000D_
    background-color:  #F9F9F9;_x000D_
    overflow: hidden;_x000D_
    border: 1px solid red;_x000D_
    transform: translate3d(-8px, -19px, 0px);_x000D_
  }_x000D_
  div {_x000D_
    border: 0;_x000D_
  }_x000D_
}
_x000D_
<script src='https://www.google.com/recaptcha/api.js?onload=recaptchaReady&&render=explicit'></script>_x000D_
_x000D_
<div class="recaptcha-wrapper">_x000D_
  <div id="myrecaptcha" class="g-recaptcha"></div>_x000D_
          <div class="rc-anchor-checkbox-label">I'm not a Robot.</div>_x000D_
        <div class="recaptcha-info"></div>_x000D_
        <div class="rc-anchor-logo-text">reCAPTCHA</div>_x000D_
        <div class="rc-anchor-pt">_x000D_
          <a href="https://www.google.com/intl/en/policies/privacy/" target="_blank">Privacy</a>_x000D_
          <span aria-hidden="true" role="presentation"> - </span>_x000D_
          <a href="https://www.google.com/intl/en/policies/terms/" target="_blank">Terms</a>_x000D_
        </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

You get this error because one of your variables is actually a factor variable . Execute

str(df) 

to check this. Then do this double variable change to keep the year numbers instead of transforming into "1,2,3,4" level numbers:

df$year <- as.numeric(as.character(df$year))

EDIT: it appears that your data.frame has a variable of class "array" which might cause the pb. Try then:

df <- data.frame(apply(df, 2, unclass))

and plot again?

Why doesn't Mockito mock static methods?

In some cases, static methods can be difficult to test, especially if they need to be mocked, which is why most mocking frameworks don't support them. I found this blog post to be very useful in determining how to mock static methods and classes.

How do you say not equal to in Ruby?

Yes. In Ruby the not equal to operator is:

!=

You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

Here's what I ended up doing after searching through all these solutions and others. It uses a stretchable png's extracted from the UIKit stock images. This way you can set the text to whatever you liek

// Generate the background images
UIImage *stretchableBackButton = [[UIImage imageNamed:@"UINavigationBarDefaultBack.png"] stretchableImageWithLeftCapWidth:14 topCapHeight:0];
UIImage *stretchableBackButtonPressed = [[UIImage imageNamed:@"UINavigationBarDefaultBackPressed.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
// Setup the UIButton
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton setBackgroundImage:stretchableBackButton forState:UIControlStateNormal];
[backButton setBackgroundImage:stretchableBackButtonPressed forState:UIControlStateSelected];
NSString *buttonTitle = NSLocalizedString(@"Back", @"Back");
[backButton setTitle:buttonTitle forState:UIControlStateNormal];
[backButton setTitle:buttonTitle forState:UIControlStateSelected];
backButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 2, 1); // Tweak the text position
NSInteger width = ([backButton.titleLabel.text sizeWithFont:backButton.titleLabel.font].width + backButton.titleEdgeInsets.right +backButton.titleEdgeInsets.left);
[backButton setFrame:CGRectMake(0, 0, width, 29)];
backButton.titleLabel.font = [UIFont boldSystemFontOfSize:13.0f];
[backButton addTarget:self action:@selector(yourSelector:) forControlEvents:UIControlEventTouchDown];
// Now add the button as a custom UIBarButtonItem
UIBarButtonItem *backButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:backButton] autorelease];
self.navigationItem.leftBarButtonItem = backButtonItem;

How to use a jQuery plugin inside Vue

I use it like this:

import jQuery from 'jQuery'

ready: function() {
    var self = this;
    jQuery(window).resize(function () {
      self.$refs.thisherechart.drawChart();
    })
  },

JavaScript Array Push key value

You may use:


To create array of objects:

var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));

Demo:

_x000D_
_x000D_
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.map(value => ({[value]: 0}));_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_


Or if you wants to create a single object from values of arrays:

var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});

Demo:

_x000D_
_x000D_
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Access restriction: Is not accessible due to restriction on required library ..\jre\lib\rt.jar

Go to Buildpath

Remove Existing JRE and add new JRE library which contain Jdk1.6 and finish Now clean all project and build again

I think this way you can resolved your error

Zoom in on a point (using scale and translate)

I want to put here some information for those, who do separately drawing of picture and moving -zooming it.

This may be useful when you want to store zooms and position of viewport.

Here is drawer:

function redraw_ctx(){
   self.ctx.clearRect(0,0,canvas_width, canvas_height)
   self.ctx.save()
   self.ctx.scale(self.data.zoom, self.data.zoom) // 
   self.ctx.translate(self.data.position.left, self.data.position.top) // position second
   // Here We draw useful scene My task - image:
   self.ctx.drawImage(self.img ,0,0) // position 0,0 - we already prepared
   self.ctx.restore(); // Restore!!!
}

Notice scale MUST be first.

And here is zoomer:

function zoom(zf, px, py){
    // zf - is a zoom factor, which in my case was one of (0.1, -0.1)
    // px, py coordinates - is point within canvas 
    // eg. px = evt.clientX - canvas.offset().left
    // py = evt.clientY - canvas.offset().top
    var z = self.data.zoom;
    var x = self.data.position.left;
    var y = self.data.position.top;

    var nz = z + zf; // getting new zoom
    var K = (z*z + z*zf) // putting some magic

    var nx = x - ( (px*zf) / K ); 
    var ny = y - ( (py*zf) / K);

    self.data.position.left = nx; // renew positions
    self.data.position.top = ny;   
    self.data.zoom = nz; // ... and zoom
    self.redraw_ctx(); // redraw context
    }

and, of course, we would need a dragger:

this.my_cont.mousemove(function(evt){
    if (is_drag){
        var cur_pos = {x: evt.clientX - off.left,
                       y: evt.clientY - off.top}
        var diff = {x: cur_pos.x - old_pos.x,
                    y: cur_pos.y - old_pos.y}

        self.data.position.left += (diff.x / self.data.zoom);  // we want to move the point of cursor strictly
        self.data.position.top += (diff.y / self.data.zoom);

        old_pos = cur_pos;
        self.redraw_ctx();

    }


})

How do I update zsh to the latest version?

I just switched the main shell to zsh. It suppresses the warnings and it isn't too complicated.

jQuery: get parent, parent id?

$(this).parent().parent().attr('id');

Is how you would get the id of the parent's parent.

EDIT:

$(this).closest('ul').attr('id');

Is a more foolproof solution for your case.

How to auto generate migrations with Sequelize CLI from Sequelize models?

You can now use the npm package sequelize-auto-migrations to automatically generate a migrations file. https://www.npmjs.com/package/sequelize-auto-migrations

Using sequelize-cli, initialize your project with

sequelize init

Create your models and put them in your models folder.

Install sequelize-auto-migrations:

npm install sequelize-auto-migrations

Create an initial migration file with

node ./node_modules/sequelize-auto-migrations/bin/makemigration --name <initial_migration_name>

Run your migration:

node ./node_modules/sequelize-auto-migrations/bin/runmigration

You can also automatically generate your models from an existing database, but that is beyond the scope of the question.

making matplotlib scatter plots from dataframes in Python's pandas

I will recommend to use an alternative method using seaborn which more powerful tool for data plotting. You can use seaborn scatterplot and define colum 3 as hue and size.

Working code:

import pandas as pd
import seaborn as sns
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20),'col_name_3': np.arange(20)*100}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df, hue="col_name_3",size="col_name_3")

enter image description here

Good NumericUpDown equivalent in WPF?

add a textbox and scrollbar

in VB

Private Sub Textbox1_ValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedPropertyChangedEventArgs(Of System.Double)) Handles Textbox1.ValueChanged
     If e.OldValue > e.NewValue Then
         Textbox1.Text = (Textbox1.Text + 1)
     Else
         Textbox1.Text = (Textbox1.Text - 1)
     End If
End Sub

How do you fade in/out a background color using jquery?

Usually you can use the .animate() method to manipulate arbitrary CSS properties, but for background colors you need to use the color plugin. Once you include this plugin, you can use something like others have indicated $('div').animate({backgroundColor: '#f00'}) to change the color.

As others have written, some of this can be done using the jQuery UI library as well.

Time comparison

The following assumes that your hours and minutes are stored as ints in variables named hh and mm respectively.

if ((hh > START_HOUR || (hh == START_HOUR && mm >= START_MINUTE)) &&
        (hh < END_HOUR || (hh == END_HOUR && mm <= END_MINUTE))) {
    ...
}

Passing references to pointers in C++

Change it to:

  std::string s;
  std::string* pS = &s;
  myfunc(pS);

EDIT:

This is called ref-to-pointer and you cannot pass temporary address as a reference to function. ( unless it is const reference).

Though, I have shown std::string* pS = &s; (pointer to a local variable), its typical usage would be : when you want the callee to change the pointer itself, not the object to which it points. For example, a function that allocates memory and assigns the address of the memory block it allocated to its argument must take a reference to a pointer, or a pointer to pointer:

void myfunc(string*& val)
{
//val is valid even after function call
   val = new std::string("Test");

}

T-SQL Cast versus Convert

Convert has a style parameter for date to string conversions.

http://msdn.microsoft.com/en-us/library/ms187928.aspx

How to disable keypad popup when on edittext?

Thanks @A.B for good solution

    android:focusableInTouchMode="false"

this case if you will disable keyboard in edit text , just add android:focusableInTouchMode="false" in edittext tagline.

work for me in Android Studio 3.0.1 minsdk 16 , maxsdk26

How to unzip a file using the command line?

Grab an executable from info-zip.

Info-ZIP supports hardware from microcomputers all the way up to Cray supercomputers, running on almost all versions of Unix, VMS, OS/2, Windows 9x/NT/etc. (a.k.a. Win32), Windows 3.x, Windows CE, MS-DOS, AmigaDOS, Atari TOS, Acorn RISC OS, BeOS, Mac OS, SMS/QDOS, MVS and OS/390 OE, VM/CMS, FlexOS, Tandem NSK and Human68K (Japanese). There is also some (old) support for LynxOS, TOPS-20, AOS/VS and Novell NLMs. Shared libraries (DLLs) are available for Unix, OS/2, Win32 and Win16, and graphical interfaces are available for Win32, Win16, WinCE and Mac OS.

How to run function in AngularJS controller on document ready?

Here's my attempt inside of an outer controller using coffeescript. It works rather well. Please note that settings.screen.xs|sm|md|lg are static values defined in a non-uglified file I include with the app. The values are per the Bootstrap 3 official breakpoints for the eponymous media query sizes:

xs = settings.screen.xs // 480
sm = settings.screen.sm // 768
md = settings.screen.md // 992
lg = settings.screen.lg // 1200

doMediaQuery = () ->

    w = angular.element($window).width()

    $scope.xs = w < sm
    $scope.sm = w >= sm and w < md
    $scope.md = w >= md and w < lg
    $scope.lg = w >= lg
    $scope.media =  if $scope.xs 
                        "xs" 
                    else if $scope.sm
                        "sm"
                    else if $scope.md 
                        "md"
                    else 
                        "lg"

$document.ready () -> doMediaQuery()
angular.element($window).bind 'resize', () -> doMediaQuery()

How to Alter Constraint

You can not alter constraints ever but you can drop them and then recreate.

Have look on this

ALTER TABLE your_table DROP CONSTRAINT ACTIVEPROG_FKEY1;

and then recreate it with ON DELETE CASCADE like this

ALTER TABLE your_table
add CONSTRAINT ACTIVEPROG_FKEY1 FOREIGN KEY(ActiveProgCode) REFERENCES PROGRAM(ActiveProgCode)
    ON DELETE CASCADE;

hope this help

How can I convert this one line of ActionScript to C#?

There is collection of Func<...> classes - Func that is probably what you are looking for:

 void MyMethod(Func<int> param1 = null) 

This defines method that have parameter param1 with default value null (similar to AS), and a function that returns int. Unlike AS in C# you need to specify type of the function's arguments.

So if you AS usage was

MyMethod(function(intArg, stringArg) { return true; }) 

Than in C# it would require param1 to be of type Func<int, siring, bool> and usage like

MyMethod( (intArg, stringArg) => { return true;} ); 

How do I convert a decimal to an int in C#?

You can't.

Well, of course you could, however an int (System.Int32) is not big enough to hold every possible decimal value.

That means if you cast a decimal that's larger than int.MaxValue you will overflow, and if the decimal is smaller than int.MinValue, it will underflow.

What happens when you under/overflow? One of two things. If your build is unchecked (i.e., the CLR doesn't care if you do), your application will continue after the value over/underflows, but the value in the int will not be what you expected. This can lead to intermittent bugs and may be hard to fix. You'll end up your application in an unknown state which may result in your application corrupting whatever important data its working on. Not good.

If your assembly is checked (properties->build->advanced->check for arithmetic overflow/underflow or the /checked compiler option), your code will throw an exception when an under/overflow occurs. This is probably better than not; however the default for assemblies is not to check for over/underflow.

The real question is "what are you trying to do?" Without knowing your requirements, nobody can tell you what you should do in this case, other than the obvious: DON'T DO IT.

If you specifically do NOT care, the answers here are valid. However, you should communicate your understanding that an overflow may occur and that it doesn't matter by wrapping your cast code in an unchecked block

unchecked
{
  // do your conversions that may underflow/overflow here
}

That way people coming behind you understand you don't care, and if in the future someone changes your builds to /checked, your code won't break unexpectedly.

If all you want to do is drop the fractional portion of the number, leaving the integral part, you can use Math.Truncate.

decimal actual = 10.5M;
decimal expected = 10M;
Assert.AreEqual(expected, Math.Truncate(actual));

How to concatenate two strings in C++?

Since it's C++ why not to use std::string instead of char*? Concatenation will be trivial:

std::string str = "abc";
str += "another";

How to preserve insertion order in HashMap?

LinkedHashMap is precisely what you're looking for.

It is exactly like HashMap, except that when you iterate over it, it presents the items in the insertion order.

How to use foreach with a hash reference?

foreach my $key (keys %$ad_grp_ref) {
    ...
}

Perl::Critic and daxim recommend the style

foreach my $key (keys %{ $ad_grp_ref }) {
    ...
}

out of concerns for readability and maintenance (so that you don't need to think hard about what to change when you need to use %{ $ad_grp_obj[3]->get_ref() } instead of %{ $ad_grp_ref })

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

Configure Two DataSources in Spring Boot 2.0.* or above

If you need to configure multiple data sources, you have to mark one of the DataSource instances as @Primary, because various auto-configurations down the road expect to be able to get one by type.

If you create your own DataSource, the auto-configuration backs off. In the following example, we provide the exact same feature set as the auto-configuration provides on the primary data source:

@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSourceProperties firstDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSource firstDataSource() {
    return firstDataSourceProperties().initializeDataSourceBuilder().build();
}

@Bean
@ConfigurationProperties("app.datasource.second")
public BasicDataSource secondDataSource() {
    return DataSourceBuilder.create().type(BasicDataSource.class).build();
}

firstDataSourceProperties has to be flagged as @Primary so that the database initializer feature uses your copy (if you use the initializer).

And your application.propoerties will look something like this:

app.datasource.first.url=jdbc:oracle:thin:@localhost/first
app.datasource.first.username=dbuser
app.datasource.first.password=dbpass
app.datasource.first.driver-class-name=oracle.jdbc.OracleDriver

app.datasource.second.url=jdbc:mariadb://localhost:3306/springboot_mariadb
app.datasource.second.username=dbuser
app.datasource.second.password=dbpass
app.datasource.second.driver-class-name=org.mariadb.jdbc.Driver

The above method is the correct to way to init multiple database in spring boot 2.0 migration and above. More read can be found here.

How to load a controller from another controller in codeigniter?

you cannot call a controller method from another controller directly

my solution is to use inheritances and extend your controller from the library controller

class Controller1 extends CI_Controller {

    public function index() {
        // some codes here
    }

    public function methodA(){
        // code here
    }
}

in your controller we call it Mycontoller it will extends Controller1

include_once (dirname(__FILE__) . "/controller1.php");

class Mycontroller extends Controller1 {

    public function __construct() {
        parent::__construct();
    }

    public function methodB(){
        // codes....
    }
}

and you can call methodA from mycontroller

http://example.com/mycontroller/methodA

http://example.com/mycontroller/methodB

this solution worked for me

MSOnline can't be imported on PowerShell (Connect-MsolService error)

After hours of searching and trying I found out that on a x64 server the MSOnline modules must be installed for x64, and some programs that need to run them are using the x86 PS version, so they will never find it.

[SOLUTION] What I did to solve the issue was:

Copy the folders called MSOnline and MSOnline Extended from the source

C:\Windows\System32\WindowsPowerShell\v1.0\Modules\

to the folder

C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\

And then in PS run the Import-Module MSOnline, and it will automatically get the module :D

How to make <input type="file"/> accept only these types?

for image write this

<input type=file accept="image/*">

For other, You can use the accept attribute on your form to suggest to the browser to restrict certain types. However, you'll want to re-validate in your server-side code to make sure. Never trust what the client sends you

Why can't I check if a 'DateTime' is 'Nothing'?

Some examples on working with nullable DateTime values.

(See Nullable Value Types (Visual Basic) for more.)

'
' An ordinary DateTime declaration. It is *not* nullable. Setting it to
' 'Nothing' actually results in a non-null value.
'
Dim d1 As DateTime = Nothing
Console.WriteLine(String.Format("d1 = [{0}]\n", d1))
' Output:  d1 = [1/1/0001 12:00:00 AM]

' Console.WriteLine(String.Format("d1 is Nothing? [{0}]\n", (d1 Is Nothing)))
'
'   Compilation error on above expression '(d1 Is Nothing)':
'
'      'Is' operator does not accept operands of type 'Date'.
'       Operands must be reference or nullable types.

'
' Three different but equivalent ways to declare a DateTime
' nullable:
'
Dim d2? As DateTime = Nothing
Console.WriteLine(String.Format("d2 = [{0}][{1}]\n", d2, (d2 Is Nothing)))
' Output:  d2 = [][True]

Dim d3 As DateTime? = Nothing
Console.WriteLine(String.Format("d3 = [{0}][{1}]\n", d3, (d3 Is Nothing)))
' Output:  d3 = [][True]

Dim d4 As Nullable(Of DateTime) = Nothing
Console.WriteLine(String.Format("d4 = [{0}][{1}]\n", d4, (d4 Is Nothing)))
' Output:  d4 = [][True]

Also, on how to check whether a variable is null (from Nothing (Visual Basic)):

When checking whether a reference (or nullable value type) variable is null, do not use = Nothing or <> Nothing. Always use Is Nothing or IsNot Nothing.

How do I restart my C# WinForm Application?

The problem of using Application.Restart() is, that it starts a new process but the "old" one is still remaining. Therefor I decided to Kill the old process by using the following code snippet:

            if(Condition){
            Application.Restart();
            Process.GetCurrentProcess().Kill();
            }

And it works proper good. In my case MATLAB and a C# Application are sharing the same SQLite database. If MATLAB is using the database, the Form-App should restart (+Countdown) again, until MATLAB reset its busy bit in the database. (Just for side information)

UTF-8: General? Bin? Unicode?

Really, I tested saving values like 'é' and 'e' in column with unique index and they cause duplicate error on both 'utf8_unicode_ci' and 'utf8_general_ci'. You can save them only in 'utf8_bin' collated column.

And mysql docs (in http://dev.mysql.com/doc/refman/5.7/en/charset-applications.html) suggest into its examples set 'utf8_general_ci' collation.

[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci

What do the different readystates in XMLHttpRequest mean, and how can I use them?

onreadystatechange Stores a function (or the name of a function) to be called automatically each time the readyState property changes readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4:

0: request not initialized

1: server connection established

2: request received

3: processing request

4: request finished and response is ready

status 200: "OK"

404: Page not found

How do I remove version tracking from a project cloned from git?

All the data Git uses for information is stored in .git/, so removing it should work just fine. Of course, make sure that your working copy is in the exact state that you want it, because everything else will be lost. .git folder is hidden so make sure you turn on the Show hidden files, folders and disks option.

From there, you can run git init to create a fresh repository.

How to use ? : if statements with Razor and inline code blocks

The key is to encapsulate the expression in parentheses after the @ delimiter. You can make any compound expression work this way.

log4j vs logback

Not exactly answering your question, but if you could move away from your self-made wrapper then there is Simple Logging Facade for Java (SLF4J) which Hibernate has now switched to (instead of commons logging).

SLF4J suffers from none of the class loader problems or memory leaks observed with Jakarta Commons Logging (JCL).

SLF4J supports JDK logging, log4j and logback. So then it should be fairly easy to switch from log4j to logback when the time is right.

Edit: Aplogies that I hadn't made myself clear. I was suggesting using SLF4J to isolate yourself from having to make a hard choice between log4j or logback.

Can I install/update WordPress plugins without providing FTP access?

Yes you can do it.

You need to add

define('METHOD','direct');

in your wpconfig. But this method won't be preferable because it has security voilances.

Thanks,

Static extension methods

No, but you could have something like:

bool b;
b = b.YourExtensionMethod();

pandas loc vs. iloc vs. at vs. iat?

df = pd.DataFrame({'A':['a', 'b', 'c'], 'B':[54, 67, 89]}, index=[100, 200, 300])

df

                        A   B
                100     a   54
                200     b   67
                300     c   89
In [19]:    
df.loc[100]

Out[19]:
A     a
B    54
Name: 100, dtype: object

In [20]:    
df.iloc[0]

Out[20]:
A     a
B    54
Name: 100, dtype: object

In [24]:    
df2 = df.set_index([df.index,'A'])
df2

Out[24]:
        B
    A   
100 a   54
200 b   67
300 c   89

In [25]:    
df2.ix[100, 'a']

Out[25]:    
B    54
Name: (100, a), dtype: int64

How to write into a file in PHP?

fwrite() is a smidgen faster and file_put_contents() is just a wrapper around those three methods anyway, so you would lose the overhead. Article

file_put_contents(file,data,mode,context):

The file_put_contents writes a string to a file.

This function follows these rules when accessing a file.If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of filename Create the file if it does not exist then Open the file and Lock the file if LOCK_EX is set and If FILE_APPEND is set, move to the end of the file. Otherwise, clear the file content Write the data into the file and Close the file and release any locks. This function returns the number of the character written into the file on success, or FALSE on failure.

fwrite(file,string,length):

The fwrite writes to an open file.The function will stop at the end of the file or when it reaches the specified length, whichever comes first.This function returns the number of bytes written or FALSE on failure.

PyCharm import external library

In my case, the correct menu path was:

File > Default settings > Project Interpreter

Java, How to implement a Shift Cipher (Caesar Cipher)

The warning is due to you attempting to add an integer (int shift = 3) to a character value. You can change the data type to char if you want to avoid that.

A char is 16 bits, an int is 32.

char shift = 3;
// ...
eMessage[i] = (message[i] + shift) % (char)letters.length;

As an aside, you can simplify the following:

char[] message = {'o', 'n', 'c', 'e', 'u', 'p', 'o', 'n', 'a', 't', 'i', 'm', 'e'}; 

To:

char[] message = "onceuponatime".toCharArray();

Python loop that also accesses previous and next values

Using a list comprehension, return a 3-tuple with current, previous and next elements:

three_tuple = [(current, 
                my_list[idx - 1] if idx >= 1 else None, 
                my_list[idx + 1] if idx < len(my_list) - 1 else None) for idx, current in enumerate(my_list)]

How do I calculate a trendline for a graph?

OK, here's my best pseudo math:

The equation for your line is:

Y = a + bX

Where:

b = (sum(x*y) - sum(x)sum(y)/n) / (sum(x^2) - sum(x)^2/n)

a = sum(y)/n - b(sum(x)/n)

Where sum(xy) is the sum of all x*y etc. Not particularly clear I concede, but it's the best I can do without a sigma symbol :)

... and now with added Sigma

b = (Σ(xy) - (ΣxΣy)/n) / (Σ(x^2) - (Σx)^2/n)

a = (Σy)/n - b((Σx)/n)

Where Σ(xy) is the sum of all x*y etc. and n is the number of points

IE6/IE7 css border on select element

Check out this code... hope ur happy :)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style type="text/css">
<style type="text/css">
*{margin:0;padding:0;}
select {font: normal 13px Arial, SansSerif, Verdana; color: black;}
.wrapper{width:198px; position: relative;  height: 20px; overflow: hidden; border-top:1px solid #dddddd; border-left:1px solid #dddddd;}
.Select{color: black; background: #fff;position: absolute; width: 200px; top: -2px; left: -2px;}
optgroup{background-color:#0099CC;color:#ffffff;}
</style>
</head>

<body>
<div class="wrapper">
<select class="Select">
<optgroup label="WebDevelopment"></optgroup>
<option>ASP</option>
<option>PHP</option>
<option>ColdFusion</option>
<optgroup label="Web Design"></optgroup>
<option>Adobe Photoshop</option>
<option>DreamWeaver</option>
<option>CSS</option>
<option>Adobe Flash</option>
</select>
</div>
</body>
</html>

Sajay

Can I find events bound on an element with jQuery?

When I pass a little complex DOM query to $._data like this: $._data($('#outerWrap .innerWrap ul li:last a'), 'events') it throws undefined in the browser console.

So I had to use $._data on the parent div: $._data($('#outerWrap')[0], 'events') to see the events for the a tags. Here is a JSFiddle for the same: http://jsfiddle.net/giri_jeedigunta/MLcpT/4/

Load a WPF BitmapImage from a System.Drawing.Bitmap

You can just share the pixeldata between a both namespaces ( Media and Drawing) by writing a custom bitmapsource. The conversion will happen immediately and no additional memory will be allocated. If you do not want to explicitly create a copy of your Bitmap this is the method you want.

class SharedBitmapSource : BitmapSource, IDisposable
{
    #region Public Properties

    /// <summary>
    /// I made it public so u can reuse it and get the best our of both namespaces
    /// </summary>
    public Bitmap Bitmap { get; private set; }

    public override double DpiX { get { return Bitmap.HorizontalResolution; } }

    public override double DpiY { get { return Bitmap.VerticalResolution; } }

    public override int PixelHeight { get { return Bitmap.Height; } }

    public override int PixelWidth { get { return Bitmap.Width; } }

    public override System.Windows.Media.PixelFormat Format { get { return ConvertPixelFormat(Bitmap.PixelFormat); } }

    public override BitmapPalette Palette { get { return null; } }

    #endregion

    #region Constructor/Destructor

    public SharedBitmapSource(int width, int height,System.Drawing.Imaging.PixelFormat sourceFormat)
        :this(new Bitmap(width,height, sourceFormat) ) { }

    public SharedBitmapSource(Bitmap bitmap)
    {
        Bitmap = bitmap;
    }

    // Use C# destructor syntax for finalization code.
    ~SharedBitmapSource()
    {
        // Simply call Dispose(false).
        Dispose(false);
    }

    #endregion

    #region Overrides

    public override void CopyPixels(Int32Rect sourceRect, Array pixels, int stride, int offset)
    {
        BitmapData sourceData = Bitmap.LockBits(
        new Rectangle(sourceRect.X, sourceRect.Y, sourceRect.Width, sourceRect.Height),
        ImageLockMode.ReadOnly,
        Bitmap.PixelFormat);

        var length = sourceData.Stride * sourceData.Height;

        if (pixels is byte[])
        {
            var bytes = pixels as byte[];
            Marshal.Copy(sourceData.Scan0, bytes, 0, length);
        }

        Bitmap.UnlockBits(sourceData);
    }

    protected override Freezable CreateInstanceCore()
    {
        return (Freezable)Activator.CreateInstance(GetType());
    }

    #endregion

    #region Public Methods

    public BitmapSource Resize(int newWidth, int newHeight)
    {
        Image newImage = new Bitmap(newWidth, newHeight);
        using (Graphics graphicsHandle = Graphics.FromImage(newImage))
        {
            graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphicsHandle.DrawImage(Bitmap, 0, 0, newWidth, newHeight);
        }
        return new SharedBitmapSource(newImage as Bitmap);
    }

    public new BitmapSource Clone()
    {
        return new SharedBitmapSource(new Bitmap(Bitmap));
    }

    //Implement IDisposable.
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    #endregion

    #region Protected/Private Methods

    private static System.Windows.Media.PixelFormat ConvertPixelFormat(System.Drawing.Imaging.PixelFormat sourceFormat)
    {
        switch (sourceFormat)
        {
            case System.Drawing.Imaging.PixelFormat.Format24bppRgb:
                return PixelFormats.Bgr24;

            case System.Drawing.Imaging.PixelFormat.Format32bppArgb:
                return PixelFormats.Pbgra32;

            case System.Drawing.Imaging.PixelFormat.Format32bppRgb:
                return PixelFormats.Bgr32;

        }
        return new System.Windows.Media.PixelFormat();
    }

    private bool _disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                // Free other state (managed objects).
            }
            // Free your own state (unmanaged objects).
            // Set large fields to null.
            _disposed = true;
        }
    }

    #endregion
}

How to use JavaScript to change the form action

Try this:

var frm = document.getElementById('search-theme-form') || null;
if(frm) {
   frm.action = 'whatever_you_need.ext' 
}

What are the calling conventions for UNIX & Linux system calls (and user-space functions) on i386 and x86-64

Linux kernel 5.0 source comments

I knew that x86 specifics are under arch/x86, and that syscall stuff goes under arch/x86/entry. So a quick git grep rdi in that directory leads me to arch/x86/entry/entry_64.S:

/*
 * 64-bit SYSCALL instruction entry. Up to 6 arguments in registers.
 *
 * This is the only entry point used for 64-bit system calls.  The
 * hardware interface is reasonably well designed and the register to
 * argument mapping Linux uses fits well with the registers that are
 * available when SYSCALL is used.
 *
 * SYSCALL instructions can be found inlined in libc implementations as
 * well as some other programs and libraries.  There are also a handful
 * of SYSCALL instructions in the vDSO used, for example, as a
 * clock_gettimeofday fallback.
 *
 * 64-bit SYSCALL saves rip to rcx, clears rflags.RF, then saves rflags to r11,
 * then loads new ss, cs, and rip from previously programmed MSRs.
 * rflags gets masked by a value from another MSR (so CLD and CLAC
 * are not needed). SYSCALL does not save anything on the stack
 * and does not change rsp.
 *
 * Registers on entry:
 * rax  system call number
 * rcx  return address
 * r11  saved rflags (note: r11 is callee-clobbered register in C ABI)
 * rdi  arg0
 * rsi  arg1
 * rdx  arg2
 * r10  arg3 (needs to be moved to rcx to conform to C ABI)
 * r8   arg4
 * r9   arg5
 * (note: r12-r15, rbp, rbx are callee-preserved in C ABI)
 *
 * Only called from user space.
 *
 * When user can change pt_regs->foo always force IRET. That is because
 * it deals with uncanonical addresses better. SYSRET has trouble
 * with them due to bugs in both AMD and Intel CPUs.
 */

and for 32-bit at arch/x86/entry/entry_32.S:

/*
 * 32-bit SYSENTER entry.
 *
 * 32-bit system calls through the vDSO's __kernel_vsyscall enter here
 * if X86_FEATURE_SEP is available.  This is the preferred system call
 * entry on 32-bit systems.
 *
 * The SYSENTER instruction, in principle, should *only* occur in the
 * vDSO.  In practice, a small number of Android devices were shipped
 * with a copy of Bionic that inlined a SYSENTER instruction.  This
 * never happened in any of Google's Bionic versions -- it only happened
 * in a narrow range of Intel-provided versions.
 *
 * SYSENTER loads SS, ESP, CS, and EIP from previously programmed MSRs.
 * IF and VM in RFLAGS are cleared (IOW: interrupts are off).
 * SYSENTER does not save anything on the stack,
 * and does not save old EIP (!!!), ESP, or EFLAGS.
 *
 * To avoid losing track of EFLAGS.VM (and thus potentially corrupting
 * user and/or vm86 state), we explicitly disable the SYSENTER
 * instruction in vm86 mode by reprogramming the MSRs.
 *
 * Arguments:
 * eax  system call number
 * ebx  arg1
 * ecx  arg2
 * edx  arg3
 * esi  arg4
 * edi  arg5
 * ebp  user stack
 * 0(%ebp) arg6
 */

glibc 2.29 Linux x86_64 system call implementation

Now let's cheat by looking at a major libc implementations and see what they are doing.

What could be better than looking into glibc that I'm using right now as I write this answer? :-)

glibc 2.29 defines x86_64 syscalls at sysdeps/unix/sysv/linux/x86_64/sysdep.h and that contains some interesting code, e.g.:

/* The Linux/x86-64 kernel expects the system call parameters in
   registers according to the following table:

    syscall number  rax
    arg 1       rdi
    arg 2       rsi
    arg 3       rdx
    arg 4       r10
    arg 5       r8
    arg 6       r9

    The Linux kernel uses and destroys internally these registers:
    return address from
    syscall     rcx
    eflags from syscall r11

    Normal function call, including calls to the system call stub
    functions in the libc, get the first six parameters passed in
    registers and the seventh parameter and later on the stack.  The
    register use is as follows:

     system call number in the DO_CALL macro
     arg 1      rdi
     arg 2      rsi
     arg 3      rdx
     arg 4      rcx
     arg 5      r8
     arg 6      r9

    We have to take care that the stack is aligned to 16 bytes.  When
    called the stack is not aligned since the return address has just
    been pushed.


    Syscalls of more than 6 arguments are not supported.  */

and:

/* Registers clobbered by syscall.  */
# define REGISTERS_CLOBBERED_BY_SYSCALL "cc", "r11", "cx"

#undef internal_syscall6
#define internal_syscall6(number, err, arg1, arg2, arg3, arg4, arg5, arg6) \
({                                  \
    unsigned long int resultvar;                    \
    TYPEFY (arg6, __arg6) = ARGIFY (arg6);              \
    TYPEFY (arg5, __arg5) = ARGIFY (arg5);              \
    TYPEFY (arg4, __arg4) = ARGIFY (arg4);              \
    TYPEFY (arg3, __arg3) = ARGIFY (arg3);              \
    TYPEFY (arg2, __arg2) = ARGIFY (arg2);              \
    TYPEFY (arg1, __arg1) = ARGIFY (arg1);              \
    register TYPEFY (arg6, _a6) asm ("r9") = __arg6;            \
    register TYPEFY (arg5, _a5) asm ("r8") = __arg5;            \
    register TYPEFY (arg4, _a4) asm ("r10") = __arg4;           \
    register TYPEFY (arg3, _a3) asm ("rdx") = __arg3;           \
    register TYPEFY (arg2, _a2) asm ("rsi") = __arg2;           \
    register TYPEFY (arg1, _a1) asm ("rdi") = __arg1;           \
    asm volatile (                          \
    "syscall\n\t"                           \
    : "=a" (resultvar)                          \
    : "0" (number), "r" (_a1), "r" (_a2), "r" (_a3), "r" (_a4),     \
      "r" (_a5), "r" (_a6)                      \
    : "memory", REGISTERS_CLOBBERED_BY_SYSCALL);            \
    (long int) resultvar;                       \
})

which I feel are pretty self explanatory. Note how this seems to have been designed to exactly match the calling convention of regular System V AMD64 ABI functions: https://en.wikipedia.org/wiki/X86_calling_conventions#List_of_x86_calling_conventions

Quick reminder of the clobbers:

  • cc means flag registers. But Peter Cordes comments that this is unnecessary here.
  • memory means that a pointer may be passed in assembly and used to access memory

For an explicit minimal runnable example from scratch see this answer: How to invoke a system call via syscall or sysenter in inline assembly?

Make some syscalls in assembly manually

Not very scientific, but fun:

  • x86_64.S

    .text
    .global _start
    _start:
    asm_main_after_prologue:
        /* write */
        mov $1, %rax    /* syscall number */
        mov $1, %rdi    /* stdout */
        mov $msg, %rsi  /* buffer */
        mov $len, %rdx  /* len */
        syscall
    
        /* exit */
        mov $60, %rax   /* syscall number */
        mov $0, %rdi    /* exit status */
        syscall
    msg:
        .ascii "hello\n"
    len = . - msg
    

    GitHub upstream.

Make system calls from C

Here's an example with register constraints: How to invoke a system call via syscall or sysenter in inline assembly?

aarch64

I've shown a minimal runnable userland example at: https://reverseengineering.stackexchange.com/questions/16917/arm64-syscalls-table/18834#18834 TODO grep kernel code here, should be easy.

OAuth2 and Google API: access token expiration time?

The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

I got this error when stubbing with sinon.

The fix is to use npm package sinon-as-promised when resolving or rejecting promises with stubs.

Instead of ...

sinon.stub(Database, 'connect').returns(Promise.reject( Error('oops') ))

Use ...

require('sinon-as-promised');
sinon.stub(Database, 'connect').rejects(Error('oops'));

There is also a resolves method (note the s on the end).

See http://clarkdave.net/2016/09/node-v6-6-and-asynchronously-handled-promise-rejections

In C++ check if std::vector<string> contains a certain value

it's in <algorithm> and called std::find.

Get GPS location from the web browser

To give a bit more specific answer. HTML5 allows you to get the geo coordinates, and it does a pretty decent job. Overall the browser support for geolocation is pretty good, all major browsers except ie7 and ie8 (and opera mini). IE9 does the job but is the worst performer. Checkout caniuse.com:

http://caniuse.com/#search=geol

Also you need the approval of your user to access their location, so make sure you check for this and give some decent instructions in case it's turned off. Especially for Iphone turning permissions on for Safari is a bit cumbersome.

Copy a table from one database to another in Postgres

First install dblink

Then, you would do something like:

INSERT INTO t2 select * from 
dblink('host=1.2.3.4
 user=*****
 password=******
 dbname=D1', 'select * t1') tt(
       id int,
  col_1 character varying,
  col_2 character varying,
  col_3 int,
  col_4 varchar 
);

How to save final model using keras?

You can use model.save(filepath) to save a Keras model into a single HDF5 file which will contain:

  • the architecture of the model, allowing to re-create the model.
  • the weights of the model.
  • the training configuration (loss, optimizer)
  • the state of the optimizer, allowing to resume training exactly where you left off.

In your Python code probable the last line should be:

model.save("m.hdf5")

This allows you to save the entirety of the state of a model in a single file. Saved models can be reinstantiated via keras.models.load_model().

The model returned by load_model() is a compiled model ready to be used (unless the saved model was never compiled in the first place).

model.save() arguments:

  • filepath: String, path to the file to save the weights to.
  • overwrite: Whether to silently overwrite any existing file at the target location, or provide the user with a manual prompt.
  • include_optimizer: If True, save optimizer's state together.

How to edit .csproj file

in vs 2019 Version 16.8.2 right click on you project name and click on "Edit Project File" enter image description here

How to set combobox default value?

Suppose you bound your combobox to a List<Person>

List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});

cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;

At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource

pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;

Of course this means that you need to add a checking code when you try to use the info from the combobox

if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
    MessageBox.Show("Please select a person name");
else
    ...... 

The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection

In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to

DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";    
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);

Subtract two dates in Java

Date d1 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
            getParameter(date1));
Date d2 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
            getParameter(date2));

long diff = d2.getTime() - d1.getTime();

System.out.println("Difference between  " + d1 + " and "+ d2+" is "
        + (diff / (1000 * 60 * 60 * 24)) + " days.");

What is the difference between HAVING and WHERE in SQL?

WHERE clause does not work for aggregate functions
means : you should not use like this bonus : table name

SELECT name  
FROM bonus  
GROUP BY name  
WHERE sum(salary) > 200  

HERE Instead of using WHERE clause you have to use HAVING..

without using GROUP BY clause, HAVING clause just works as WHERE clause

SELECT name  
FROM bonus  
GROUP BY name  
HAVING sum(salary) > 200  

laravel the requested url was not found on this server

Alternatively you could replace all the contents in your .htaccess file

Options +FollowSymLinks -Indexes
RewriteEngine On
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

See the docs here. https://laravel.com/docs/5.8/installation#web-server-configuration

Best approach to converting Boolean object to string in java

Depends on what you mean by "efficient". Performance-wise both versions are the same as its the same bytecode.

$ ./javap.exe -c java.lang.String | grep -A 10 "valueOf(boolean)"
  public static java.lang.String valueOf(boolean);
    Code:
       0: iload_0
       1: ifeq          9
       4: ldc           #14                 // String true
       6: goto          11
       9: ldc           #10                 // String false
      11: areturn


$ ./javap.exe -c java.lang.Boolean | grep -A 10 "toString(boolean)"
  public static java.lang.String toString(boolean);
    Code:
       0: iload_0
       1: ifeq          9
       4: ldc           #3                  // String true
       6: goto          11
       9: ldc           #2                  // String false
      11: areturn

How to set the 'selected option' of a select dropdown list with jquery

Try this :

$('select[name^="salesrep"] option[value="Bruce Jones"]').attr("selected","selected");

Just replace option[value="Bruce Jones"] by option[value=result[0]]

And before selecting a new option, you might want to "unselect" the previous :

$('select[name^="salesrep"] option:selected').attr("selected",null);

You may want to read this too : jQuery get specific option tag text

Edit: Using jQuery Mobile, this link may provide a good solution : jquery mobile - set select/option values

Specify JDK for Maven to use

I know its an old thread. But I was having some issues with something similar to this in Maven for Java 8 compiler source. I figured this out with a quick fix mentioned in this article thought I can put it here and maybe can help others:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

When to Redis? When to MongoDB?

Maybe this resource is useful helping decide between both. It also discusses several other NoSQL databases, and offers a short list of characteristics, along with a "what I would use it for" explanation for each of them.

http://kkovacs.eu/cassandra-vs-mongodb-vs-couchdb-vs-redis

How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

After wasting many hours, I came across this!

jquery-ui-touch-punch

It translates tap events as click events. Remember to load the script after jquery.

I got this working on the iPad and iPhone

$('#movable').draggable({containment: "parent"});

How can I convert an Int to a CString?

Here's one way:

CString str;
str.Format("%d", 5);

In your case, try _T("%d") or L"%d" rather than "%d"

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

The problem is that I missed out 'db' folder for the dbpath in the command:

C:\mongodb\bin> mongod --directoryperdb --dbpath C:\mongodb\data\db --logpath C:\mongodb\log\mongodb.log --logappend -rest --install

AngularJS - get element attributes values

You can do this using dataset property of the element, using with or without jquery it work... i'm not aware of old browser Note: that when you use dash ('-') sign, you need to use capital case. Eg. a-b => aB

_x000D_
_x000D_
function onContentLoad() {_x000D_
  var item = document.getElementById("id1");_x000D_
  var x = item.dataset.x;_x000D_
  var data = item.dataset.myData;_x000D_
_x000D_
  var resX = document.getElementById("resX");_x000D_
  var resData = document.getElementById("resData");_x000D_
_x000D_
  resX.innerText = x;_x000D_
  resData.innerText = data;_x000D_
_x000D_
  console.log(x);_x000D_
  console.log(data);_x000D_
}
_x000D_
<body onload="onContentLoad()">_x000D_
  <div id="id1" data-x="a" data-my-data="b"></div>_x000D_
_x000D_
  Read 'x':_x000D_
  <label id="resX"></label>_x000D_
  <br/>Read 'my-data':_x000D_
  <label id="resData"></label>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to use a DataAdapter with stored procedure and parameter

Short and sweet...

DataTable dataTable = new DataTable();
try
{
   using (var adapter = new SqlDataAdapter("StoredProcedureName", ConnectionString))
   {
       adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
       adapter.SelectCommand.Parameters.Add("@ParameterName", SqlDbType.Int).Value = 123;
       adapter.Fill(dataTable);
   };
}
catch (Exception ex)
{
    Logger.Error("Error occured while fetching records from SQL server", ex);
}

select rows in sql with latest date for each ID repeated multiple times

You can use a join to do this

SELECT t1.* from myTable t1
LEFT OUTER JOIN myTable t2 on t2.ID=t1.ID AND t2.`Date` > t1.`Date`
WHERE t2.`Date` IS NULL;

Only rows which have the latest date for each ID with have a NULL join to t2.

Using Google Translate in C#

I found this code works for me:

public String Translate(String word)
{
    var toLanguage = "en";//English
    var fromLanguage = "de";//Deutsch
    var url = $"https://translate.googleapis.com/translate_a/single?client=gtx&sl={fromLanguage}&tl={toLanguage}&dt=t&q={HttpUtility.UrlEncode(word)}";
    var webClient = new WebClient
    {
        Encoding = System.Text.Encoding.UTF8
    };
    var result = webClient.DownloadString(url);
    try
    {
        result = result.Substring(4, result.IndexOf("\"", 4, StringComparison.Ordinal) - 4);
        return result;
    }
    catch
    {
        return "Error";
    }
}

Using grep to search for hex strings in a file

If you want search for printable strings, you can use:

strings -ao filename | grep string

strings will output all printable strings from a binary with offsets, and grep will search within.

If you want search for any binary string, here is your friend:

jQuery UI Color Picker

Make sure you have jQuery UI base and the color picker widget included on your page (as well as a copy of jQuery 1.3):

<link rel="stylesheet" href="http://dev.jquery.com/view/tags/ui/latest/themes/flora/flora.all.css" type="text/css" media="screen" title="Flora (Default)">

<script type="text/javascript" src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.core.js"></script>

<script type="text/javascript" src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.colorpicker.js"></script>

If you have those included, try posting your source so we can see what's going on.

round a single column in pandas

Use the pandas.DataFrame.round() method like this:

df = df.round({'value1': 0})

Any columns not included will be left as is.

Why can't I declare static methods in an interface?

Now Java8 allows us to define even Static Methods in Interface.

interface X {
    static void foo() {
       System.out.println("foo");
    }
}

class Y implements X {
    //...
}

public class Z {
   public static void main(String[] args) {
      X.foo();
      // Y.foo(); // won't compile because foo() is a Static Method of X and not Y
   }
}

Note: Methods in Interface are still public abstract by default if we don't explicitly use the keywords default/static to make them Default methods and Static methods resp.

Printing tuple with string formatting in Python

You can try this one as well;

tup = (1,2,3)
print("this is a tuple {something}".format(something=tup))

You can't use %something with (tup) just because of packing and unpacking concept with tuple.

How do I change UIView Size?

This can be achieved in various methods in Swift 3.0 Worked on Latest version MAY- 2019

Directly assign the Height & Width values for a view:

userView.frame.size.height = 0

userView.frame.size.width = 10

Assign the CGRect for the Frame

userView.frame =  CGRect(x:0, y: 0, width:0, height:0)

Method Details:

CGRect(x: point of X, y: point of Y, width: Width of View, height: Height of View)

Using an Extension method for CGRECT

Add following extension code in any swift file,

extension CGRect {

    init(_ x:CGFloat, _ y:CGFloat, _ w:CGFloat, _ h:CGFloat) {

        self.init(x:x, y:y, width:w, height:h)
    }
}

Use the following code anywhere in your application for the view to set the size parameters

userView.frame =  CGRect(1, 1, 20, 45)

Initialize a Map containing arrays

Per Mozilla's Map documentation, you can initialize as follows:

private _gridOptions:Map<string, Array<string>> = 
    new Map([
        ["1", ["test"]],
        ["2", ["test2"]]
    ]);

Prevent Sequelize from outputting SQL to the console on execution of query?

When you create your Sequelize object, pass false to the logging parameter:

var sequelize = new Sequelize('database', 'username', 'password', {
  
  // disable logging; default: console.log
  logging: false

});

For more options, check the docs.

How to find the php.ini file used by the command line?

If you want all the configuration files loaded, this is will tell you:

php -i | grep "\.ini"

Some systems load things from more than one ini file. On my ubuntu system, it looks like this:

$  php -i | grep "\.ini"
Configuration File (php.ini) Path => /etc/php5/cli
Loaded Configuration File => /etc/php5/cli/php.ini
Scan this dir for additional .ini files => /etc/php5/cli/conf.d
additional .ini files parsed => /etc/php5/cli/conf.d/apc.ini,
/etc/php5/cli/conf.d/curl.ini,
/etc/php5/cli/conf.d/gd.ini,
/etc/php5/cli/conf.d/mcrypt.ini,
/etc/php5/cli/conf.d/memcache.ini,
/etc/php5/cli/conf.d/mysql.ini,
/etc/php5/cli/conf.d/mysqli.ini,
/etc/php5/cli/conf.d/pdo.ini,
/etc/php5/cli/conf.d/pdo_mysql.ini

Permission denied (publickey,keyboard-interactive)

You may want to double check the authorized_keys file permissions:

$ chmod 600 ~/.ssh/authorized_keys

Newer SSH server versions are very picky on this respect.

Change the Textbox height?

All you have to do is enable the multiline in the properties window, put the size you want in that same window and then in your .cs after the InitializeComponent put txtexample.Multiline = false; and so the multiline is not enabled but the size of the txt is as you put it.

InitializeComponent();
txtEmail.Multiline = false;
txtPassword.Multiline = false;

enter image description here

enter image description here

enter image description here

How to enable php7 module in apache?

I found the solution on the following thread : https://askubuntu.com/questions/760907/upgrade-to-16-04-php7-not-working-in-browser

Im my case not only the php wasn't working but phpmyadmin aswell i did step by step like that

sudo apt install php libapache2-mod-php
sudo apt install php7.0-mbstring
sudo a2dismod mpm_event
sudo a2enmod mpm_prefork
service apache2 restart

And then to:

gksu gedit /etc/apache2/apache2.conf

In the last line I do add Include /etc/phpmyadmin/apache.conf

That make a deal with all problems

Maciej

If it solves your problem, up vote this solution in the original post.

Folder is locked and I can't unlock it

Clean up, check all check box => This work for me

Select where count of one field is greater than one

As OMG Ponies stated, the having clause is what you are after. However, if you were hoping that you would get discrete rows instead of a summary (the "having" creates a summary) - it cannot be done in a single statement. You must use two statements in that case.

How to override application.properties during production in Spring-Boot?

I know you asked how to do this, but the answer is you should not do this.

Instead, have a application.properties, application-default.properties application-dev.properties etc., and switch profiles via args to the JVM: e.g. -Dspring.profiles.active=dev

You can also override some things at test time using @TestPropertySource

Ideally everything should be in source control so that there are no surprises e.g. How do you know what properties are sitting there in your server location, and which ones are missing? What happens if developers introduce new things?

Spring Boot is already giving you enough ways to do this right.

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

How to convert timestamps to dates in Bash?

You can get formatted date from timestamp like this

date +'%Y-%m-%d %H:%M:%S' -d "@timestamp"

How to set a CheckBox by default Checked in ASP.Net MVC

I use viewbag with the same variable name in the Controller. E.g if the variable is called "IsActive" and I want this to default to true on the "Create" form, on the Create Action I set the value ViewBag.IsActive = true;

public ActionResult Create()
{
    ViewBag.IsActive = true;
    return View();
}

Ascii/Hex convert in bash

For single line solution:

echo "Hello World" | xxd -ps -c 200 | tr -d '\n'

It will print:

48656c6c6f20576f726c640a

or for files:

cat /path/to/file | xxd -ps -c 200 | tr -d '\n'

For reverse operation:

echo '48656c6c6f20576f726c640a' | xxd -ps -r

It will print:

Hello World

Quick unix command to display specific lines in the middle of a file?

I am surprised only one other answer (by Ramana Reddy) suggested to add line numbers to the output. The following searches for the required line number and colours the output.

file=FILE
lineno=LINENO
wb="107"; bf="30;1"; rb="101"; yb="103"
cat -n ${file} | { GREP_COLORS="se=${wb};${bf}:cx=${wb};${bf}:ms=${rb};${bf}:sl=${yb};${bf}" grep --color -C 10 "^[[:space:]]\\+${lineno}[[:space:]]"; }

jQuery: get data attribute

This is what I came up with:

_x000D_
_x000D_
  $(document).ready(function(){_x000D_
  _x000D_
  $(".fc-event").each(function(){_x000D_
  _x000D_
   console.log(this.attributes['data'].nodeValue) _x000D_
  });_x000D_
    _x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>_x000D_
<div id='external-events'>_x000D_
   <h4>Booking</h4>_x000D_
   <div class='fc-event' data='00:30:00' >30 Mins</div>_x000D_
   <div class='fc-event' data='00:45:00' >45 Mins</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Select n random rows from SQL Server table

Try this:

SELECT TOP 10 Field1, ..., FieldN
FROM Table1
ORDER BY NEWID()

How does java do modulus calculations with negative numbers?

Modulo arithmetic with negative operands is defined by the language designer, who might leave it to the language implementation, who might defer the definition to the CPU architecture.

I wasn't able to find a Java language definition.
Thanks Ishtar, Java Language Specification for the Remainder Operator % says that the sign of the result is the same as the sign of the numerator.

Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

if you have remote server installed on you machine. give server.py host as "localhost" and the port number. then client side , you have to give local ip- 127.0.0.1 and port number. then its works

How to compare 2 dataTables

 public static bool AreTablesTheSame( DataTable tbl1, DataTable tbl2)
 {
    if (tbl1.Rows.Count != tbl2.Rows.Count || tbl1.Columns.Count != tbl2.Columns.Count)
                return false;


    for ( int i = 0; i < tbl1.Rows.Count; i++)
    {
        for ( int c = 0; c < tbl1.Columns.Count; c++)
        {
            if (!Equals(tbl1.Rows[i][c] ,tbl2.Rows[i][c]))
                        return false;
        }
     }
     return true;
  }

How do you Make A Repeat-Until Loop in C++?

Just use:

do
{
  //enter code here
} while ( !condition );

So what this does is, it moves your 'check for condition' part to the end, since the while is at the end. So it only checks the condition after running the code, just like how you want it

Bind event to right mouse click

To disable right click context menu on all images of a page simply do this with following:

jQuery(document).ready(function(){
    // Disable context menu on images by right clicking
    for(i=0;i<document.images.length;i++) {
        document.images[i].onmousedown = protect;
    }
});

function protect (e) {
    //alert('Right mouse button not allowed!');
    this.oncontextmenu = function() {return false;};
}

How to compare timestamp dates with date-only parameter in MySQL?

As I was researching this I thought it would be nice to modify the BETWEEN solution to show an example for a particular non-static/string date, but rather a variable date, or today's such as CURRENT_DATE(). This WILL use the index on the log_timestamp column.

SELECT *
FROM some_table
WHERE
    log_timestamp
    BETWEEN 
        timestamp(CURRENT_DATE()) 
    AND # Adds 23.9999999 HRS of seconds to the current date
        timestamp(DATE_ADD(CURRENT_DATE(), INTERVAL '86399.999999' SECOND_MICROSECOND));

I did the seconds/microseconds to avoid the 12AM case on the next day. However, you could also do `INTERVAL '1 DAY' via comparison operators for a more reader-friendly non-BETWEEN approach:

SELECT *
FROM some_table
WHERE
    log_timestamp >= timestamp(CURRENT_DATE()) AND
    log_timestamp < timestamp(DATE_ADD(CURRENT_DATE(), INTERVAL 1 DAY));

Both of these approaches will use the index and should perform MUCH faster. Both seem to be equally as fast.