Programs & Examples On #Formsauthentication

How does HttpContext.Current.User.Identity.Name know which usernames exist?

The HttpContext.Current.User.Identity.Name returns null

This depends on whether the authentication mode is set to Forms or Windows in your web.config file.

For example, if I write the authentication like this:

<authentication mode="Forms"/>

Then because the authentication mode="Forms", I will get null for the username. But if I change the authentication mode to Windows like this:

<authentication mode="Windows"/>

I can run the application again and check for the username, and I will get the username successfully.

For more information, see System.Web.HttpContext.Current.User.Identity.Name Vs System.Environment.UserName in ASP.NET.

How to get the cookie value in asp.net website

FormsAuthentication.Decrypt takes the actual value of the cookie, not the name of it. You can get the cookie value like

HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value;

and decrypt that.

How to check user is "logged in"?

Easiest way to check if they are authenticated is Request.User.IsAuthenticated I think (from memory)

Hash string in c#

The shortest and fastest way ever. Only 1 line!

    public static string StringSha256Hash(string text) =>
        string.IsNullOrEmpty(text) ? string.Empty : BitConverter.ToString(new System.Security.Cryptography.SHA256Managed().ComputeHash(System.Text.Encoding.UTF8.GetBytes(text))).Replace("-", string.Empty);

Hash and salt passwords in C#

 protected void m_GenerateSHA256_Button1_Click(objectSender, EventArgs e)
{
string salt =createSalt(10);
string hashedPassword=GenerateSHA256Hash(m_UserInput_TextBox.Text,Salt);
m_SaltHash_TextBox.Text=Salt;
 m_SaltSHA256Hash_TextBox.Text=hashedPassword;

}
 public string createSalt(int size)
{
 var rng= new System.Security.Cyptography.RNGCyptoServiceProvider();
 var buff= new byte[size];
rng.GetBytes(buff);
 return Convert.ToBase64String(buff);
}


 public string GenerateSHA256Hash(string input,string salt)
{
 byte[]bytes=System.Text.Encoding.UTF8.GetBytes(input+salt);
 new System.Security.Cyptography.SHA256Managed();
 byte[]hash=sha256hashString.ComputedHash(bytes);
 return bytesArrayToHexString(hash);
  }

ASP.NET MVC - Set custom IIdentity or IPrincipal

I can't speak directly for ASP.NET MVC, but for ASP.NET Web Forms, the trick is to create a FormsAuthenticationTicket and encrypt it into a cookie once the user has been authenticated. This way, you only have to call the database once (or AD or whatever you are using to perform your authentication), and each subsequent request will authenticate based on the ticket stored in the cookie.

A good article on this: http://www.ondotnet.com/pub/a/dotnet/2004/02/02/effectiveformsauth.html (broken link)

Edit:

Since the link above is broken, I would recommend LukeP's solution in his answer above: https://stackoverflow.com/a/10524305 - I would also suggest that the accepted answer be changed to that one.

Edit 2: An alternative for the broken link: https://web.archive.org/web/20120422011422/http://ondotnet.com/pub/a/dotnet/2004/02/02/effectiveformsauth.html

What do two question marks together mean in C#?

coalescing operator

it's equivalent to

FormsAuth = formsAUth == null ? new FormsAuthenticationWrapper() : formsAuth

FormsAuthentication.SignOut() does not log the user out

It could be that you are logging in from one subdomain (sub1.domain.com) and then trying to logout from a different subdomain (www.domain.com).

How can I enable CORS on Django REST Framework

Well, I don't know guys but:

using here python 3.6 and django 2.2

Renaming MIDDLEWARE_CLASSES to MIDDLEWARE in settings.py worked.

What is the iOS 5.0 user agent string?

fixed my agent string evaluation by scrubbing the string for LOWERCASE "iphone os 5_0" as opposed to "iPhone OS 5_0." now i am properly assigning iOS 5 specific classes to my html, when the uppercase scrub failed.

Create MSI or setup project with Visual Studio 2012

Have a look at the article Visual Studio Installer Deployment. It will surely help you.

You can choose the correct version of .NET framework on the page. So for you, make it .NET 4.5. I guess that would be there for Visual Studio 2012.

How to run 'sudo' command in windows

There is no sudo command in Windows. The nearest equivalent is "run as administrator."

You can do this using the runas command with an administrator trust-level, or by right-clicking the program in the UI and choosing "run as administrator."

How to check is Apache2 is stopped in Ubuntu?

You can also type "top" and look at the list of running processes.

MySQL - Rows to Columns

I make that into Group By hostId then it will show only first row with values,
like:

A   B  C
1  10
2      3

Remove element by id

Functions that use ele.parentNode.removeChild(ele) won't work for elements you've created but not yet inserted into the HTML. Libraries like jQuery and Prototype wisely use a method like the following to evade that limitation.

_limbo = document.createElement('div');
function deleteElement(ele){
    _limbo.appendChild(ele);
    _limbo.removeChild(ele);
}

I think JavaScript works like that because the DOM's original designers held parent/child and previous/next navigation as a higher priority than the DHTML modifications that are so popular today. Being able to read from one <input type='text'> and write to another by relative location in the DOM was useful in the mid-90s, a time when the dynamic generation of entire HTML forms or interactive GUI elements was barely a twinkle in some developer's eye.

What are the use cases for selecting CHAR over VARCHAR in SQL?

In some SQL databases, VARCHAR will be padded out to its maximum size in order to optimize the offsets, This is to speed up full table scans and indexes.

Because of this, you do not have any space savings by using a VARCHAR(200) compared to a CHAR(200)

how to extract only the year from the date in sql server 2008?

You can use year() function in sql to get the year from the specified date.

Syntax:

YEAR ( date )

For more information check here

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

This can happen if you have a newline (or other control character) in a JSON string literal.

{"foo": "bar
baz"}

If you are the one producing the data, replace actual newlines with escaped ones "\\n" when creating your string literals.

{"foo": "bar\nbaz"}

Force flushing of output to a file while bash script is still running

Buffering of output depends on how your program /homedir/MyScript is implemented. If you find that output is getting buffered, you have to force it in your implementation. For example, use sys.stdout.flush() if it's a python program or use fflush(stdout) if it's a C program.

Styling JQuery UI Autocomplete

Based on @md-nazrul-islam reply, This is what I did with SCSS:

ul.ui-autocomplete {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    float: left;
    display: none;
    min-width: 160px;
    margin: 0 0 10px 25px;
    list-style: none;
    background-color: #ffffff;
    border: 1px solid #ccc;
    border-color: rgba(0, 0, 0, 0.2);
    //@include border-radius(5px);
    @include box-shadow( rgba(0, 0, 0, 0.1) 0 5px 10px );
    @include background-clip(padding-box);
    *border-right-width: 2px;
    *border-bottom-width: 2px;

    li.ui-menu-item{
        padding:0 .5em;
        line-height:2em;
        font-size:.8em;
        &.ui-state-focus{
            background: #F7F7F7;
        }
    }

}

How can I emulate a get request exactly like a web browser?

i'll make an example, first decide what browser you want to emulate, in this case i chose Firefox 60.6.1esr (64-bit), and check what GET request it issues, this can be obtained with a simple netcat server (MacOS bundles netcat, most linux distributions bunles netcat, and Windows users can get netcat from.. Cygwin.org , among other places),

setting up the netcat server to listen on port 9999: nc -l 9999

now hitting http://127.0.0.1:9999 in firefox, i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

now let us compare that with this simple script:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_exec($ch);

i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
Accept: */*

there are several missing headers here, they can all be added with the CURLOPT_HTTPHEADER option of curl_setopt, but the User-Agent specifically should be set with CURLOPT_USERAGENT instead (it will be persistent across multiple calls to curl_exec() and if you use CURLOPT_FOLLOWLOCATION then it will persist across http redirections as well), and the Accept-Encoding header should be set with CURLOPT_ENCODING instead (if they're set with CURLOPT_ENCODING then curl will automatically decompress the response if the server choose to compress it, but if you set it via CURLOPT_HTTPHEADER then you must manually detect and decompress the content yourself, which is a pain in the ass and completely unnecessary, generally speaking) so adding those we get:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

now running that code, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Upgrade-Insecure-Requests: 1

and voila! our php-emulated browser GET request should now be indistinguishable from the real firefox GET request :)

this next part is just nitpicking, but if you look very closely, you'll see that the headers are stacked in the wrong order, firefox put the Accept-Encoding header in line 6, and our emulated GET request puts it in line 3.. to fix this, we can manually put the Accept-Encoding header in the right line,

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Accept-Encoding: gzip, deflate',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

running that, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

problem solved, now the headers is even in the correct order, and the request seems to be COMPLETELY INDISTINGUISHABLE from the real firefox request :) (i don't actually recommend this last step, it's a maintenance burden to keep CURLOPT_ENCODING in sync with the custom Accept-Encoding header, and i've never experienced a situation where the order of the headers are significant)

Python TypeError must be str not int

Python comes with numerous ways of formatting strings:

New style .format(), which supports a rich formatting mini-language:

>>> temperature = 10
>>> print("the furnace is now {} degrees!".format(temperature))
the furnace is now 10 degrees!

Old style % format specifier:

>>> print("the furnace is now %d degrees!" % temperature)
the furnace is now 10 degrees!

In Py 3.6 using the new f"" format strings:

>>> print(f"the furnace is now {temperature} degrees!")
the furnace is now 10 degrees!

Or using print()s default separator:

>>> print("the furnace is now", temperature, "degrees!")
the furnace is now 10 degrees!

And least effectively, construct a new string by casting it to a str() and concatenating:

>>> print("the furnace is now " + str(temperature) + " degrees!")
the furnace is now 10 degrees!

Or join()ing it:

>>> print(' '.join(["the furnace is now", str(temperature), "degrees!"]))
the furnace is now 10 degrees!

difference between $query>num_rows() and $this->db->count_all_results() in CodeIgniter & which one is recommended

$sql = "select count(*) as row from login WHERE firstname = '" . $username . "' AND password = '" . $password . "'";
    $query = $this->db->query($sql);
    print_r($query);exit;
    if ($query->num_rows() == 1) {
    return true;
    } else {
    return false;
    }

How to change menu item text dynamically in Android

I use this code to costum my bottom navigation item

BottomNavigationView navigation = this.findViewById(R.id.my_bottom_navigation);
Menu menu = navigation.getMenu();
menu.findItem(R.id.nav_wall_see).setTitle("Hello");

Create a .csv file with values from a Python list

Here is working copy-paste example for Python 3.x with options to define your own delimiter and quote char.

import csv

mylist = ['value 1', 'value 2', 'value 3']

with open('employee_file.csv', mode='w') as employee_file:
    employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
    employee_writer.writerow(mylist)

This will generate employee_file.csv that looks like this:

"value 1","value 2","value 3"

NOTE:

If quoting is set to csv.QUOTE_MINIMAL, then .writerow() will quote fields only if they contain the delimiter or the quotechar. This is the default case.

If quoting is set to csv.QUOTE_ALL, then .writerow() will quote all fields.

If quoting is set to csv.QUOTE_NONNUMERIC, then .writerow() will quote all fields containing text data and convert all numeric fields to the float data type.

If quoting is set to csv.QUOTE_NONE, then .writerow() will escape delimiters instead of quoting them. In this case, you also must provide a value for the escapechar optional parameter.

selecting rows with id from another table

Try this (subquery):

SELECT * FROM terms WHERE id IN 
   (SELECT term_id FROM terms_relation WHERE taxonomy = "categ")

Or you can try this (JOIN):

SELECT t.* FROM terms AS t 
   INNER JOIN terms_relation AS tr 
   ON t.id = tr.term_id AND tr.taxonomy = "categ"

If you want to receive all fields from two tables:

SELECT t.id, t.name, t.slug, tr.description, tr.created_at, tr.updated_at 
  FROM terms AS t 
   INNER JOIN terms_relation AS tr 
   ON t.id = tr.term_id AND tr.taxonomy = "categ"

How to get my project path?

You can use

string wanted_path = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));

Delete all nodes and relationships in neo4j 1.8

if the name of node is for example : abcd then below query will work :

MATCH (n:abcd)
DETACH DELETE n

This will only delete the node with label "abcd" and all its relation-ships.

What is the best way to uninstall gems from a rails3 project?

With newer versions of bundler you can use the clean task:

$ bundle help clean
Usage:
    bundle clean

Options:
    [--dry-run=only print out changes, do not actually clean gems]
    [--force=forces clean even if --path is not set]
    [--no-color=Disable colorization in output]
    -V, [--verbose=Enable verbose output mode]

Cleans up unused gems in your bundler directory
$ bundle clean --dry-run --force
Would have removed actionmailer (3.1.12)
Would have removed actionmailer (3.2.0.rc2)
Would have removed actionpack (3.1.12)
Would have removed actionpack (3.2.0.rc2)
Would have removed activemodel (3.1.12)
...

edit:

This is not recommended if you're using a global gemset (i.e. - all of your projects keep their gems in the same place). There're few ways to keep each project's gems separate, though:

  1. rvm gemsets (http://rvm.io/gemsets/basics)
  2. bundle install with any of the following options: --deployment or --path=<path> (http://bundler.io/v1.3/man/bundle-install.1.html)

How to git commit a single file/directory

you try if You are in Master branch git commit -m "Commit message" -- filename.ext

How to generate the "create table" sql statement for an existing table in postgreSQL

Like the other answers mentioned, there is no built in function that does this.

Here is a function that attempts to get all of the information that would be needed to replicate the table - or to compare deployed and checked in ddl.

This function outputs:

  • columns (w/ precision, null/not-null, default value)
  • constraints
  • indexes

CREATE OR REPLACE FUNCTION public.show_create_table(
  in_schema_name varchar,
  in_table_name varchar
)
RETURNS text
LANGUAGE plpgsql VOLATILE
AS
$$
  DECLARE
    -- the ddl we're building
    v_table_ddl text;

    -- data about the target table
    v_table_oid int;

    -- records for looping
    v_column_record record;
    v_constraint_record record;
    v_index_record record;
  BEGIN
    -- grab the oid of the table; https://www.postgresql.org/docs/8.3/catalog-pg-class.html
    SELECT c.oid INTO v_table_oid
    FROM pg_catalog.pg_class c
    LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
    WHERE 1=1
      AND c.relkind = 'r' -- r = ordinary table; https://www.postgresql.org/docs/9.3/catalog-pg-class.html
      AND c.relname = in_table_name -- the table name
      AND n.nspname = in_schema_name; -- the schema

    -- throw an error if table was not found
    IF (v_table_oid IS NULL) THEN
      RAISE EXCEPTION 'table does not exist';
    END IF;

    -- start the create definition
    v_table_ddl := 'CREATE TABLE ' || in_schema_name || '.' || in_table_name || ' (' || E'\n';

    -- define all of the columns in the table; https://stackoverflow.com/a/8153081/3068233
    FOR v_column_record IN
      SELECT
        c.column_name,
        c.data_type,
        c.character_maximum_length,
        c.is_nullable,
        c.column_default
      FROM information_schema.columns c
      WHERE (table_schema, table_name) = (in_schema_name, in_table_name)
      ORDER BY ordinal_position
    LOOP
      v_table_ddl := v_table_ddl || '  ' -- note: two char spacer to start, to indent the column
        || v_column_record.column_name || ' '
        || v_column_record.data_type || CASE WHEN v_column_record.character_maximum_length IS NOT NULL THEN ('(' || v_column_record.character_maximum_length || ')') ELSE '' END || ' '
        || CASE WHEN v_column_record.is_nullable = 'NO' THEN 'NOT NULL' ELSE 'NULL' END
        || CASE WHEN v_column_record.column_default IS NOT null THEN (' DEFAULT ' || v_column_record.column_default) ELSE '' END
        || ',' || E'\n';
    END LOOP;

    -- define all the constraints in the; https://www.postgresql.org/docs/9.1/catalog-pg-constraint.html && https://dba.stackexchange.com/a/214877/75296
    FOR v_constraint_record IN
      SELECT
        con.conname as constraint_name,
        con.contype as constraint_type,
        CASE
          WHEN con.contype = 'p' THEN 1 -- primary key constraint
          WHEN con.contype = 'u' THEN 2 -- unique constraint
          WHEN con.contype = 'f' THEN 3 -- foreign key constraint
          WHEN con.contype = 'c' THEN 4
          ELSE 5
        END as type_rank,
        pg_get_constraintdef(con.oid) as constraint_definition
      FROM pg_catalog.pg_constraint con
      JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid
      JOIN pg_catalog.pg_namespace nsp ON nsp.oid = connamespace
      WHERE nsp.nspname = in_schema_name
      AND rel.relname = in_table_name
      ORDER BY type_rank
    LOOP
      v_table_ddl := v_table_ddl || '  ' -- note: two char spacer to start, to indent the column
        || 'CONSTRAINT' || ' '
        || v_constraint_record.constraint_name || ' '
        || v_constraint_record.constraint_definition
        || ',' || E'\n';
    END LOOP;

    -- drop the last comma before ending the create statement
    v_table_ddl = substr(v_table_ddl, 0, length(v_table_ddl) - 1) || E'\n';

    -- end the create definition
    v_table_ddl := v_table_ddl || ');' || E'\n';

    -- suffix create statement with all of the indexes on the table
    FOR v_index_record IN
      SELECT indexdef
      FROM pg_indexes
      WHERE (schemaname, tablename) = (in_schema_name, in_table_name)
    LOOP
      v_table_ddl := v_table_ddl
        || v_index_record.indexdef
        || ';' || E'\n';
    END LOOP;

    -- return the ddl
    RETURN v_table_ddl;
  END;
$$;

example

SELECT * FROM public.show_create_table('public', 'example_table');

produces

CREATE TABLE public.example_table (
  id bigint NOT NULL DEFAULT nextval('test_tb_for_show_create_on_id_seq'::regclass),
  name character varying(150) NULL,
  level character varying(50) NULL,
  description text NOT NULL DEFAULT 'hello there!'::text,
  CONSTRAINT test_tb_for_show_create_on_pkey PRIMARY KEY (id),
  CONSTRAINT test_tb_for_show_create_on_level_check CHECK (((level)::text = ANY ((ARRAY['info'::character varying, 'warn'::character varying, 'error'::character varying])::text[])))
);
CREATE UNIQUE INDEX test_tb_for_show_create_on_pkey ON public.test_tb_for_show_create_on USING btree (id);

Selecting specific rows and columns from NumPy array

Fancy indexing requires you to provide all indices for each dimension. You are providing 3 indices for the first one, and only 2 for the second one, hence the error. You want to do something like this:

>>> a[[[0, 0], [1, 1], [3, 3]], [[0,2], [0,2], [0, 2]]]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

That is of course a pain to write, so you can let broadcasting help you:

>>> a[[[0], [1], [3]], [0, 2]]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

This is much simpler to do if you index with arrays, not lists:

>>> row_idx = np.array([0, 1, 3])
>>> col_idx = np.array([0, 2])
>>> a[row_idx[:, None], col_idx]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

Compiled vs. Interpreted Languages

Short (un-precise) definition:

Compiled language: Entire program is translated to machine code at once, then the machine code is run by the CPU.

Interpreted language: Program is read line-by-line and as soon as a line is read the machine instructions for that line are executed by the CPU.

But really, few languages these days are purely compiled or purely interpreted, it often is a mix. For a more detailed description with pictures, see this thread:

What is the difference between compilation and interpretation?

Or my later blog post:

https://orangejuiceliberationfront.com/the-difference-between-compiler-and-interpreter/

Is there an opposite of include? for Ruby Arrays?

Looking at Ruby only:

TL;DR

Use none? passing it a block with == for the comparison:

[1, 2].include?(1)
  #=> true
[1, 2].none? { |n| 1 == n  }
  #=> false

Array#include? accepts one argument and uses == to check against each element in the array:

player = [1, 2, 3]
player.include?(1)
 #=> true

Enumerable#none? can also accept one argument in which case it uses === for the comparison. To get the opposing behaviour to include? we omit the parameter and pass it a block using == for the comparison.

player.none? { |n| 7 == n }
 #=> true 
!player.include?(7)    #notice the '!'
 #=> true

In the above example we can actually use:

player.none?(7)
 #=> true

That's because Integer#== and Integer#=== are equivalent. But consider:

player.include?(Integer)
 #=> false
player.none?(Integer)
 #=> false

none? returns false because Integer === 1 #=> true. But really a legit notinclude? method should return true. So as we did before:

player.none? { |e| Integer == e  }
 #=> true

Convert Linq Query Result to Dictionary

Try using the ToDictionary method like so:

var dict = TableObj.ToDictionary( t => t.Key, t => t.TimeStamp );

How can I store the result of a system command in a Perl variable?

The easiest way is to use the `` feature in Perl. This will execute what is inside and return what was printed to stdout:

 my $pid = 5892;
 my $var = `top -H -p $pid -n 1 | grep myprocess | wc -l`;
 print "not = $var\n";

This should do it.

Extract month and year from a zoo::yearmon object

For large vectors:

y = as.POSIXlt(date1)$year + 1900    # x$year : years since 1900
m = as.POSIXlt(date1)$mon + 1        # x$mon : 0–11

Set a border around a StackPanel.

You set DockPanel.Dock="Top" to the StackPanel, but the StackPanel is not a child of the DockPanel... the Border is. Your docking property is being ignored.

If you move DockPanel.Dock="Top" to the Border instead, both of your problems will be fixed :)

How to hide reference counts in VS2013?

Workaround....

In VS 2015 Professional (and probably other versions). Go to Tools / Options / Environment / Fonts and Colours. In the "Show Settings For" drop-down, select "CodeLens" Choose the smallest font you can find e.g. Calibri 6. Change the foreground colour to your editor foreground colour (say "White") Click OK.

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

There's a great blog post on this here:

http://www.kylejlarson.com/blog/2011/fixed-elements-and-scrolling-divs-in-ios-5/

Along with a demo here:

http://www.kylejlarson.com/files/iosdemo/

In summary, you can use the following on a div containing your main content:

.scrollable {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: scroll;
    -webkit-overflow-scrolling: touch;
}

The problem I think you're describing is when you try to scroll up within a div that is already at the top - it then scrolls up the page instead of up the div and causes a bounce effect at the top of the page. I think your question is asking how to get rid of this?

In order to fix this, the author suggests that you use ScrollFix to auto increase the height of scrollable divs.

It's also worth noting that you can use the following to prevent the user from scrolling up e.g. in a navigation element:

document.addEventListener('touchmove', function(event) {
   if(event.target.parentNode.className.indexOf('noBounce') != -1 
|| event.target.className.indexOf('noBounce') != -1 ) {
    event.preventDefault(); }
}, false);

Unfortunately there are still some issues with ScrollFix (e.g. when using form fields), but the issues list on ScrollFix is a good place to look for alternatives. Some alternative approaches are discussed in this issue.

Other alternatives, also mentioned in the blog post, are Scrollability and iScroll

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

Maybe check Hibernate Validator 4.0, the Reference Implementation of the JSR 303: Bean Validation.

This is an example of an annotated class:

public class Address {

    @NotNull 
    private String line1;
    private String line2;
    private String zip;
    private String state;

    @Length(max = 20)
    @NotNull
    private String country;

    @Range(min = -2, max = 50, message = "Floor out of range")
    public int floor;

        ...
}

For an introduction, see Getting started with JSR 303 (Bean Validation) – part 1 and part 2 or the "Getting started" section of the reference guide which is part of the Hibernate Validator distribution.

how to add or embed CKEditor in php page

Alternately, it could also be done as:

<?php
    include("ckeditor/ckeditor.php");
    $CKeditor = new CKeditor();
    $CKeditor->BasePath = 'ckeditor/';
    $CKeditor->editor('editor1');
?>

Note that the last line is having 'editor1' as name, it could be changed as per your requirement.

Try-Catch-End Try in VBScript doesn't seem to work

VBScript doesn't have Try/Catch. (VBScript language reference. If it had Try, it would be listed in the Statements section.)

On Error Resume Next is the only error handling in VBScript. Sorry. If you want try/catch, JScript is an option. It's supported everywhere that VBScript is and has the same capabilities.

How to pass data to view in Laravel?

You can pass data to the view using the with method.

return view('greeting', ['name' => 'James']);

Using BufferedReader to read Text File

private void readFile() throws Exception {
      AsynchronousFileChannel input=AsynchronousFileChannel.open(Paths.get("E:/dicom_server_storage/abc.txt"),StandardOpenOption.READ);
      ByteBuffer buffer=ByteBuffer.allocate(1024);
      input.read(buffer,0,null,new CompletionHandler<Integer,Void>(){
        @Override public void completed(    Integer result,    Void attachment){
          System.out.println("Done reading the file.");
        }
        @Override public void failed(    Throwable exc,    Void attachment){
          System.err.println("An error occured:" + exc.getMessage());
        }
      }
    );
      System.out.println("This thread keeps on running");
      Thread.sleep(100);
    }

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

<table>
     <ng-container *ngFor="let group of groups">
         <tr><td><h2>{{group.name}}</h2></td></tr>
         <tr *ngFor="let item of group.items"><td>{{item}}</td></tr>
     </ng-container>
</table>

Eclipse error: "Editor does not contain a main type"

Did you import the packages for the file reading stuff.

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

also here

cfiltering(numberOfUsers, numberOfMovies);

Are you trying to create an object or calling a method?

also another thing:

user_movie_matrix[userNo][movieNo]=rating;

you are assigning a value to a member of an instance as if it was a static variable also remove the Th in

private int user_movie_matrix[][];Th

Hope this helps.

How do I specify new lines on Python, when writing on files?

You can either write in the new lines separately or within a single string, which is easier.

Example 1

Input

line1 = "hello how are you"
line2 = "I am testing the new line escape sequence"
line3 = "this seems to work"

You can write the '\n' separately:

file.write(line1)
file.write("\n")
file.write(line2)
file.write("\n")
file.write(line3)
file.write("\n")

Output

hello how are you
I am testing the new line escape sequence
this seems to work

Example 2

Input

As others have pointed out in the previous answers, place the \n at the relevant points in your string:

line = "hello how are you\nI am testing the new line escape sequence\nthis seems to work"

file.write(line)

Output

hello how are you
I am testing the new line escape sequence
this seems to work

Best approach to converting Boolean object to string in java

I don't think there would be any significant performance difference between them, but I would prefer the 1st way.

If you have a Boolean reference, Boolean.toString(boolean) will throw NullPointerException if your reference is null. As the reference is unboxed to boolean before being passed to the method.

While, String.valueOf() method as the source code shows, does the explicit null check:

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

Just test this code:

Boolean b = null;

System.out.println(String.valueOf(b));    // Prints null
System.out.println(Boolean.toString(b));  // Throws NPE

For primitive boolean, there is no difference.

How to confirm RedHat Enterprise Linux version?

Avoid /etc/*release* files and run this command instead, it is far more reliable and gives more details:

rpm -qia '*release*'

What is the purpose of nameof?

It's really useful for ArgumentException and its derivatives:

public string DoSomething(string input) 
{
    if(input == null) 
    {
        throw new ArgumentNullException(nameof(input));
    }
    ...

Now if someone refactors the name of the input parameter the exception will be kept up to date too.

It is also useful in some places where previously reflection had to be used to get the names of properties or parameters.

In your example nameof(T) gets the name of the type parameter - this can be useful too:

throw new ArgumentException(nameof(T), $"Type {typeof(T)} does not support this method.");

Another use of nameof is for enums - usually if you want the string name of an enum you use .ToString():

enum MyEnum { ... FooBar = 7 ... }

Console.WriteLine(MyEnum.FooBar.ToString());

> "FooBar"

This is actually relatively slow as .Net holds the enum value (i.e. 7) and finds the name at run time.

Instead use nameof:

Console.WriteLine(nameof(MyEnum.FooBar))

> "FooBar"

Now .Net replaces the enum name with a string at compile time.


Yet another use is for things like INotifyPropertyChanged and logging - in both cases you want the name of the member that you're calling to be passed to another method:

// Property with notify of change
public int Foo
{
    get { return this.foo; }
    set
    {
        this.foo = value;
        PropertyChanged(this, new PropertyChangedEventArgs(nameof(this.Foo));
    }
}

Or...

// Write a log, audit or trace for the method called
void DoSomething(... params ...)
{
    Log(nameof(DoSomething), "Message....");
}

Find the number of employees in each department - SQL Oracle

A request to list "Number of employees in each department" or "Display how many people work in each department" is the same as "For each department, list the number of employees", this must include departments with no employees. In the sample database, Operations has 0 employees. So a LEFT OUTER JOIN should be used.

SELECT dept.name, COUNT(emp.empno) AS count
FROM dept
LEFT OUTER JOIN emp ON emp.deptno = dept.deptno
GROUP BY dept.name;

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

  1. The accepted answer is one way of fixing the issue, because it will just apply some strategy for the problematic dependency (com.google.code.findbugs:jsr305) and it will resolve the problem around the project, using some version of this dependency. Basically it will align the versions of this library inside the whole project.

  2. There is an answer from @Santhosh (and couple of other people) who suggests to exclude the same dependency for espresso, which should work by the same way, but if the project has some other dependencies who depend on the same library (com.google.code.findbugs:jsr305), again we will have the same issue. So in order to use this approach you will need to exclude the same group from all project dependencies, who depend on com.google.code.findbugs:jsr305. I personally found that Espresso Contrib and Espresso Intents also use com.google.code.findbugs:jsr305.

I hope this thoughts will help somebody to realise what exactly is happening here and how things work (not just copy paste some code) :).

Find location of a removable SD card

I have created a utils method to check a SD card is available on device or not, and get SD card path on device if it available.

You can copy 2 methods bellow into your project's class that you need. That's all.

public String isRemovableSDCardAvailable() {
    final String FLAG = "mnt";
    final String SECONDARY_STORAGE = System.getenv("SECONDARY_STORAGE");
    final String EXTERNAL_STORAGE_DOCOMO = System.getenv("EXTERNAL_STORAGE_DOCOMO");
    final String EXTERNAL_SDCARD_STORAGE = System.getenv("EXTERNAL_SDCARD_STORAGE");
    final String EXTERNAL_SD_STORAGE = System.getenv("EXTERNAL_SD_STORAGE");
    final String EXTERNAL_STORAGE = System.getenv("EXTERNAL_STORAGE");

    Map<Integer, String> listEnvironmentVariableStoreSDCardRootDirectory = new HashMap<Integer, String>();
    listEnvironmentVariableStoreSDCardRootDirectory.put(0, SECONDARY_STORAGE);
    listEnvironmentVariableStoreSDCardRootDirectory.put(1, EXTERNAL_STORAGE_DOCOMO);
    listEnvironmentVariableStoreSDCardRootDirectory.put(2, EXTERNAL_SDCARD_STORAGE);
    listEnvironmentVariableStoreSDCardRootDirectory.put(3, EXTERNAL_SD_STORAGE);
    listEnvironmentVariableStoreSDCardRootDirectory.put(4, EXTERNAL_STORAGE);

    File externalStorageList[] = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
        externalStorageList = getContext().getExternalFilesDirs(null);
    }
    String directory = null;
    int size = listEnvironmentVariableStoreSDCardRootDirectory.size();
    for (int i = 0; i < size; i++) {
        if (externalStorageList != null && externalStorageList.length > 1 && externalStorageList[1] != null)
            directory = externalStorageList[1].getAbsolutePath();
        else
            directory = listEnvironmentVariableStoreSDCardRootDirectory.get(i);

        directory = canCreateFile(directory);
        if (directory != null && directory.length() != 0) {
            if (i == size - 1) {
                if (directory.contains(FLAG)) {
                    Log.e(getClass().getSimpleName(), "SD Card's directory: " + directory);
                    return directory;
                } else {
                    return null;
                }
            }
            Log.e(getClass().getSimpleName(), "SD Card's directory: " + directory);
            return directory;
        }
    }
    return null;
}

/**
 * Check if can create file on given directory. Use this enclose with method
 * {@link BeginScreenFragement#isRemovableSDCardAvailable()} to check sd
 * card is available on device or not.
 * 
 * @param directory
 * @return
 */
public String canCreateFile(String directory) {
    final String FILE_DIR = directory + File.separator + "hoang.txt";
    File tempFlie = null;
    try {
        tempFlie = new File(FILE_DIR);
        FileOutputStream fos = new FileOutputStream(tempFlie);
        fos.write(new byte[1024]);
        fos.flush();
        fos.close();
        Log.e(getClass().getSimpleName(), "Can write file on this directory: " + FILE_DIR);
    } catch (Exception e) {
        Log.e(getClass().getSimpleName(), "Write file error: " + e.getMessage());
        return null;
    } finally {
        if (tempFlie != null && tempFlie.exists() && tempFlie.isFile()) {
            // tempFlie.delete();
            tempFlie = null;
        }
    }
    return directory;
}

How can I uninstall an application using PowerShell?

One line of code:

get-package *notepad* |% { & $_.Meta.Attributes["UninstallString"]}

Is it possible to overwrite a function in PHP

Edit

To address comments that this answer doesn't directly address the original question. If you got here from a Google Search, start here

There is a function available called override_function that actually fits the bill. However, given that this function is part of The Advanced PHP Debugger extension, it's hard to make an argument that override_function() is intended for production use. Therefore, I would say "No", it is not possible to overwrite a function with the intent that the original questioner had in mind.

Original Answer

This is where you should take advantage of OOP, specifically polymorphism.

interface Fooable
{
    public function ihatefooexamples();
}

class Foo implements Fooable
{
    public function ihatefooexamples()
    {
        return "boo-foo!";
    }
}

class FooBar implements Fooable
{
    public function ihatefooexamples()
    {
        return "really boo-foo";
    }
}

$foo = new Foo();

if (10 == $_GET['foolevel']) {
    $foo = new FooBar();
}

echo $foo->ihatefooexamples();

NSURLErrorDomain error codes description

IN SWIFT 3. Here are the NSURLErrorDomain error codes description in a Swift 3 enum: (copied from answer above and converted what i can).

enum NSURLError: Int {
    case unknown = -1
    case cancelled = -999
    case badURL = -1000
    case timedOut = -1001
    case unsupportedURL = -1002
    case cannotFindHost = -1003
    case cannotConnectToHost = -1004
    case connectionLost = -1005
    case lookupFailed = -1006
    case HTTPTooManyRedirects = -1007
    case resourceUnavailable = -1008
    case notConnectedToInternet = -1009
    case redirectToNonExistentLocation = -1010
    case badServerResponse = -1011
    case userCancelledAuthentication = -1012
    case userAuthenticationRequired = -1013
    case zeroByteResource = -1014
    case cannotDecodeRawData = -1015
    case cannotDecodeContentData = -1016
    case cannotParseResponse = -1017
    //case NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022
    case fileDoesNotExist = -1100
    case fileIsDirectory = -1101
    case noPermissionsToReadFile = -1102
    //case NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) =   -1103

    // SSL errors
    case secureConnectionFailed = -1200
    case serverCertificateHasBadDate = -1201
    case serverCertificateUntrusted = -1202
    case serverCertificateHasUnknownRoot = -1203
    case serverCertificateNotYetValid = -1204
    case clientCertificateRejected = -1205
    case clientCertificateRequired = -1206
    case cannotLoadFromNetwork = -2000

    // Download and file I/O errors
    case cannotCreateFile = -3000
    case cannotOpenFile = -3001
    case cannotCloseFile = -3002
    case cannotWriteToFile = -3003
    case cannotRemoveFile = -3004
    case cannotMoveFile = -3005
    case downloadDecodingFailedMidStream = -3006
    case downloadDecodingFailedToComplete = -3007

    /*
     case NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) =         -1018
     case NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) =                    -1019
     case NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) =                  -1020
     case NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) =      -1021

     case NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995
     case NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996
     case NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997
     */
}

Direct link to URLError.Code in the Swift github repository, which contains the up to date list of error codes being used (github link).

HTML input time in 24 format

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <body>_x000D_
        Time: <input type="time" id="myTime" value="16:32:55">_x000D_
_x000D_
 <p>Click the button to get the time of the time field.</p>_x000D_
_x000D_
 <button onclick="myFunction()">Try it</button>_x000D_
_x000D_
 <p id="demo"></p>_x000D_
_x000D_
 <script>_x000D_
     function myFunction() {_x000D_
         var x = document.getElementById("myTime").value;_x000D_
         document.getElementById("demo").innerHTML = x;_x000D_
     }_x000D_
 </script>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

I found that by setting value field (not just what is given below) time input will be internally converted into the 24hr format.

Keras, how do I predict after I trained a model?

You must use the same Tokenizer you used to build your model!

Else this will give different vector to each word.

Then, I am using:

phrase = "not good"
tokens = myTokenizer.texts_to_matrix([phrase])

model.predict(np.array(tokens))

Generating all permutations of a given string

Java implementation without recursion

public Set<String> permutate(String s){
    Queue<String> permutations = new LinkedList<String>();
    Set<String> v = new HashSet<String>();
    permutations.add(s);

    while(permutations.size()!=0){
        String str = permutations.poll();
        if(!v.contains(str)){
            v.add(str);
            for(int i = 0;i<str.length();i++){
                String c = String.valueOf(str.charAt(i));
                permutations.add(str.substring(i+1) + c +  str.substring(0,i));
            }
        }
    }
    return v;
}

How to implement a Map with multiple keys?

Yet another solution is to use Google's Guava

import com.google.common.collect.Table;
import com.google.common.collect.HashBasedTable;

Table<String, String, Integer> table = HashBasedTable.create();

The usage is really simple:

String row = "a";
String column = "b";
int value = 1;

if (!table.contains(row, column)) {
    table.put(row, column, value);
}

System.out.println("value = " + table.get(row, column));

The method HashBasedTable.create() is basically doing something like this:

Table<String, String, Integer> table = Tables.newCustomTable(
        Maps.<String, Map<String, Integer>>newHashMap(),
        new Supplier<Map<String, Integer>>() {
    public Map<String, Integer> get() {
        return Maps.newHashMap();
    }
});

if you're trying to create some custom maps, you should go for the second option (as @Karatheodory suggests) otherwise you should be fine with the first one.

Best Practices for Custom Helpers in Laravel 5

Custom Classes in Laravel 5, the Easy Way

This answer is applicable to general custom classes within Laravel. For a more Blade-specific answer, see Custom Blade Directives in Laravel 5.

Step 1: Create your Helpers (or other custom class) file and give it a matching namespace. Write your class and method:

<?php // Code within app\Helpers\Helper.php

namespace App\Helpers;

class Helper
{
    public static function shout(string $string)
    {
        return strtoupper($string);
    }
}

Step 2: Create an alias:

<?php // Code within config/app.php

    'aliases' => [
     ...
        'Helper' => App\Helpers\Helper::class,
     ...

Step 3: Run composer dump-autoload in the project root

Step 4: Use it in your Blade template:

<!-- Code within resources/views/template.blade.php -->

{!! Helper::shout('this is how to use autoloading correctly!!') !!}

Extra Credit: Use this class anywhere in your Laravel app:

<?php // Code within app/Http/Controllers/SomeController.php

namespace App\Http\Controllers;

use Helper;

class SomeController extends Controller
{

    public function __construct()
    {
        Helper::shout('now i\'m using my helper class in a controller!!');
    }
    ...

Source: http://www.php-fig.org/psr/psr-4/

Why it works: https://github.com/laravel/framework/blob/master/src/Illuminate/Support/ClassLoader.php

Where autoloading originates from: http://php.net/manual/en/language.oop5.autoload.php

How do I return multiple values from a function?

Named tuples were added in 2.6 for this purpose. Also see os.stat for a similar builtin example.

>>> import collections
>>> Point = collections.namedtuple('Point', ['x', 'y'])
>>> p = Point(1, y=2)
>>> p.x, p.y
1 2
>>> p[0], p[1]
1 2

In recent versions of Python 3 (3.6+, I think), the new typing library got the NamedTuple class to make named tuples easier to create and more powerful. Inheriting from typing.NamedTuple lets you use docstrings, default values, and type annotations.

Example (From the docs):

class Employee(NamedTuple):  # inherit from typing.NamedTuple
    name: str
    id: int = 3  # default value

employee = Employee('Guido')
assert employee.id == 3

MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB

I experienced the same issue on an import of a data dump. Temporarily disabling the innodb strict mode solved my problem.

-- shows the acutal value of the variable
SHOW VARIABLES WHERE variable_name = 'innodb_strict_mode';

-- change the value (ON/OFF)
SET GLOBAL innodb_strict_mode=ON;

Singletons vs. Application Context in Android?

They're actually the same. There's one difference I can see. With Application class you can initialize your variables in Application.onCreate() and destroy them in Application.onTerminate(). With singleton you have to rely VM initializing and destroying statics.

Postgres: How to convert a json string to text?

An easy way of doing this:

SELECT  ('[' || to_json('Some "text"'::TEXT) || ']')::json ->> 0;

Just convert the json string into a json list

How to update array value javascript?

How about;

function keyValue(key, value){
    this.Key = key;
    this.Value = value;
};
keyValue.prototype.updateTo = function(newKey, newValue) {
    this.Key = newKey;
    this.Value = newValue;  
};

array[1].updateTo("xxx", "999");   

How to convert list data into json in java

JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = new JSONArray();

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

for(product cj:cities.getList()) {
    ls.add(cj);
    JSONObject formDetailsJson = new JSONObject();
    formDetailsJson.put("id", cj.id);
    formDetailsJson.put("name", cj.name);
    jsonArray.put(formDetailsJson);
}

responseDetailsJson.put("Cities", jsonArray);

return responseDetailsJson;

Replacing a character from a certain index

You can also Use below method if you have to replace string between specific index

def Replace_Substring_Between_Index(singleLine,stringToReplace='',startPos=0,endPos=1):
    try:
       singleLine = singleLine[:startPos]+stringToReplace+singleLine[endPos:]
    except Exception as e:
        exception="There is Exception at this step while calling replace_str_index method, Reason = " + str(e)
        BuiltIn.log_to_console(exception)
    return singleLine

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

what does "dead beef" mean?

It's a made up expression using only the letters A-F, often used when a recognisable hexadecimal number is required. Some systems use it for various purposes such as showing memory which has been freed and should not be referenced again. In a debugger this value showing up could be a sign that you have made an error. From Wikipedia:

0xDEADBEEF ("dead beef") is used by IBM RS/6000 systems, Mac OS on 32-bit PowerPC processors and the Commodore Amiga as a magic debug value. On Sun Microsystems' Solaris, it marks freed kernel memory. On OpenVMS running on Alpha processors, DEAD_BEEF can be seen by pressing CTRL-T.

The number 0xDEADBEEF is equal to the less recognisable decimal number 3735928559 (unsigned) or -559038737 (signed).

mssql '5 (Access is denied.)' error during restoring database

The fix for me was to go into Options when trying to Restore the database and change the path to the new path. Here is the screenshot

Python strptime() and timezones?

The datetime module documentation says:

Return a datetime corresponding to date_string, parsed according to format. This is equivalent to datetime(*(time.strptime(date_string, format)[0:6])).

See that [0:6]? That gets you (year, month, day, hour, minute, second). Nothing else. No mention of timezones.

Interestingly, [Win XP SP2, Python 2.6, 2.7] passing your example to time.strptime doesn't work but if you strip off the " %Z" and the " EST" it does work. Also using "UTC" or "GMT" instead of "EST" works. "PST" and "MEZ" don't work. Puzzling.

It's worth noting this has been updated as of version 3.2 and the same documentation now also states the following:

When the %z directive is provided to the strptime() method, an aware datetime object will be produced. The tzinfo of the result will be set to a timezone instance.

Note that this doesn't work with %Z, so the case is important. See the following example:

In [1]: from datetime import datetime

In [2]: start_time = datetime.strptime('2018-04-18-17-04-30-AEST','%Y-%m-%d-%H-%M-%S-%Z')

In [3]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
TZ NAME: None

In [4]: start_time = datetime.strptime('2018-04-18-17-04-30-+1000','%Y-%m-%d-%H-%M-%S-%z')

In [5]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
TZ NAME: UTC+10:00

How can I escape square brackets in a LIKE clause?

The ESCAPE keyword is used if you need to search for special characters like % and _, which are normally wild cards. If you specify ESCAPE, SQL will search literally for the characters % and _.

Here's a good article with some more examples

SELECT columns FROM table WHERE 
    column LIKE '%[[]SQL Server Driver]%' 

-- or 

SELECT columns FROM table WHERE 
    column LIKE '%\[SQL Server Driver]%' ESCAPE '\'

How to search in commit messages using command line?

git log --grep=<pattern>
    Limit the commits output to ones with log message that matches the 
    specified pattern (regular expression).

--git help log

How do I make flex box work in safari?

Demo -> https://jsfiddle.net/xdsuozxf/

Safari still requires the -webkit- prefix to use flexbox.

_x000D_
_x000D_
.row{_x000D_
    box-sizing: border-box;_x000D_
    display: -webkit-box;_x000D_
    display: -webkit-flex;_x000D_
    display: -ms-flexbox;_x000D_
    display: flex;_x000D_
    -webkit-flex: 0 1 auto;_x000D_
    -ms-flex: 0 1 auto;_x000D_
    flex: 0 1 auto;_x000D_
    -webkit-box-orient: horizontal;_x000D_
    -webkit-box-direction: normal;_x000D_
    -webkit-flex-direction: row;_x000D_
    -ms-flex-direction: row;_x000D_
    flex-direction: row;_x000D_
    -webkit-flex-wrap: wrap;_x000D_
    -ms-flex-wrap: wrap;_x000D_
    flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.col {_x000D_
    background:red;_x000D_
    border:1px solid black;_x000D_
_x000D_
    -webkit-flex: 1 ;-ms-flex: 1 ;flex: 1 ;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
      _x000D_
    <div class="content">_x000D_
        <div class="row">_x000D_
            <div class="col medium">_x000D_
                <div class="box">_x000D_
                    work on safari browser _x000D_
                </div>_x000D_
            </div>_x000D_
            <div class="col medium">_x000D_
                <div class="box">_x000D_
                    work on safari browser _x000D_
                    work on safari browser _x000D_
                    work on safari browser _x000D_
                    work on safari browser _x000D_
                    work on safari browser _x000D_
                </div>_x000D_
            </div>_x000D_
            <div class="col medium">_x000D_
                <div class="box">_x000D_
                    work on safari browser _x000D_
                    work on safari browser _x000D_
                    work on safari browser _x000D_
                    work on safari browser _x000D_
                    work on safari browser _x000D_
                    work on safari browser  work on safari browser _x000D_
                    work on safari browser _x000D_
                </div>_x000D_
            </div>_x000D_
        </div>   _x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I use regular expressions in bash scripts?

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi

Eslint: How to disable "unexpected console statement" in Node.js?

Create a .eslintrc.js in the directory of your file, and put the following contents in it:

module.exports = {
    rules: {
        'no-console': 'off',
    },
};

Easiest way to ignore blank lines when reading a file in Python

When a treatment of text must be done to just extract data from it, I always think first to the regexes, because:

  • as far as I know, regexes have been invented for that

  • iterating over lines appears clumsy to me: it essentially consists to search the newlines then to search the data to extract in each line; that makes two searches instead of a direct unique one with a regex

  • way of bringing regexes into play is easy; only the writing of a regex string to be compiled into a regex object is sometimes hard, but in this case the treatment with an iteration over lines will be complicated too

For the problem discussed here, a regex solution is fast and easy to write:

import re
names = re.findall('\S+',open(filename).read())

I compared the speeds of several solutions:

import re
from time import clock

A,AA,B1,B2,BS,reg = [],[],[],[],[],[]
D,Dsh,C1,C2 = [],[],[],[]
F1,F2,F3  = [],[],[]

def nonblank_lines(f):
    for l in f:
        line = l.rstrip()
        if line:  yield line

def short_nonblank_lines(f):
    for l in f:
        line = l[0:-1]
        if line:  yield line

for essays in xrange(50):

    te = clock()
    with open('raa.txt') as f:
        names_listA = [line.strip() for line in f if line.strip()] # Felix Kling
    A.append(clock()-te)

    te = clock()
    with open('raa.txt') as f:
        names_listAA = [line[0:-1] for line in f if line[0:-1]] # Felix Kling with line[0:-1]
    AA.append(clock()-te)

    #-------------------------------------------------------
    te = clock()
    with open('raa.txt') as f_in:
        namesB1 = [ name for name in (l.strip() for l in f_in) if name ] # aaronasterling without list()
    B1.append(clock()-te)

    te = clock()
    with open('raa.txt') as f_in:
        namesB2 = [ name for name in (l[0:-1] for l in f_in) if name ] # aaronasterling without list() and with line[0:-1]
    B2.append(clock()-te)

    te = clock()
    with open('raa.txt') as f_in:
        namesBS = [ name for name in f_in.read().splitlines() if name ] # a list comprehension with read().splitlines()
    BS.append(clock()-te)

    #-------------------------------------------------------
    te = clock()
    with open('raa.txt') as f:
        xreg = re.findall('\S+',f.read()) #  eyquem
    reg.append(clock()-te)

    #-------------------------------------------------------
    te = clock()
    with open('raa.txt') as f_in:
        linesC1 = list(line for line in (l.strip() for l in f_in) if line) # aaronasterling
    C1.append(clock()-te)

    te = clock()
    with open('raa.txt') as f_in:
        linesC2 = list(line for line in (l[0:-1] for l in f_in) if line) # aaronasterling  with line[0:-1]
    C2.append(clock()-te)

    #-------------------------------------------------------
    te = clock()
    with open('raa.txt') as f_in:
        yD = [ line for line in nonblank_lines(f_in)  ] # aaronasterling  update
    D.append(clock()-te)

    te = clock()
    with open('raa.txt') as f_in:
        yDsh = [ name for name in short_nonblank_lines(f_in)  ] # nonblank_lines with line[0:-1]
    Dsh.append(clock()-te)

    #-------------------------------------------------------
    te = clock()
    with open('raa.txt') as f_in:
        linesF1 = filter(None, (line.rstrip() for line in f_in)) # aaronasterling update 2
    F1.append(clock()-te)

    te = clock()
    with open('raa.txt') as f_in:
        linesF2 = filter(None, (line[0:-1] for line in f_in)) # aaronasterling update 2 with line[0:-1]
    F2.append(clock()-te)

    te = clock()
    with open('raa.txt') as f_in:
        linesF3 =  filter(None, f_in.read().splitlines()) # aaronasterling update 2 with read().splitlines()
    F3.append(clock()-te)


print 'names_listA == names_listAA==namesB1==namesB2==namesBS==xreg\n  is ',\
       names_listA == names_listAA==namesB1==namesB2==namesBS==xreg
print 'names_listA == yD==yDsh==linesC1==linesC2==linesF1==linesF2==linesF3\n  is ',\
       names_listA == yD==yDsh==linesC1==linesC2==linesF1==linesF2==linesF3,'\n\n\n'


def displ((fr,it,what)):  print fr + str( min(it) )[0:7] + '   ' + what

map(displ,(('* ', A,    '[line.strip() for line in f if line.strip()]               * Felix Kling\n'),

           ('  ', B1,   '    [name for name in (l.strip() for l in f_in) if name ]    aaronasterling without list()'),
           ('* ', C1,   'list(line for line in (l.strip() for l in f_in) if line)   * aaronasterling\n'),          

           ('* ', reg,  're.findall("\S+",f.read())                                 * eyquem\n'),

           ('* ', D,    '[ line for line in       nonblank_lines(f_in)  ]           * aaronasterling  update'),
           ('  ', Dsh,  '[ line for line in short_nonblank_lines(f_in)  ]             nonblank_lines with line[0:-1]\n'),

           ('* ', F1 ,  'filter(None, (line.rstrip() for line in f_in))             * aaronasterling update 2\n'),

           ('  ', B2,   '    [name for name in (l[0:-1]   for l in f_in) if name ]    aaronasterling without list() and with line[0:-1]'),
           ('  ', C2,   'list(line for line in (l[0:-1]   for l in f_in) if line)     aaronasterling  with line[0:-1]\n'),

           ('  ', AA,   '[line[0:-1] for line in f if line[0:-1]  ]                   Felix Kling with line[0:-1]\n'),

           ('  ', BS,   '[name for name in f_in.read().splitlines() if name ]        a list comprehension with read().splitlines()\n'),

           ('  ', F2 ,  'filter(None, (line[0:-1] for line in f_in))                  aaronasterling update 2 with line[0:-1]'),

           ('  ', F3 ,  'filter(None, f_in.read().splitlines()                        aaronasterling update 2 with read().splitlines()'))
    )

Solution with regex is straightforward and neat. Though, it isn't among the fastest ones. The solution of aaronasterling with filter() is surprisigly fast for me (I wasn't aware of this particular filter()'s speed) and times of optimized solutions go down until 27 % of the biggest time. I wonder what makes the miracle of the filter-splitlines association:

names_listA == names_listAA==namesB1==namesB2==namesBS==xreg
  is  True
names_listA == yD==yDsh==linesC1==linesC2==linesF1==linesF2==linesF3
  is  True 



* 0.08266   [line.strip() for line in f if line.strip()]               * Felix Kling

  0.07535       [name for name in (l.strip() for l in f_in) if name ]    aaronasterling without list()
* 0.06912   list(line for line in (l.strip() for l in f_in) if line)   * aaronasterling

* 0.06612   re.findall("\S+",f.read())                                 * eyquem

* 0.06486   [ line for line in       nonblank_lines(f_in)  ]           * aaronasterling  update
  0.05264   [ line for line in short_nonblank_lines(f_in)  ]             nonblank_lines with line[0:-1]

* 0.05451   filter(None, (line.rstrip() for line in f_in))             * aaronasterling update 2

  0.04689       [name for name in (l[0:-1]   for l in f_in) if name ]    aaronasterling without list() and with line[0:-1]
  0.04582   list(line for line in (l[0:-1]   for l in f_in) if line)     aaronasterling  with line[0:-1]

  0.04171   [line[0:-1] for line in f if line[0:-1]  ]                   Felix Kling with line[0:-1]

  0.03265   [name for name in f_in.read().splitlines() if name ]        a list comprehension with read().splitlines()

  0.03638   filter(None, (line[0:-1] for line in f_in))                  aaronasterling update 2 with line[0:-1]
  0.02198   filter(None, f_in.read().splitlines()                        aaronasterling update 2 with read().splitlines()

But this problem is particular, the most simple of all: only one name in each line. So the solutions are only games with lines, splitings and [0:-1] cuts.

On the contrary, regex doesn't matter with lines, it straightforwardly finds the desired data: I consider it is a more natural way of resolution, applying from the simplest to the more complex cases, and hence is often the way to be prefered in treatments of texts.

EDIT

I forgot to say that I use Python 2.7 and I measured the above times with a file containing 500 times the following chain

SMITH
JONES
WILLIAMS
TAYLOR
BROWN
DAVIES
EVANS
WILSON
THOMAS
JOHNSON

ROBERTS
ROBINSON
THOMPSON
WRIGHT
WALKER
WHITE
EDWARDS
HUGHES
GREEN
HALL

LEWIS
HARRIS
CLARKE
PATEL
JACKSON
WOOD
TURNER
MARTIN
COOPER
HILL

WARD
MORRIS
MOORE
CLARK
LEE
KING
BAKER
HARRISON
MORGAN
ALLEN

JAMES
SCOTT
PHILLIPS
WATSON
DAVIS
PARKER
PRICE
BENNETT
YOUNG
GRIFFITHS

MITCHELL
KELLY
COOK
CARTER
RICHARDSON
BAILEY
COLLINS
BELL
SHAW
MURPHY

MILLER
COX
RICHARDS
KHAN
MARSHALL
ANDERSON
SIMPSON
ELLIS
ADAMS
SINGH

BEGUM
WILKINSON
FOSTER
CHAPMAN
POWELL
WEBB
ROGERS
GRAY
MASON
ALI

HUNT
HUSSAIN
CAMPBELL
MATTHEWS
OWEN
PALMER
HOLMES
MILLS
BARNES
KNIGHT

LLOYD
BUTLER
RUSSELL
BARKER
FISHER
STEVENS
JENKINS
MURRAY
DIXON
HARVEY

How to initialize a JavaScript Date to a particular time zone

Building on the answers above, I am using this native one liner to convert the long timezone string to the three letter string:

var longTz = 'America/Los_Angeles';
var shortTz = new Date().
    toLocaleString("en", {timeZoneName: "short", timeZone: longTz}).
    split(' ').
    pop();

This will give PDT or PST depending on the date provided. In my particular use case, developing on Salesforce (Aura/Lightning), we are able to get the user timezone in the long format from the backend.

Link to reload current page

<a href="/">Clicking me refreshes the page</a>

<a href="?">Click Me To Reload the page</a>

How to print a linebreak in a python function?

>>> A = ['a1', 'a2', 'a3']
>>> B = ['b1', 'b2', 'b3']

>>> for x in A:
        for i in B:
            print ">" + x + "\n" + i

Outputs:

>a1
b1
>a1
b2
>a1
b3
>a2
b1
>a2
b2
>a2
b3
>a3
b1
>a3
b2
>a3
b3

Notice that you are using /n which is not correct!

CodeIgniter : Unable to load the requested file:

"Unable to load the requested file"

Can be also caused by access permissions under linux , make sure you set the correct read permissions for the directory "views/home"

Django: multiple models in one template using forms

I just was in about the same situation a day ago, and here are my 2 cents:

1) I found arguably the shortest and most concise demonstration of multiple model entry in single form here: http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/ .

In a nutshell: Make a form for each model, submit them both to template in a single <form>, using prefix keyarg and have the view handle validation. If there is dependency, just make sure you save the "parent" model before dependant, and use parent's ID for foreign key before commiting save of "child" model. The link has the demo.

2) Maybe formsets can be beaten into doing this, but as far as I delved in, formsets are primarily for entering multiples of the same model, which may be optionally tied to another model/models by foreign keys. However, there seem to be no default option for entering more than one model's data and that's not what formset seems to be meant for.

How can I check if an array contains a specific value in php?

Following is how you can do this:

<?php
$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('kitchen', $rooms)){
    echo 'this array contains kitchen';
}

Make sure that you search for kitchen and not Kitchen. This function is case sensitive. So, the below function simply won't work:

$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('KITCHEN', $rooms)){
    echo 'this array contains kitchen';
}

If you rather want a quick way to make this search case insensitive, have a look at the proposed solution in this reply: https://stackoverflow.com/a/30555568/8661779

Source: http://dwellupper.io/post/50/understanding-php-in-array-function-with-examples

How can I copy data from one column to another in the same table?

UPDATE table_name SET
    destination_column_name=orig_column_name
WHERE condition_if_necessary

How to check if an object is a list or tuple (but not string)?

Python 3 has this:

from typing import List

def isit(value):
    return isinstance(value, List)

isit([1, 2, 3])  # True
isit("test")  # False
isit({"Hello": "Mars"})  # False
isit((1, 2))  # False

So to check for both Lists and Tuples, it would be:

from typing import List, Tuple

def isit(value):
    return isinstance(value, List) or isinstance(value, Tuple)

How do I merge dictionaries together in Python?

Starting in Python 3.9, the operator | creates a new dictionary with the merged keys and values from two dictionaries:

# d1 = { 'a': 1, 'b': 2 }
# d2 = { 'b': 1, 'c': 3 }
d3 = d2 | d1
# d3: {'b': 2, 'c': 3, 'a': 1}

This:

Creates a new dictionary d3 with the merged keys and values of d2 and d1. The values of d1 take priority when d2 and d1 share keys.


Also note the |= operator which modifies d2 by merging d1 in, with priority on d1 values:

# d1 = { 'a': 1, 'b': 2 }
# d2 = { 'b': 1, 'c': 3 }
d2 |= d1
# d2: {'b': 2, 'c': 3, 'a': 1}

?

Changing Java Date one hour back

Or using the famous Joda Time library:

DateTime dateTime = new DateTime();
dateTime = dateTime.minusHours(1);
Date modifiedDate = dateTime.toDate();

Print the contents of a DIV

I think there is a better solution. Make your div to print cover the entire document, but only when it's printed:

@media print {
    .myDivToPrint {
        background-color: white;
        height: 100%;
        width: 100%;
        position: fixed;
        top: 0;
        left: 0;
        margin: 0;
        padding: 15px;
        font-size: 14px;
        line-height: 18px;
    }
}

How do I mount a host directory as a volume in docker compose

In docker-compose.yml you can use this format:

volumes:
    - host directory:container directory

according to their documentation

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

Your class MyClass creates a new MyClassToBeTested, instead of using your mock. My article on the Mockito wiki describes two ways of dealing with this.

What is the difference between re.search and re.match?

re.search searches for the pattern throughout the string, whereas re.match does not search the pattern; if it does not, it has no other choice than to match it at start of the string.

SqlServer: Login failed for user

I got the same error message when trying to connect to my SQL DB in Azure (using sql-cli). The simple solution was to escape the password with single quotes like this:

mssql -s server.database.windows.net -u user@server -p 'your_password' -d your_db -e

Python exit commands - why so many and when should each be used?

Let me give some information on them:

  1. quit() simply raises the SystemExit exception.

    Furthermore, if you print it, it will give a message:

    >>> print (quit)
    Use quit() or Ctrl-Z plus Return to exit
    >>>
    

    This functionality was included to help people who do not know Python. After all, one of the most likely things a newbie will try to exit Python is typing in quit.

    Nevertheless, quit should not be used in production code. This is because it only works if the site module is loaded. Instead, this function should only be used in the interpreter.

  2. exit() is an alias for quit (or vice-versa). They exist together simply to make Python more user-friendly.

    Furthermore, it too gives a message when printed:

    >>> print (exit)
    Use exit() or Ctrl-Z plus Return to exit
    >>>
    

    However, like quit, exit is considered bad to use in production code and should be reserved for use in the interpreter. This is because it too relies on the site module.

  3. sys.exit() also raises the SystemExit exception. This means that it is the same as quit and exit in that respect.

    Unlike those two however, sys.exit is considered good to use in production code. This is because the sys module will always be there.

  4. os._exit() exits the program without calling cleanup handlers, flushing stdio buffers, etc. Thus, it is not a standard way to exit and should only be used in special cases. The most common of these is in the child process(es) created by os.fork.

    Note that, of the four methods given, only this one is unique in what it does.

Summed up, all four methods exit the program. However, the first two are considered bad to use in production code and the last is a non-standard, dirty way that is only used in special scenarios. So, if you want to exit a program normally, go with the third method: sys.exit.


Or, even better in my opinion, you can just do directly what sys.exit does behind the scenes and run:

raise SystemExit

This way, you do not need to import sys first.

However, this choice is simply one on style and is purely up to you.

Why does an SSH remote command get fewer environment variables then when run manually?

How about sourcing the profile before running the command?

ssh user@host "source /etc/profile; /path/script.sh"

You might find it best to change that to ~/.bash_profile, ~/.bashrc, or whatever.

(As here (linuxquestions.org))

XMLHttpRequest (Ajax) Error

So there might be a few things wrong here.

First start by reading how to use XMLHttpRequest.open() because there's a third optional parameter for specifying whether to make an asynchronous request, defaulting to true. That means you're making an asynchronous request and need to specify a callback function before you do the send(). Here's an example from MDN:

var oXHR = new XMLHttpRequest();

oXHR.open("GET", "http://www.mozilla.org/", true);

oXHR.onreadystatechange = function (oEvent) {
    if (oXHR.readyState === 4) {
        if (oXHR.status === 200) {
          console.log(oXHR.responseText)
        } else {
           console.log("Error", oXHR.statusText);
        }
    }
};

oXHR.send(null);

Second, since you're getting a 101 error, you might use the wrong URL. So make sure that the URL you're making the request with is correct. Also, make sure that your server is capable of serving your quiz.xml file.

You'll probably have to debug by simplifying/narrowing down where the problem is. So I'd start by making an easy synchronous request so you don't have to worry about the callback function. So here's another example from MDN for making a synchronous request:

var request = new XMLHttpRequest();
request.open('GET', 'file:///home/user/file.json', false); 
request.send(null);

if (request.status == 0)
    console.log(request.responseText);

Also, if you're just starting out with Javascript, you could refer to MDN for Javascript API documentation/examples/tutorials.

How to determine the screen width in terms of dp or dip at runtime in Android?

If you just want to know about your screen width, you can just search for "smallest screen width" in your developer options. You can even edit it.

Get week day name from a given month, day and year individually in SQL Server

select to_char(sysdate,'DAY') from dual; It's work try it

How do you use "git --bare init" repository?

The general practice is to have the central repository to which you push as a bare repo.

If you have SVN background, you can relate an SVN repo to a Git bare repo. It doesn't have the files in the repo in the original form. Whereas your local repo will have the files that form your "code" in addition.

You need to add a remote to the bare repo from your local repo and push your "code" to it.

It will be something like:

git remote add central <url> # url will be ssh based for you
git push --all central

What do parentheses surrounding an object/function/class declaration mean?

A few considerations on the subject:

  • The parenthesis:

    The browser (engine/parser) associates the keyword function with

    [optional name]([optional parameters]){...code...}
    

    So in an expression like function(){}() the last parenthesis makes no sense.

    Now think at

    name=function(){} ; name() !?
    

Yes, the first pair of parenthesis force the anonymous function to turn into a variable (stored expression) and the second launches evaluation/execution, so ( function(){} )() makes sense.

  • The utility: ?

    1. For executing some code on load and isolate the used variables from the rest of the page especially when name conflicts are possible;

    2. Replace eval("string") with

      (new Function("string"))()

    3. Wrap long code for " =?: " operator like:

      result = exp_to_test ? (function(){... long_code ...})() : (function(){...})();

Installing Python 3 on RHEL

Full working 36 when SCL is not available (based on Joys input)

yum install wget –y
wget https://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/e/epel-release-7-11.noarch.rpm
rpm –ivh epel-*.rpm
yum install python36

sudo yum install python34-setuptools
sudo mkdir /usr/local/lib/python3.6
sudo mkdir /usr/local/lib/python3.6/site-packages

sudo easy_install-3.6 pip

Finally activate the environment...

pyvenv-3.6 py3
source py3/bin/activate

Then python3

Object reference not set to an instance of an object.

strSearch in this case is probably null (not simply empty).

Try using

String.IsNullOrEmpty(strSearch)

if you are just trying to determine if the string doesn't have any contents.

The PowerShell -and conditional operator

The code that you have shown will do what you want iff those properties equal "" when they are not filled in. If they equal $null when not filled in for example, then they will not equal "". Here is an example to prove the point that what you have will work for "":

$foo = 1
$bar = 1
$foo -eq 1 -and $bar -eq 1
True
$foo -eq 1 -and $bar -eq 2
False

How to format current time using a yyyyMMddHHmmss format?

import("time")

layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)
if err != nil {
    fmt.Println(err)
}
fmt.Println(t)

gives:

>> 2014-11-12 11:45:26.371 +0000 UTC

Reading in double values with scanf in c

As far as i know %d means decadic which is number without decimal point. if you want to load double value, use %lf conversion (long float). for printf your values are wrong for same reason, %d is used only for integer (and possibly chars if you know what you are doing) numbers.

Example:

double a,b;
printf("--------\n"); //seperate lines
scanf("%lf",&a);
printf("--------\n"); 
scanf("%lf",&b);
printf("%lf %lf",a,b);

laravel Unable to prepare route ... for serialization. Uses Closure

check that your web.php file has this extension

use Illuminate\Support\Facades\Route;

my problem gone fixed by this way.

Load a Bootstrap popover content with AJAX. Is this possible?

Here is my solution which works fine with ajax loaded content too.

/*
 * popover handler assigned document (or 'body') 
 * triggered on hover, show content from data-content or 
 * ajax loaded from url by using data-remotecontent attribute
 */
$(document).popover({
    selector: 'a.preview',
    placement: get_popover_placement,
    content: get_popover_content,
    html: true,
    trigger: 'hover'
});

function get_popover_content() {
    if ($(this).attr('data-remotecontent')) {
        // using remote content, url in $(this).attr('data-remotecontent')
        $(this).addClass("loading");
        var content = $.ajax({
            url: $(this).attr('data-remotecontent'),
            type: "GET",
            data: $(this).serialize(),
            dataType: "html",
            async: false,
            success: function() {
                // just get the response
            },
            error: function() {
                // nothing
            }
        }).responseText;
        var container = $(this).attr('data-rel');
        $(this).removeClass("loading");
        if (typeof container !== 'undefined') {
            // show a specific element such as "#mydetails"
            return $(content).find(container);
        }
        // show the whole page
        return content;
    }
    // show standard popover content
    return $(this).attr('data-content');
}

function get_popover_placement(pop, el) {
    if ($(el).attr('data-placement')) {
        return $(el).attr('data-placement');
    }
    // find out the best placement
    // ... cut ...
    return 'left';
}

How can I get the full/absolute URL (with domain) in Django?

request.get_host() will give you the domain.

How do I parse a URL into hostname and path in javascript?

a simple hack with the first answer

var getLocation = function(href=window.location.href) {
    var l = document.createElement("a");
    l.href = href;
    return l;
};

this can used even without argument to figure out the current hostname getLocation().hostname will give current hostname

What is SYSNAME data type in SQL Server?

Another use case is when using the SQL Server 2016+ functionality of AT TIME ZONE

The below statement will return a date converted to GMT

SELECT 
CONVERT(DATETIME, SWITCHOFFSET([ColumnA], DATEPART(TZOFFSET, [ColumnA] AT TIME ZONE 'GMT Standard Time')))

If you want to pass the time zone as a variable, say:

SELECT 
CONVERT(DATETIME, SWITCHOFFSET([ColumnA], DATEPART(TZOFFSET, [ColumnA] AT TIME ZONE @TimeZone)))

then that variable needs to be of the type sysname (declaring it as varchar will cause an error).

Difference between static STATIC_URL and STATIC_ROOT on Django

All the answers above are helpful but none solved my issue. In my production file, my STATIC_URL was https://<URL>/static and I used the same STATIC_URL in my dev settings.py file.

This causes a silent failure in django/conf/urls/static.py.

The test elif not settings.DEBUG or '://' in prefix: picks up the '//' in the URL and does not add the static URL pattern, causing no static files to be found.

It would be thoughtful if Django spit out an error message stating you can't use a http(s):// with DEBUG = True

I had to change STATIC_URL to be '/static/'

REST API - Bulk Create or Update in single request

PUT ing

PUT /binders/{id}/docs Create or update, and relate a single document to a binder

e.g.:

PUT /binders/1/docs HTTP/1.1
{
  "docNumber" : 1
}

PATCH ing

PATCH /docs Create docs if they do not exist and relate them to binders

e.g.:

PATCH /docs HTTP/1.1
[
    { "op" : "add", "path" : "/binder/1/docs", "value" : { "doc_number" : 1 } },
    { "op" : "add", "path" : "/binder/8/docs", "value" : { "doc_number" : 8 } },
    { "op" : "add", "path" : "/binder/3/docs", "value" : { "doc_number" : 6 } }
] 

I'll include additional insights later, but in the meantime if you want to, have a look at RFC 5789, RFC 6902 and William Durand's Please. Don't Patch Like an Idiot blog entry.

What is the difference between POST and GET?

With POST you can also do multipart mime encoding which means you can attach files as well. Also if you are using post variables across navigation of pages, the user will get a warning asking if they want to resubmit the post parameter. Typically they look the same in an HTTP request, but you should just stick to POST if you need to "POST" something TO a server and "GET" if you need to GET something FROM a server as that's the way they were intended.

How to remove text from a string?

I was used to the C# (Sharp) String.Remove method. In Javascript, there is no remove function for string, but there is substr function. You can use the substr function once or twice to remove characters from string. You can make the following function to remove characters at start index to the end of string, just like the c# method first overload String.Remove(int startIndex):

function Remove(str, startIndex) {
    return str.substr(0, startIndex);
}

and/or you also can make the following function to remove characters at start index and count, just like the c# method second overload String.Remove(int startIndex, int count):

function Remove(str, startIndex, count) {
    return str.substr(0, startIndex) + str.substr(startIndex + count);
}

and then you can use these two functions or one of them for your needs!

Example:

alert(Remove("data-123", 0, 5));

Output: 123

Attaching click to anchor tag in angular

I have encountered this issue in Angular 5 which still followed the link. The solution was to have the function return false in order to prevent the page being refreshed:

html

<a href="" (click)="openChangePasswordForm()">Change expired password</a>

ts

openChangePasswordForm(): boolean {
  console.log("openChangePasswordForm called!");
  return false;
}

sql query distinct with Row_Number

How about something like

;WITH DistinctVals AS (
        SELECT  distinct id 
        FROM    table 
        where   fid = 64
    )
SELECT  id,
        ROW_NUMBER() OVER (ORDER BY  id) AS RowNum
FROM    DistinctVals

SQL Fiddle DEMO

You could also try

SELECT distinct id, DENSE_RANK() OVER (ORDER BY  id) AS RowNum
FROM @mytable
where fid = 64

SQL Fiddle DEMO

javascript multiple OR conditions in IF statement

You want to execute code where the id is not (1 or 2 or 3), but the OR operator does not distribute over id. The only way to say what you want is to say

the id is not 1, and the id is not 2, and the id is not 3.

which translates to

if (id !== 1 && id !== 2 && id !== 3)

or alternatively for something more pythonesque:

if (!(id in [,1,2,3]))

Auto generate function documentation in Visual Studio

GhostDoc!

Right-click on the function, select "Document this" and

private bool FindTheFoo(int numberOfFoos)

becomes

/// <summary>
/// Finds the foo.
/// </summary>
/// <param name="numberOfFoos">The number of foos.</param>
/// <returns></returns>
private bool FindTheFoo(int numberOfFoos)

(yes, it is all autogenerated).

It has support for C#, VB.NET and C/C++. It is per default mapped to Ctrl+Shift+D.

Remember: you should add information beyond the method signature to the documentation. Don't just stop with the autogenerated documentation. The value of a tool like this is that it automatically generates the documentation that can be extracted from the method signature, so any information you add should be new information.

That being said, I personally prefer when methods are totally selfdocumenting, but sometimes you will have coding-standards that mandate outside documentation, and then a tool like this will save you a lot of braindead typing.

Is it possible to send a variable number of arguments to a JavaScript function?

This is a sample program for calculating sum of integers for variable arguments and array on integers. Hope this helps.

var CalculateSum = function(){
    calculateSumService.apply( null, arguments );
}

var calculateSumService = function(){
    var sum = 0;

    if( arguments.length === 1){
        var args = arguments[0];

        for(var i = 0;i<args.length; i++){
           sum += args[i]; 
        }
    }else{
        for(var i = 0;i<arguments.length; i++){
           sum += arguments[i]; 
        }        
    }

     alert(sum);

}


//Sample method call

// CalculateSum(10,20,30);         

// CalculateSum([10,20,30,40,50]);

// CalculateSum(10,20);

How to disable textbox from editing?

As mentioned above, you can change the property of the textbox "Read Only" to "True" from the properties window.

enter image description here

Access parent URL from iframe

I know his is super old but it blows my mind no one recommended just passing cookies from one domain to the other. As you are using subdomains you can share cookies from a base domain to all subdomains just by setting cookies to the url .basedomain.com

Then you can share whatever data you need through the cookies.

How to terminate a window in tmux?

Kent's response fully answered your question, however if you are looking to change tmux's configuration to be similar to GNU Screen, here's a tmux.conf that I've used to accomplish this:

# Prefix key
set -g prefix C-a
unbind C-b
bind C-a send-prefix

# Keys
bind k confirm kill-window
bind K confirm kill-server
bind % split-window -h
bind : split-window -v
bind < resize-pane -L 1
bind > resize-pane -R 1
bind - resize-pane -D 1
bind + resize-pane -U 1
bind . command-prompt
bind a last-window
bind space command-prompt -p index "select-window"
bind r source-file ~/.tmux.conf

# Options
set -g bell-action none
set -g set-titles on
set -g set-titles-string "tmux (#I:#W)"
set -g base-index 1
set -g status-left ""
set -g status-left-attr bold
set -g status-right "tmux"
set -g pane-active-border-bg black
set -g pane-active-border-fg black
set -g default-terminal "screen-256color"

# Window options
setw -g monitor-activity off
setw -g automatic-rename off

# Colors
setw -g window-status-current-fg colour191
set -g status-bg default
set -g status-fg white
set -g message-bg default
set -g message-fg colour191

How to change ReactJS styles dynamically?

Ok, finally found the solution.

Probably due to lack of experience with ReactJS and web development...

    var Task = React.createClass({
    render: function() {
      var percentage = this.props.children + '%';
      ....
        <div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
      ...

I created the percentage variable outside in the render function.

How can I execute a python script from an html button?

Best way is to Use a Python Web Frame Work you can choose Django/Flask. I will suggest you to Use Django because it's more powerful. Here is Step by guide to get complete your task :

pip install django
django-admin createproject buttonpython

then you have to create a file name views.py in buttonpython directory.

write below code in views.py:

from django.http import HttpResponse

def sample(request):
    #your python script code
    output=code output
    return HttpResponse(output)

Once done navigate to urls.py and add this stanza

from . import views

path('', include('blog.urls')),

Now go to parent directory and execute manage.py

python manage.py runserver 127.0.0.1:8001

Step by Step Guide in Detail: Run Python script on clicking HTML button

In Python, how do you convert seconds since epoch to a `datetime` object?

datetime.datetime.fromtimestamp will do, if you know the time zone, you could produce the same output as with time.gmtime

>>> datetime.datetime.fromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 11, 19, 54)

or

>>> datetime.datetime.utcfromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 10, 19, 54)

HTTP Basic Authentication credentials passed in URL and encryption

Will the username and password be automatically SSL encrypted? Is the same true for GETs and POSTs

Yes, yes yes.

The entire communication (save for the DNS lookup if the IP for the hostname isn't already cached) is encrypted when SSL is in use.

How can I remove a character from a string using JavaScript?

If it is always the 4th char in yourString you can try:

yourString.replace(/^(.{4})(r)/, function($1, $2) { return $2; });

Submitting a form on 'Enter' with jQuery?

Just adding for easy implementation. You can simply make a form and then make the submit button hidden:

For example:

<form action="submit.php" method="post">
Name : <input type="text" name="test">
<input type="submit" style="display: none;">
</form>

How to search all loaded scripts in Chrome Developer Tools?

Your text may be located in the networking response.There is also a search tool in the Network tab, and you may try it.

What you want to search for may stay either in DOM or in memory. If it is not in DOM, well, it may be in memory, because you have just see it in your computer screen anyway. The text you search for may be loaded either from scripts in the initial DOM or from response in the later request.

import module from string variable

The __import__ function can be a bit hard to understand.

If you change

i = __import__('matplotlib.text')

to

i = __import__('matplotlib.text', fromlist=[''])

then i will refer to matplotlib.text.

In Python 2.7 and Python 3.1 or later, you can use importlib:

import importlib

i = importlib.import_module("matplotlib.text")

Some notes

  • If you're trying to import something from a sub-folder e.g. ./feature/email.py, the code will look like importlib.import_module("feature.email")

  • You can't import anything if there is no __init__.py in the folder with file you are trying to import

Virtualhost For Wildcard Subdomain and Static Subdomain

<VirtualHost *:80>
  DocumentRoot /var/www/app1
  ServerName app1.example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/example
  ServerName example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/wildcard
  ServerName other.example.com
  ServerAlias *.example.com
</VirtualHost>

Should work. The first entry will become the default if you don't get an explicit match. So if you had app.otherexample.com point to it, it would be caught be app1.example.com.

How to read request body in an asp.net core webapi controller?

I also wanted to read the Request.Body without automatically map it to some action parameter model. Tested a lot of different ways before solved this. And I didn´t find any working solution described here. This solution is currently based on the .NET Core 3.0 framework.

reader.readToEnd() seamed like a simple way, even though it compiled, it throwed an runtime exception required me to use async call. So instead I used ReadToEndAsync(), however it worked sometimes, and sometimes not. Giving me errors like, cannot read after stream is closed. The problem is that we cannot guarantee that it will return the result in the same thread (even if we use the await). So we need some kind of callback. This solution worked for me.

[Route("[controller]/[action]")]
public class MyController : ControllerBase
{

    // ...

    [HttpPost]
    public async void TheAction()
    {
        try
        {
            HttpContext.Request.EnableBuffering();
            Request.Body.Position = 0;
            using (StreamReader stream = new StreamReader(HttpContext.Request.Body))
            {
                var task = stream
                    .ReadToEndAsync()
                    .ContinueWith(t => {
                        var res = t.Result;
                        // TODO: Handle the post result!
                    });

                // await processing of the result
                task.Wait();
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to handle post!");
        }
    }

File inside jar is not visible for spring

In the spring jar package, I use new ClassPathResource(filename).getFile(), which throws the exception:

cannot be resolved to absolute file path because it does not reside in the file system: jar

But using new ClassPathResource(filename).getInputStream() will solve this problem. The reason is that the configuration file in the jar does not exist in the operating system's file tree,so must use getInputStream().

Unloading classes in java?

If you're live watching if unloading class worked in JConsole or something, try also adding java.lang.System.gc() at the end of your class unloading logic. It explicitly triggers Garbage Collector.

How to find available directory objects on Oracle 11g system?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

Calculate business days

I had this same need i started with bobbin's first example and ended up with this

  function add_business_days($startdate,$buisnessdays,$holidays=array(),$dateformat){
    $enddate = strtotime($startdate);
    $day = date('N',$enddate);
    while($buisnessdays > 1){
        $enddate = strtotime(date('Y-m-d',$enddate).' +1 day');
        $day = date('N',$enddate);
        if($day < 6 && !in_array($enddate,$holidays))$buisnessdays--;
    }
    return date($dateformat,$enddate);
  }

hth someone

Hamcrest compare collections

List<Long> actual = Arrays.asList(1L, 2L);
List<Long> expected = Arrays.asList(2L, 1L);
assertThat(actual, containsInAnyOrder(expected.toArray()));

Shorter version of @Joe's answer without redundant parameters.

Prevent multiple instances of a given app in .NET?

Hanselman has a post on using the WinFormsApplicationBase class from the Microsoft.VisualBasic assembly to do this.

How can I hide a TD tag using inline JavaScript or CSS?

You can simply hide the <td> tag content by just including a style attribute: style = "display:none"

For e.g

<td style = "display:none" >
<p> I'm invisible </p>
</td>

Limit text length to n lines using CSS

Currently you can't, but in future you will be able to use text-overflow:ellipis-lastline. Currently it's available with vendor prefix in Opera 10.60+: example

android pick images from gallery

For only pick from local add this :

        i.putExtra(Intent.EXTRA_LOCAL_ONLY,true)

And this working nice :

    val i = Intent(Intent.ACTION_GET_CONTENT,MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
    i.type = "image/*"
    i.putExtra(Intent.EXTRA_LOCAL_ONLY,true)
    startActivityForResult(Intent.createChooser(i,"Select Photo"),pickImageRequestCode)

What does random.sample() method in python do?

random.sample() also works on text

example:

> text = open("textfile.txt").read() 

> random.sample(text, 5)

> ['f', 's', 'y', 'v', '\n']

\n is also seen as a character so that can also be returned

you could use random.sample() to return random words from a text file if you first use the split method

example:

> words = text.split()

> random.sample(words, 5)

> ['the', 'and', 'a', 'her', 'of']

Sending and receiving data over a network using TcpClient

I've developed a dotnet library that might come in useful. I have fixed the problem of never getting all of the data if it exceeds the buffer, which many posts have discounted. Still some problems with the solution but works descently well https://github.com/NicholasLKSharp/DotNet-TCP-Communication

Chrome Dev Tools - Modify javascript and reload

I know it's not the asnwer to the precise question (Chrome Developer Tools) but I'm using this workaround with success: http://www.telerik.com/fiddler

(pretty sure some of the web devs already know about this tool)

  1. Save the file locally
  2. Edit as required
  3. Profit!

enter image description here

Full docs: http://docs.telerik.com/fiddler/KnowledgeBase/AutoResponder

PS. I would rather have it implemented in Chrome as a flag preserve after reload, cannot do this now, forums and discussion groups blocked on corporate network :)

Google API authentication: Not valid origin for the client

For me - I just went here:

https://console.developers.google.com/apis/credentials

Then chose the right project; then choose the credential with the same ID shown in your console error message. When editing the credentials you can add multiple origins to the white list.

How do I use $rootScope in Angular to store variables?

Variables set at the root-scope are available to the controller scope via prototypical inheritance.

Here is a modified version of @Nitish's demo that shows the relationship a bit clearer: http://jsfiddle.net/TmPk5/6/

Notice that the rootScope's variable is set when the module initializes, and then each of the inherited scope's get their own copy which can be set independently (the change function). Also, the rootScope's value can be updated too (the changeRs function in myCtrl2)

angular.module('myApp', [])
.run(function($rootScope) {
    $rootScope.test = new Date();
})
.controller('myCtrl', function($scope, $rootScope) {
  $scope.change = function() {
        $scope.test = new Date();
    };

    $scope.getOrig = function() {
        return $rootScope.test;
    };
})
.controller('myCtrl2', function($scope, $rootScope) {
    $scope.change = function() {
        $scope.test = new Date();
    };

    $scope.changeRs = function() {
        $rootScope.test = new Date();
    };

    $scope.getOrig = function() {
        return $rootScope.test;
    };
});

git pull fails "unable to resolve reference" "unable to update local ref"

 # remove the reference file of the branch "lost"
 rm -fv ./.git/refs/remotes/origin/feature/v1.6.9-api-token-bot-reader

 # get all the branches from the master
 git fetch --all

 # git will "know" how-to handle the issue from now on
 #     From github.com:futurice/senzoit-www-server
 # * [new branch]      feature/v1.6.9-api-token-bot-reader ->
 # origin/feature/v1.6.9-api-token-bot-reader

 # and push your local changes
 git push

How do I make a new line in swift

You can do this

textView.text = "Name: \(string1) \n" + "Phone Number: \(string2)"

The output will be

Name: output of string1 Phone Number: output of string2

Importing data from a JSON file into R

jsonlite will import the JSON into a data frame. It can optionally flatten nested objects. Nested arrays will be data frames.

> library(jsonlite)
> winners <- fromJSON("winners.json", flatten=TRUE)
> colnames(winners)
[1] "winner" "votes" "startPrice" "lastVote.timestamp" "lastVote.user.name" "lastVote.user.user_id"
> winners[,c("winner","startPrice","lastVote.user.name")]
    winner startPrice lastVote.user.name
1 68694999          0              Lamur
> winners[,c("votes")]
[[1]]
                            ts user.name user.user_id
1 Thu Mar 25 03:13:01 UTC 2010     Lamur     68694999
2 Thu Mar 25 03:13:08 UTC 2010     Lamur     68694999

Java difference between FileWriter and BufferedWriter

You are right. Here is how write() method of BufferedWriter looks:

public void write(int c) throws IOException {
    synchronized (lock) {
        ensureOpen();
        if (nextChar >= nChars)
            flushBuffer();
        cb[nextChar++] = (char) c;
    }
}

As you can see it indeed checks whether the buffer is full (if (nextChar >= nChars)) and flushes the buffer. Then it adds new character to buffer (cb[nextChar++] = (char) c;).

Get Value of a Edit Text field

By using getText():

Button   mButton;
EditText mEdit;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mButton = (Button)findViewById(R.id.button);
    mEdit   = (EditText)findViewById(R.id.edittext);

    mButton.setOnClickListener(
        new View.OnClickListener()
        {
            public void onClick(View view)
            {
                Log.v("EditText", mEdit.getText().toString());
            }
        });
}

Compilation error - missing zlib.h

I also had the same problem. Then I installed the zlib, still the problem remained the same. Then I added the following lines in my .bashrc and it worked. You should replace the path with your zlib installation path. (I didn't have root privileges).

export PATH =$PATH:$HOME/Softwares/library/Zlib/zlib-1.2.11/
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/Softwares/library/Zlib/zlib-1.2.11/lib/
export LIBRARY_PATH=$LIBRARY_PATH:$HOME/Softwares/library/Zlib/zlib-1.2.11/lib/
export C_INCLUDE_PATH=$HOME/Softwares/library/Zlib/zlib-1.2.11/include/
export CPLUS_INCLUDE_PATH=$HOME/Softwares/library/Zlib/zlib-1.2.11/include/
export PKG_CONFIG_PATH=$HOME/Softwares/library/Zlib/zlib-1.2.11/lib/pkgconfig

Simple Android RecyclerView example

To get started , just to view something in Recycler view

recycler view adapter can be something like this.

class CustomAdapter: RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
    var data =  listOf<String>()
        set(value) {
            field = value
            notifyDataSetChanged()
        }
    override fun getItemCount() =data.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.txt.text= data[position]
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.item_view, parent, false)
        )
    }


    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
        val txt: TextView = itemView.findViewById(R.id.item_text_view)
    }
}

and to attach the adapter to the recycler view and to attach data to adapter

val view = findViewById<RecyclerView>(R.id.recycler_view)                                              
val adapter = CustomAdapter()                                                                          
val data = listOf("text1", "text2", "text3")
adapter.data = data                                                                             
view.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
view.adapter = adapter       
            

Undefined index error PHP

Try:

<?php

if (isset($_POST['name'])) {
    $name = $_POST['name'];
}

if (isset($_POST['price'])) {
    $price = $_POST['price'];
}

if (isset($_POST['description'])) {
    $description = $_POST['description'];
}

?>

How do I programmatically click a link with javascript?

Instead of clicking, can you forward to the URL that the click would go to using Javascript?

Maybe you could put something in the body onLoad to go where you want.

How do I use an INSERT statement's OUTPUT clause to get the identity value?

You can either have the newly inserted ID being output to the SSMS console like this:

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar() (instead of .ExecuteNonQuery()) to read the resulting ID back.

Or if you need to capture the newly inserted ID inside T-SQL (e.g. for later further processing), you need to create a table variable:

DECLARE @OutputTbl TABLE (ID INT)

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

This way, you can put multiple values into @OutputTbl and do further processing on those. You could also use a "regular" temporary table (#temp) or even a "real" persistent table as your "output target" here.

What is The difference between ListBox and ListView

A ListView let you define a set of views for it and gives you a native way (WPF binding support) to control the display of ListView by using defined views.

Example:

XAML

<ListView ItemsSource="{Binding list}" Name="listv" MouseEnter="listv_MouseEnter" MouseLeave="listv_MouseLeave">
        <ListView.Resources>
            <GridView x:Key="one">
                <GridViewColumn Header="ID" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding id}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="Name" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding name}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
            <GridView x:Key="two">                    
                <GridViewColumn Header="Name" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding name}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.Resources>
        <ListView.Style>
            <Style TargetType="ListView">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ViewType}" Value="1">
                        <Setter Property="View" Value="{StaticResource one}" />
                    </DataTrigger>
                </Style.Triggers>
                <Setter Property="View" Value="{StaticResource two}" />
            </Style>
        </ListView.Style>  

Code Behind:

private int viewType;

public int ViewType
{
    get { return viewType; }
    set 
    { 
        viewType = value;
        UpdateProperty("ViewType");
    }
}        

private void listv_MouseEnter(object sender, MouseEventArgs e)
{
    ViewType = 1;
}

private void listv_MouseLeave(object sender, MouseEventArgs e)
{
    ViewType = 2;
}

OUTPUT:

Normal View: View 2 in above XAML

Normal

MouseOver View: View 1 in above XAML

Mouse Over

If you try to achieve above in a ListBox, probably you'll end up writing a lot more code forControlTempalate/ItemTemplate of ListBox.

How to rename files and folder in Amazon S3?

aws s3 cp s3://source_folder/ s3://destination_folder/ --recursive
aws s3 rm s3://source_folder --recursive

Where is the default log location for SharePoint/MOSS?

SharePoint uses a lot of different logging mechanisms. Most importantly you can configure the location of the logs through Central Admin. To give you an understanding of the logs involved, here is a quote from http://raiumair.wordpress.com/2007/06/19/quick-a-to-z-of-sharepoint-logs/

All file based logs can be read by text editors and can be parsed by using popular log parsing tools (Log Parser 2.2 from Microsoft or Funnel Web). It will also be a good idea to read the IIS Logs which are generally saved at (System Drive):\WINDOWS\system32\LogFiles

a) Diagnostics Logs

· Event Throttling Logs – These end up going to the Windows Event Log and can be viewed in the Event Viewer. They show Errors and Warnings.

· Trace Logs – These show detailed line by line tracing infomration emitted during a web request or service execution. They end up being stored at a known location on the front-end server. Default Location: (System Drive):\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\LOGS\

b) Audit Logs - They end up in the associated Content Database tables and can be viewed at Site Collection Level as well as Site Level using the web browser. WSS 3.0 and MOSS 2007 use different pages to show Audit Log Reports.

c) Usage Logs – They get stored locally on the front-end servers and get processed both locally and at farm level via SSP (this is based on the setup as I understand the results from the local processing are merged by SSP) and can be viewed at both the Site Level and Site Collection Level. Default Location: (System Drive):\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\Logs

d) Search\Query Logs – These are saved in the associated SSP database but can be viewed at SSP level via the Web Browser and in MOSS at Site Collection Level by going to the settings page.

e) Information Management Logs – Stored in the associated Content Database and can be can be viewed at the Site Collection Level.

f) Content and Structure Logs – This option is only available after one enables the publication feature. This store is saved in the Content Database associated with the Site Collection and can be viewed at Site Collection level by going to the settings page.

"code ." Not working in Command Line for Visual Studio Code on OSX/Mac

If you have trouble using the Command Palette solution, you can manually add VS Code to the $PATH environment variable when your terminal starts:

cat << EOF >> ~/.bash_profile
# Add Visual Studio Code (code)
export PATH="$PATH:/Applications/Visual Studio 
Code.app/Contents/Resources/app/bin"
EOF

Query based on multiple where clauses in Firebase

Firebase doesn't allow querying with multiple conditions. However, I did find a way around for this:

We need to download the initial filtered data from the database and store it in an array list.

                Query query = databaseReference.orderByChild("genre").equalTo("comedy");
                databaseReference.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                        ArrayList<Movie> movies = new ArrayList<>();
                        for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                            String lead = dataSnapshot1.child("lead").getValue(String.class);
                            String genre = dataSnapshot1.child("genre").getValue(String.class);

                            movie = new Movie(lead, genre);

                            movies.add(movie);

                        }

                        filterResults(movies, "Jack Nicholson");

                        }

                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });

Once we obtain the initial filtered data from the database, we need to do further filter in our backend.

public void filterResults(final List<Movie> list,  final String genre) {
        List<Movie> movies = new ArrayList<>();
        movies = list.stream().filter(o -> o.getLead().equals(genre)).collect(Collectors.toList());
        System.out.println(movies);

        employees.forEach(movie -> System.out.println(movie.getFirstName()));
    }

Regex number between 1 and 100

Try:

^[1-9][0-9]?$|^100$

Working fiddle

EDIT: IF you want to match 00001, 00000099 try

^0*(?:[1-9][0-9]?|100)$

FIDDLE

Append text to textarea with javascript

Use event delegation by assigning the onclick to the <ol>. Then pass the event object as the argument, and using that, grab the text from the clicked element.

_x000D_
_x000D_
function addText(event) {_x000D_
    var targ = event.target || event.srcElement;_x000D_
    document.getElementById("alltext").value += targ.textContent || targ.innerText;_x000D_
}
_x000D_
<textarea id="alltext"></textarea>_x000D_
_x000D_
<ol onclick="addText(event)">_x000D_
  <li>Hello</li>_x000D_
  <li>World</li>_x000D_
  <li>Earthlings</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Note that this method of passing the event object works in older IE as well as W3 compliant systems.

Read and write to binary files in C?

There are a few ways to do it. If I want to read and write binary I usually use open(), read(), write(), close(). Which are completely different than doing a byte at a time. You work with integer file descriptors instead of FILE * variables. fileno will get an integer descriptor from a FILE * BTW. You read a buffer full of data, say 32k bytes at once. The buffer is really an array which you can read from really fast because it's in memory. And reading and writing many bytes at once is faster than one at a time. It's called a blockread in Pascal I think, but read() is the C equivalent.

I looked but I don't have any examples handy. OK, these aren't ideal because they also are doing stuff with JPEG images. Here's a read, you probably only care about the part from open() to close(). fbuf is the array to read into, sb.st_size is the file size in bytes from a stat() call.

    fd = open(MASKFNAME,O_RDONLY);
    if (fd != -1) {
      read(fd,fbuf,sb.st_size);
      close(fd);
      splitmask(fbuf,(uint32_t)sb.st_size); // look at lines, etc
      have_mask = 1;
    }

Here's a write: (here pix is the byte array, jwidth and jheight are the JPEG width and height so for RGB color we write height * width * 3 color bytes). It's the # of bytes to write.

void simpdump(uint8_t *pix, char *nm) { // makes a raw aka .data file
  int sdfd;
  sdfd = open(nm,O_WRONLY | O_CREAT);
  if (sdfd == -1) {
    printf("bad open\n");
    exit(-1);
  }
  printf("width: %i height: %i\n",jwidth,jheight);  // to the console
  write(sdfd,pix,(jwidth*jheight*3));
  close(sdfd);
}

Look at man 2 open, also read, write, close. Also this old-style jpeg example.c: https://github.com/LuaDist/libjpeg/blob/master/example.c I'm reading and writing an entire image at once here. But they're binary reads and writes of bytes, just a lot at once.

"But when I try to read from a file it is not outputting correctly." Hmmm. If you read a number 65 that's (decimal) ASCII for an A. Maybe you should look at man ascii too. If you want a 1 that's ASCII 0x31. A char variable is a tiny 8-bit integer really, if you do a printf as a %i you get the ASCII value, if you do a %c you get the character. Do %x for hexadecimal. All from the same number between 0 and 255.

Can someone explain how to append an element to an array in C programming?

int arr[10] = {0, 5, 3, 64};
arr[4] = 5;

EDIT: So I was asked to explain what's happening when you do:

int arr[10] = {0, 5, 3, 64};

you create an array with 10 elements and you allocate values for the first 4 elements of the array.

Also keep in mind that arr starts at index arr[0] and ends at index arr[9] - 10 elements

arr[0] has value 0;
arr[1] has value 5;
arr[2] has value 3;
arr[3] has value 64;

after that the array contains garbage values / zeroes because you didn't allocated any other values

But you could still allocate 6 more values so when you do

arr[4] = 5;

you allocate the value 5 to the fifth element of the array.

You could do this until you allocate values for the last index of the arr that is arr[9];

Sorry if my explanation is choppy, but I have never been good at explaining things.

Java variable number or arguments for a method

For different types of arguments, there is 3-dots :

public void foo(Object... x) {
    String myVar1  = x.length > 0 ? (String)x[0]  : "Hello";
    int myVar2     = x.length > 1 ? Integer.parseInt((String) x[1]) : 888;
} 

Then call it

foo("Hii"); 
foo("Hii", 146); 

for security, use like this:
if (!(x[0] instanceof String)) { throw new IllegalArgumentException("..."); }

The main drawback of this approach is that if optional parameters are of different types you lose static type checking. Please, see more variations .

Reset push notification settings for app

The plist: /private/var/mobile/Library/RemoteNotification/Clients.plist

... contains the registered clients for push notifications. Removing your app's entry will cause the prompt to re-appear

Disable all table constraints in Oracle

SELECT 'ALTER TABLE '||substr(c.table_name,1,35)|| 
' DISABLE CONSTRAINT '||constraint_name||' ;' 
FROM user_constraints c, user_tables u 
WHERE c.table_name = u.table_name; 

This statement returns the commands which turn off all the constraints including primary key, foreign keys, and another constraints.

Where is android_sdk_root? and how do I set it.?

You need to make a system env variable with the name: ANDROID_SDK_ROOT and it's value should be C:\Users\your_user_name\AppData\Sdk\tools\bin worked for me

How to download/upload files from/to SharePoint 2013 using CSOM?

Upload a file

Upload a file to a SharePoint site (including SharePoint Online) using File.SaveBinaryDirect Method:

using (var clientContext = new ClientContext(url))
{
     using (var fs = new FileStream(fileName, FileMode.Open))
     {
         var fi = new FileInfo(fileName);
         var list = clientContext.Web.Lists.GetByTitle(listTitle);
         clientContext.Load(list.RootFolder);
         clientContext.ExecuteQuery();
         var fileUrl = String.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, fi.Name);

         Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, fileUrl, fs, true);
     }
}

Download file

Download file from a SharePoint site (including SharePoint Online) using File.OpenBinaryDirect Method:

using (var clientContext = new ClientContext(url))
{

     var list = clientContext.Web.Lists.GetByTitle(listTitle);
     var listItem = list.GetItemById(listItemId);
     clientContext.Load(list);
     clientContext.Load(listItem, i => i.File);
     clientContext.ExecuteQuery();

     var fileRef = listItem.File.ServerRelativeUrl;
     var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef);
     var fileName = Path.Combine(filePath,(string)listItem.File.Name);
     using (var fileStream = System.IO.File.Create(fileName))
     {                  
          fileInfo.Stream.CopyTo(fileStream);
     }
}

How to detect the device orientation using CSS media queries?

In Javascript it is better to use screen.width and screen.height. These two values are available in all modern browsers. They give the real dimensions of the screen, even if the browser has been scaled down when the app fires up. window.innerWidth changes when the browser is scaled down, which can't happen on mobile devices but can happen on PCs and laptops.

The values of screen.width and screen.height change when the mobile device flips between portrait and landscape modes, so it is possible to determine the mode by comparing the values. If screen.width is greater than 1280px you're dealing with a PC or laptop.

You can construct an event listener in Javascript to detect when the two values are flipped. The portrait screen.width values to concentrate on are 320px (mainly iPhones), 360px (most other phones), 768px (small tablets) and 800px (regular tablets).

How do I convert a PDF document to a preview image in PHP?

You need ImageMagick and GhostScript

<?php
$im = new imagick('file.pdf[0]');
$im->setImageFormat('jpg');
header('Content-Type: image/jpeg');
echo $im;
?>

The [0] means page 1.

How to Concatenate Numbers and Strings to Format Numbers in T-SQL?

Change this:

SET @ActualWeightDIMS= @Actual_Dims_Lenght + 'x' + 
    @Actual_Dims_Width + 'x' + @Actual_Dims_Height;

To this:

SET @ActualWeightDIMS= CAST(@Actual_Dims_Lenght as varchar(3)) + 'x' + 
    CAST(@Actual_Dims_Width as varchar(3)) + 'x' + 
    CAST(@Actual_Dims_Height as varchar(3));

Change this:

SET @ActualWeightDIMS = @ActualWeight;

To this:

SET @ActualWeightDIMS = CAST(@ActualWeight as varchar(50));

You need to use CAST. Learn all about CAST and CONVERT here, because data types are important!

Do checkbox inputs only post data if they're checked?

I resolved the problem with this code:

HTML Form

<input type="checkbox" id="is-business" name="is-business" value="off" onclick="changeValueCheckbox(this)" >
<label for="is-business">Soy empresa</label>

and the javascript function by change the checkbox value form:

//change value of checkbox element
function changeValueCheckbox(element){
   if(element.checked){
    element.value='on';
  }else{
    element.value='off';
  }
}

and the server checked if the data post is "on" or "off". I used playframework java

        final Map<String, String[]> data = request().body().asFormUrlEncoded();

        if (data.get("is-business")[0].equals('on')) {
            login.setType(new MasterValue(Login.BUSINESS_TYPE));
        } else {
            login.setType(new MasterValue(Login.USER_TYPE));
        }

Objective-C declared @property attributes (nonatomic, copy, strong, weak)

Great answers! One thing that I would like to clarify deeper is nonatomic/atomic. The user should understand that this property - "atomicity" spreads only on the attribute's reference and not on it's contents. I.e. atomic will guarantee the user atomicity for reading/setting the pointer and only the pointer to the attribute. For example:

@interface MyClass: NSObject
@property (atomic, strong) NSDictionary *dict;
...

In this case it is guaranteed that the pointer to the dict will be read/set in the atomic manner by different threads. BUT the dict itself (the dictionary dict pointing to) is still thread unsafe, i.e. all read/add operations to the dictionary are still thread unsafe.

If you need thread safe collection you either have bad architecture (more often) OR real requirement (more rare). If it is "real requirement" - you should either find good&tested thread safe collection component OR be prepared for trials and tribulations writing your own one. It latter case look at "lock-free", "wait-free" paradigms. Looks like rocket-science at a first glance, but could help you achieving fantastic performance in comparison to "usual locking".

Django Template Variables and Javascript

The {{variable}} is substituted directly into the HTML. Do a view source; it isn't a "variable" or anything like it. It's just rendered text.

Having said that, you can put this kind of substitution into your JavaScript.

<script type="text/javascript"> 
   var a = "{{someDjangoVariable}}";
</script>

This gives you "dynamic" javascript.

Order discrete x scale by frequency/value

Hadley has been developing a package called forcats. This package makes the task so much easier. You can exploit fct_infreq() when you want to change the order of x-axis by the frequency of a factor. In the case of the mtcars example in this post, you want to reorder levels of cyl by the frequency of each level. The level which appears most frequently stays on the left side. All you need is the fct_infreq().

library(ggplot2)
library(forcats)

ggplot(mtcars, aes(fct_infreq(factor(cyl)))) +
geom_bar() +
labs(x = "cyl")

If you wanna go the other way around, you can use fct_rev() along with fct_infreq().

ggplot(mtcars, aes(fct_rev(fct_infreq(factor(cyl))))) +
geom_bar() +
labs(x = "cyl") 

enter image description here

How to check if a key exists in Json Object and get its value

JSONObject class has a method named "has". Returns true if this object has a mapping for name. The mapping may be NULL. http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)

How do I import an existing Java keystore (.jks) file into a Java installation?

You can bulk import all aliases from one keystore to another:

keytool -importkeystore -srckeystore source.jks -destkeystore dest.jks

How to pretty print nested dictionaries?

From this link:

def prnDict(aDict, br='\n', html=0,
            keyAlign='l',   sortKey=0,
            keyPrefix='',   keySuffix='',
            valuePrefix='', valueSuffix='',
            leftMargin=0,   indent=1 ):
    '''
return a string representive of aDict in the following format:
    {
     key1: value1,
     key2: value2,
     ...
     }

Spaces will be added to the keys to make them have same width.

sortKey: set to 1 if want keys sorted;
keyAlign: either 'l' or 'r', for left, right align, respectively.
keyPrefix, keySuffix, valuePrefix, valueSuffix: The prefix and
   suffix to wrap the keys or values. Good for formatting them
   for html document(for example, keyPrefix='<b>', keySuffix='</b>'). 
   Note: The keys will be padded with spaces to have them
         equally-wide. The pre- and suffix will be added OUTSIDE
         the entire width.
html: if set to 1, all spaces will be replaced with '&nbsp;', and
      the entire output will be wrapped with '<code>' and '</code>'.
br: determine the carriage return. If html, it is suggested to set
    br to '<br>'. If you want the html source code eazy to read,
    set br to '<br>\n'

version: 04b52
author : Runsun Pan
require: odict() # an ordered dict, if you want the keys sorted.
         Dave Benjamin 
         http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/161403
    '''

    if aDict:

        #------------------------------ sort key
        if sortKey:
            dic = aDict.copy()
            keys = dic.keys()
            keys.sort()
            aDict = odict()
            for k in keys:
                aDict[k] = dic[k]

        #------------------- wrap keys with ' ' (quotes) if str
        tmp = ['{']
        ks = [type(x)==str and "'%s'"%x or x for x in aDict.keys()]

        #------------------- wrap values with ' ' (quotes) if str
        vs = [type(x)==str and "'%s'"%x or x for x in aDict.values()] 

        maxKeyLen = max([len(str(x)) for x in ks])

        for i in range(len(ks)):

            #-------------------------- Adjust key width
            k = {1            : str(ks[i]).ljust(maxKeyLen),
                 keyAlign=='r': str(ks[i]).rjust(maxKeyLen) }[1]

            v = vs[i]        
            tmp.append(' '* indent+ '%s%s%s:%s%s%s,' %(
                        keyPrefix, k, keySuffix,
                        valuePrefix,v,valueSuffix))

        tmp[-1] = tmp[-1][:-1] # remove the ',' in the last item
        tmp.append('}')

        if leftMargin:
          tmp = [ ' '*leftMargin + x for x in tmp ]

        if html:
            return '<code>%s</code>' %br.join(tmp).replace(' ','&nbsp;')
        else:
            return br.join(tmp)     
    else:
        return '{}'

'''
Example:

>>> a={'C': 2, 'B': 1, 'E': 4, (3, 5): 0}

>>> print prnDict(a)
{
 'C'   :2,
 'B'   :1,
 'E'   :4,
 (3, 5):0
}

>>> print prnDict(a, sortKey=1)
{
 'B'   :1,
 'C'   :2,
 'E'   :4,
 (3, 5):0
}

>>> print prnDict(a, keyPrefix="<b>", keySuffix="</b>")
{
 <b>'C'   </b>:2,
 <b>'B'   </b>:1,
 <b>'E'   </b>:4,
 <b>(3, 5)</b>:0
}

>>> print prnDict(a, html=1)
<code>{
&nbsp;'C'&nbsp;&nbsp;&nbsp;:2,
&nbsp;'B'&nbsp;&nbsp;&nbsp;:1,
&nbsp;'E'&nbsp;&nbsp;&nbsp;:4,
&nbsp;(3,&nbsp;5):0
}</code>

>>> b={'car': [6, 6, 12], 'about': [15, 9, 6], 'bookKeeper': [9, 9, 15]}

>>> print prnDict(b, sortKey=1)
{
 'about'     :[15, 9, 6],
 'bookKeeper':[9, 9, 15],
 'car'       :[6, 6, 12]
}

>>> print prnDict(b, keyAlign="r")
{
        'car':[6, 6, 12],
      'about':[15, 9, 6],
 'bookKeeper':[9, 9, 15]
}
'''

How can I create a simple message box in Python?

Also you can position the other window before withdrawing it so that you position your message

#!/usr/bin/env python

from Tkinter import *
import tkMessageBox

window = Tk()
window.wm_withdraw()

#message at x:200,y:200
window.geometry("1x1+200+200")#remember its .geometry("WidthxHeight(+or-)X(+or-)Y")
tkMessageBox.showerror(title="error",message="Error Message",parent=window)

#centre screen message
window.geometry("1x1+"+str(window.winfo_screenwidth()/2)+"+"+str(window.winfo_screenheight()/2))
tkMessageBox.showinfo(title="Greetings", message="Hello World!")

Using python map and other functional tools

import itertools

foos=[1.0, 2.0, 3.0, 4.0, 5.0]
bars=[1, 2, 3]

print zip(foos, itertools.cycle([bars]))

Full screen background image in an activity

What about

android:background="@drawable/your_image"

on the main layout of your activity?

This way you can also have different images for different screen densities by placing them in the appropriate res/drawable-**dpi folders.

I want to execute shell commands from Maven's pom.xml

Thanks! Tomer Ben David. it helped me. as I am doing pip install in demo folder as you mentioned npm install

<groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.3.2</version>
            <executions>
              <execution>
                <goals>
                  <goal>exec</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <executable>pip</executable>
              <arguments><argument>install</argument></arguments>                            
             <workingDirectory>${project.build.directory}/Demo</workingDirectory>
            </configuration>

Is there a CSS parent selector?

Technically there is no direct way to do this. However, you can sort that out with either jQuery or JavaScript.

However, you can do something like this as well.

a.active h1 {color: blue;}
a.active p {color: green;}

jQuery

$("a.active").parents('li').css("property", "value");

If you want to achieve this using jQuery here is the reference for the jQuery parent selector.

How display only years in input Bootstrap Datepicker?

format: "YYYY" 

Should be capital instead of "yyyy"

jQuery ajax request with json response, how to?

You need to call the

$.parseJSON();

For example:

...
success: function(data){
       var json = $.parseJSON(data); // create an object with the key of the array
       alert(json.html); // where html is the key of array that you want, $response['html'] = "<a>something..</a>";
    },
    error: function(data){
       var json = $.parseJSON(data);
       alert(json.error);
    } ...

see this in http://api.jquery.com/jQuery.parseJSON/

if you still have the problem of slashes: search for security.magicquotes.disabling.php or: function.stripslashes.php

Note:

This answer here is for those who try to use $.ajax with the dataType property set to json and even that got the wrong response type. Defining the header('Content-type: application/json'); in the server may correct the problem, but if you are returning text/html or any other type, the $.ajax method should convert it to json. I make a test with older versions of jQuery and only after version 1.4.4 the $.ajax force to convert any content-type to the dataType passed. So if you have this problem, try to update your jQuery version.

how to compare two elements in jquery

For the record, jQuery has an is() function for this:

a.is(b)

Note that a is already a jQuery instance.

How to change font-color for disabled input?

The following gets you pretty close in IE8 and works in other browsers too.

In your html:

<input type="text" 
       readonly="readonly"    <!-- disallow editting -->
       onfocus="this.blur();" <!-- prevent focus -->
       tabindex="-1"          <!-- disallow tabbing -->
       class="disabledInput"  <!-- change the color with CSS -->
       />

In your CSS:

.disabledInput {
    color: black;
}

In IE8, there is a slight amount of border color change on hover. Some CSS for input.disabledInput:hover could probably take care of this.

Running a simple shell script as a cronjob

Specify complete path and grant proper permission to scriptfile. I tried following script file to run through cron:

#!/bin/bash
/bin/mkdir /scratch/ofsaaweb/CHEF_FICHOME/ficdb/bin/crondir

And crontab command is

* * * * * /bin/bash /scratch/ofsaaweb/CHEF_FICHOME/ficdb/bin/test.sh

It worked for me.

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639

How can I give access to a private GitHub repository?

Struggled to find this as well.

Heres a screenshot of how to do it:

enter image description here

get the margin size of an element with jquery

From jQuery's website

Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.

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

In the "root" __init__.py you can also do a

import sys
sys.path.insert(1, '.')

which should make both modules importable.

How do I loop through children objects in javascript?

The backwards compatible version (IE9+) is

var parent = document.querySelector(selector);
Array.prototype.forEach.call(parent.children, function(child, index){
  // Do stuff
});

The es6 way is

const parent = document.querySelector(selector);
Array.from(parent.children).forEach((child, index) => {
  // Do stuff
});

How do you create a dropdownlist from an enum in ASP.NET MVC?

So without Extension functions if you are looking for simple and easy.. This is what I did

<%= Html.DropDownListFor(x => x.CurrentAddress.State, new SelectList(Enum.GetValues(typeof(XXXXX.Sites.YYYY.Models.State))))%>

where XXXXX.Sites.YYYY.Models.State is an enum

Probably better to do helper function, but when time is short this will get the job done.

Adding/removing items from a JavaScript object with jQuery

First off, your quoted code is not JSON. Your code is JavaScript object literal notation. JSON is a subset of that designed for easier parsing.

Your code defines an object (data) containing an array (items) of objects (each with an id, name, and type).

You don't need or want jQuery for this, just JavaScript.

Adding an item:

data.items.push(
    {id: "7", name: "Douglas Adams", type: "comedy"}
);

That adds to the end. See below for adding in the middle.

Removing an item:

There are several ways. The splice method is the most versatile:

data.items.splice(1, 3); // Removes three items starting with the 2nd,
                         // ("Witches of Eastwick", "X-Men", "Ordinary People")

splice modifies the original array, and returns an array of the items you removed.

Adding in the middle:

splice actually does both adding and removing. The signature of the splice method is:

removed_items = arrayObject.splice(index, num_to_remove[, add1[, add2[, ...]]]);
  • index - the index at which to start making changes
  • num_to_remove - starting with that index, remove this many entries
  • addN - ...and then insert these elements

So I can add an item in the 3rd position like this:

data.items.splice(2, 0,
    {id: "7", name: "Douglas Adams", type: "comedy"}
);

What that says is: Starting at index 2, remove zero items, and then insert this following item. The result looks like this:

var data = {items: [
    {id: "1", name: "Snatch", type: "crime"},
    {id: "2", name: "Witches of Eastwick", type: "comedy"},
    {id: "7", name: "Douglas Adams", type: "comedy"},     // <== The new item
    {id: "3", name: "X-Men", type: "action"},
    {id: "4", name: "Ordinary People", type: "drama"},
    {id: "5", name: "Billy Elliot", type: "drama"},
    {id: "6", name: "Toy Story", type: "children"}
]};

You can remove some and add some at once:

data.items.splice(1, 3,
    {id: "7", name: "Douglas Adams", type: "comedy"},
    {id: "8", name: "Dick Francis", type: "mystery"}
);

...which means: Starting at index 1, remove three entries, then add these two entries. Which results in:

var data = {items: [
    {id: "1", name: "Snatch", type: "crime"},
    {id: "7", name: "Douglas Adams", type: "comedy"},
    {id: "8", name: "Dick Francis", type: "mystery"},
    {id: "4", name: "Ordinary People", type: "drama"},
    {id: "5", name: "Billy Elliot", type: "drama"},
    {id: "6", name: "Toy Story", type: "children"}
]};

How do I get JSON data from RESTful service using Python?

Something like this should work unless I'm missing the point:

import json
import urllib2
json.load(urllib2.urlopen("url"))

Regex replace uppercase with lowercase letters

Try this

  • Find: ([A-Z])([A-Z]+)\b
  • Replace: $1\L$2

Make sure case sensitivity is on (Alt + C)

How can I create a self-signed cert for localhost?

you could try mkcert.

macos: brew install mkcert