Programs & Examples On #Removeclass

A method to remove specific class(es) from a DOM element.

JQuery addclass to selected div, remove class if another div is selected

You can use a single line to add and remove class on a div. Please remove a class first to add a new class.

$('div').on('click',function(){
  $('div').removeClass('active').addClass('active');     
});

Removing elements by class name?

One line

document.querySelectorAll(".remove").forEach(el => el.remove());

For example you can do in this page to remove userinfo

document.querySelectorAll(".user-info").forEach(el => el.remove());

How to: Add/Remove Class on mouseOver/mouseOut - JQuery .hover?

You are missing the dot on the selector, and you can use toggleClass method on jquery:

$(".result").hover(
  function () {
    $(this).toggleClass("result_hover")      
  }
);

addClass and removeClass in jQuery - not removing class

I actually just resolved an issue I was having by swapping around the order that I was altering the properties in. For example I was changing the attribute first but I actually had to remove the class and add the new class before modifying the attributes. I'm not sure why it worked but it did. So something to try would be to change from $("XXXX").attr('something').removeClass( "class" ).addClass( "newClass" ) to $("XXXX").removeClass( "class" ).addClass( "newClass" ).attr('something').

JQuery Find #ID, RemoveClass and AddClass

Try this

$('#testID').addClass('nameOfClass');

or

$('#testID').removeClass('nameOfClass');

Bootstrap modal: is not a function

Use:

jQuery.noConflict();
$('#prizePopup').modal('toggle');

How to solve a timeout error in Laravel 5

The Maximum execution time of 30 seconds exceeded error is not related to Laravel but rather your PHP configuration.

Here is how you can fix it. The setting you will need to change is max_execution_time.

;;;;;;;;;;;;;;;;;;;
; Resource Limits ;
;;;;;;;;;;;;;;;;;;;

max_execution_time = 30     ; Maximum execution time of each script, in seconds
max_input_time = 60 ; Maximum amount of time each script may spend parsing request data
memory_limit = 8M      ; Maximum amount of memory a script may consume (8MB)

You can change the max_execution_time to 300 seconds like max_execution_time = 300

You can find the path of your PHP configuration file in the output of the phpinfo function in the Loaded Configuration File section.

How to print all information from an HTTP request to the screen, in PHP

Putting together answers from Peter Bailey and Cmyker you get something like:

<?php
foreach ($_SERVER as $key => $value) {
    if (strpos($key, 'HTTP_') === 0) {
        $chunks = explode('_', $key);
        $header = '';
        for ($i = 1; $y = sizeof($chunks) - 1, $i < $y; $i++) {
            $header .= ucfirst(strtolower($chunks[$i])).'-';
        }
        $header .= ucfirst(strtolower($chunks[$i])).': '.$value;
        echo $header."\n";
    }
}
$body = file_get_contents('php://input');
if ($body != '') {
  print("\n$body\n\n");
}
?>

which works with the php -S built-in webserver, which is quite a handy feature of PHP.

Move top 1000 lines from text file to a new file using Unix shell commands

This is a one-liner but uses four atomic commands:

head -1000 file.txt > newfile.txt; tail +1000 file.txt > file.txt.tmp; cp file.txt.tmp file.txt; rm file.txt.tmp

How to group subarrays by a column value?

for($i = 0 ; $i < count($arr)  ; $i++ )
{
    $tmpArr[$arr[$i]['id']] = $arr[$i]['id'];
}
$vmpArr = array_keys($tmpArr);
print_r($vmpArr);

/usr/bin/ld: cannot find

Add -L/opt/lib to your compiler parameters, this makes the compiler and linker search that path for libcalc.so in that folder.

Can't find out where does a node.js app running and can't kill it

List node process:

$ ps -e|grep node

Kill the process using

$kill -9 XXXX

Here XXXX is the process number

Conditionally hide CommandField or ButtonField in Gridview

To conditionally control view of Template/Command fields, use RowDataBound event of Gridview, like:

    <asp:GridView ID="gv1" OnRowDataBound="gv1_RowDataBound"
              runat="server" AutoGenerateColumns="False" DataKeyNames="Id" >
    <Columns>   
        ...        
           <asp:TemplateField HeaderText="Order Status" 
HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"> 
                 <ItemTemplate> 
                       <asp:Label ID="lblOrderStatus" runat="server"
Text='<%# Bind("OrderStatus") %>'></asp:Label> 
                 </ItemTemplate>
                 <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
                 <ItemStyle HorizontalAlign="Center"></ItemStyle>
           </asp:TemplateField>  
        ...

            <asp:CommandField ShowSelectButton="True" SelectText="Select" />

    </Columns>
                </asp:GridView>

and following:

protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        Label lblOrderStatus=(Label) e.Row.Cells[4].FindControl("lblOrderStatus");

        if (lblOrderStatus.Text== "Ordered")
        {
            lblOrderStatus.ForeColor = System.Drawing.Color.DarkBlue;
            LinkButton bt = (LinkButton)e.Row.Cells[5].Controls[0];
            bt.Visible = false;
            e.Row.BackColor = System.Drawing.Color.LightGray;
        }
    }

z-index issue with twitter bootstrap dropdown menu

This will fix it

.navbar .nav > li {
z-index: 10000;
}

Solr vs. ElasticSearch

Since the long history of Apache Solr, I think one strength of the Solr is its ecosystem. There are many Solr plugins for different types of data and purposes.

solr stack

Search platform in the following layers from bottom to top:

  • Data
    • Purpose: Represent various data types and sources
  • Document building
    • Purpose: Build document information for indexing
  • Indexing and searching
    • Purpose: Build and query a document index
  • Logic enhancement
    • Purpose: Additional logic for processing search queries and results
  • Search platform service
    • Purpose: Add additional functionalities of search engine core to provide a service platform.
  • UI application
    • Purpose: End-user search interface or applications

Reference article : Enterprise search

How can I show the table structure in SQL Server query?

For SQL Server, if using a newer version, you can use

select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='tableName'

There are different ways to get the schema. Using ADO.NET, you can use the schema methods. Use the DbConnection's GetSchema method or the DataReader'sGetSchemaTable method.

Provided that you have a reader for the for the query, you can do something like this:

using(DbCommand cmd = ...)
using(var reader = cmd.ExecuteReader())
{
    var schema = reader.GetSchemaTable();
    foreach(DataRow row in schema.Rows)
    {
        Debug.WriteLine(row["ColumnName"] + " - " + row["DataTypeName"])
    }
}

See this article for further details.

How do I use valgrind to find memory leaks?

Try this:

valgrind --leak-check=full -v ./your_program

As long as valgrind is installed it will go through your program and tell you what's wrong. It can give you pointers and approximate places where your leaks may be found. If you're segfault'ing, try running it through gdb.

Test if numpy array contains only zeros

As another answer says, you can take advantage of truthy/falsy evaluations if you know that 0 is the only falsy element possibly in your array. All elements in an array are falsy iff there are not any truthy elements in it.*

>>> a = np.zeros(10)
>>> not np.any(a)
True

However, the answer claimed that any was faster than other options due partly to short-circuiting. As of 2018, Numpy's all and any do not short-circuit.

If you do this kind of thing often, it's very easy to make your own short-circuiting versions using numba:

import numba as nb

# short-circuiting replacement for np.any()
@nb.jit(nopython=True)
def sc_any(array):
    for x in array.flat:
        if x:
            return True
    return False

# short-circuiting replacement for np.all()
@nb.jit(nopython=True)
def sc_all(array):
    for x in array.flat:
        if not x:
            return False
    return True

These tend to be faster than Numpy's versions even when not short-circuiting. count_nonzero is the slowest.

Some input to check performance:

import numpy as np

n = 10**8
middle = n//2
all_0 = np.zeros(n, dtype=int)
all_1 = np.ones(n, dtype=int)
mid_0 = np.ones(n, dtype=int)
mid_1 = np.zeros(n, dtype=int)
np.put(mid_0, middle, 0)
np.put(mid_1, middle, 1)
# mid_0 = [1 1 1 ... 1 0 1 ... 1 1 1]
# mid_1 = [0 0 0 ... 0 1 0 ... 0 0 0]

Check:

## count_nonzero
%timeit np.count_nonzero(all_0) 
# 220 ms ± 8.73 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit np.count_nonzero(all_1)
# 150 ms ± 4.56 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

### all
# np.all
%timeit np.all(all_1)
%timeit np.all(mid_0)
%timeit np.all(all_0)
# 56.8 ms ± 3.41 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 57.4 ms ± 1.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 55.9 ms ± 2.13 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

# sc_all
%timeit sc_all(all_1)
%timeit sc_all(mid_0)
%timeit sc_all(all_0)
# 44.4 ms ± 2.49 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 22.7 ms ± 599 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 288 ns ± 6.36 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

### any
# np.any
%timeit np.any(all_0)
%timeit np.any(mid_1)
%timeit np.any(all_1)
# 60.7 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 60 ms ± 287 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 57.7 ms ± 1.12 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

# sc_any
%timeit sc_any(all_0)
%timeit sc_any(mid_1)
%timeit sc_any(all_1)
# 41.7 ms ± 1.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 22.4 ms ± 1.51 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 287 ns ± 12.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

* Helpful all and any equivalences:

np.all(a) == np.logical_not(np.any(np.logical_not(a)))
np.any(a) == np.logical_not(np.all(np.logical_not(a)))
not np.all(a) == np.any(np.logical_not(a))
not np.any(a) == np.all(np.logical_not(a))

how to set ul/li bullet point color?

I believe this is controlled by the css color property applied to the element.

The module ".dll" was loaded but the entry-point was not found

I had this problem and

dumpbin /exports mydll.dll

and

depends mydll.dll

showed 'DllRegisterServer'.

The problem was that there was another DLL in the system that had the same name. After renaming mydll the registration succeeded.

mysql extract year from date format

SELECT EXTRACT(YEAR FROM subdateshow) FROM tbl_name;

WPF Binding StringFormat Short Date String

Use the StringFormat property (or ContentStringFormat on ContentControl and its derivatives, e.g. Label).

<TextBlock Text="{Binding Date, StringFormat={}{0:d}}" />

Note the {} prior to the standard String.Format positional argument notation allows the braces to be escaped in the markup extension language.

Facebook Oauth Logout

This solution no longer works with FaceBook's current API (seems it was unintended to begin with)

http://m.facebook.com/logout.php?confirm=1&next=http://yoursitename.com;

Try to give this link on you signout link or button where "yoursitename.com" is where u want to redirect back after signout may be ur home page.

It works..

Html.DropdownListFor selected value not being set

Make sure that you have trim the selected value before you assigning.

//Model

public class SelectType
{
    public string Text { get; set; }
    public string Value { get; set; }
}

//Controller

var types = new List<SelectType>();
types.Add(new SelectType() { Value =  0, Text = "Select a Type" });
types.Add(new SelectType() { Value =  1, Text = "Family Trust" });
types.Add(new SelectType() { Value =  2, Text = "Unit Trust"});
ViewBag.PartialTypes = types;

//View

@Html.DropDownListFor(m => m.PartialType, new SelectList(ViewBag.PartialTypes, "Value", "Text"), new { id = "Type" })

Draw horizontal rule in React Native

You can also try react-native-hr-component

npm i react-native-hr-component --save

Your code:

import Hr from 'react-native-hr-component'

//..

<Hr text="Some Text" fontSize={5} lineColor="#eee" textPadding={5} textStyles={yourCustomStyles} hrStyles={yourCustomHRStyles} />

Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit

--version is a valid option from JDK 9 and it is not a valid option until JDK 8 hence you get the below:

Unrecognized option: --version
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

You can try installing JDK 9 or any version later and check for java --version it will work.

Alternately, from the installed JDK 9 or later versions you can see from java -help the below two options will be available:

    -version      print product version to the error stream and exit
    --version     print product version to the output stream and exit

where as in JDK 8 you will only have below when you execute java -help

    -version      print product version and exit

I hope it answers your question.

Fatal error: "No Target Architecture" in Visual Studio

It would seem that _AMD64_ is not defined, since I can't imagine you are compiling for Itanium (_IA64_).

No module named 'openpyxl' - Python 3.4 - Ubuntu

I still was not able to import 'openpyxl' after successfully installing it via both conda and pip. I discovered that it was installed in '/usr/lib/python3/dist-packages', so this https://stackoverflow.com/a/59861933/10794682 worked for me:

import sys 
sys.path.append('/usr/lib/python3/dist-packages')

Hope this might be useful for others.

StringBuilder vs String concatenation in toString() in Java

Since Java 1.5, simple one line concatenation with "+" and StringBuilder.append() generate exactly the same bytecode.

So for the sake of code readability, use "+".

2 exceptions :

  • multithreaded environment : StringBuffer
  • concatenation in loops : StringBuilder/StringBuffer

How do I import a .dmp file into Oracle?

i got solution what you are getting as per imp help=y it is mentioned that imp is only valid for TRANSPORT_TABLESPACE as below:

Keyword  Description (Default)       Keyword      Description (Default)
--------------------------------------------------------------------------
USERID   username/password           FULL         import entire file (N)
BUFFER   size of data buffer         FROMUSER     list of owner usernames
FILE     input files (EXPDAT.DMP)    TOUSER       list of usernames
SHOW     just list file contents (N) TABLES       list of table names
IGNORE   ignore create errors (N)    RECORDLENGTH length of IO record
GRANTS   import grants (Y)           INCTYPE      incremental import type
INDEXES  import indexes (Y)          COMMIT       commit array insert (N)
ROWS     import data rows (Y)        PARFILE      parameter filename
LOG      log file of screen output   CONSTRAINTS  import constraints (Y)
DESTROY                overwrite tablespace data file (N)
INDEXFILE              write table/index info to specified file
SKIP_UNUSABLE_INDEXES  skip maintenance of unusable indexes (N)
FEEDBACK               display progress every x rows(0)
TOID_NOVALIDATE        skip validation of specified type ids
FILESIZE               maximum size of each dump file
STATISTICS             import precomputed statistics (always)
RESUMABLE              suspend when a space related error is encountered(N)
RESUMABLE_NAME         text string used to identify resumable statement
RESUMABLE_TIMEOUT      wait time for RESUMABLE
COMPILE                compile procedures, packages, and functions (Y)
STREAMS_CONFIGURATION  import streams general metadata (Y)
STREAMS_INSTANTIATION  import streams instantiation metadata (N)
DATA_ONLY              import only data (N)

The following keywords only apply to transportable tablespaces
TRANSPORT_TABLESPACE import transportable tablespace metadata (N)
TABLESPACES tablespaces to be transported into database
DATAFILES datafiles to be transported into database
TTS_OWNERS users that own data in the transportable tablespace set

So, Please create table space for your user:

CREATE TABLESPACE <tablespace name> DATAFILE <path to save, example: 'C:\ORACLEXE\APP\ORACLE\ORADATA\XE\ABC.dbf'> SIZE 100M AUTOEXTEND ON NEXT 100M MAXSIZE 10G EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M;

Convert SVG to image (JPEG, PNG, etc.) in the browser

I recently discovered a couple of image tracing libraries for JavaScript that indeed are able to build an acceptable approximation to the bitmap, both size and quality. I'm developing this JavaScript library and CLI :

https://www.npmjs.com/package/svg-png-converter

Which provides unified API for all of them, supporting browser and node, non depending on DOM, and a Command line tool.

For converting logos/cartoon/like images it does excellent job. For photos / realism some tweaking is needed since the output size can grow a lot.

It has a playground although right now I'm working on a better one, easier to use, since more features has been added:

https://cancerberosgx.github.io/demos/svg-png-converter/playground/#

How to check in Javascript if one element is contained within another

I just had to share 'mine'.

Although conceptually the same as Asaph's answer (benefiting from the same cross-browser compatibility, even IE6), it is a lot smaller and comes in handy when size is at a premium and/or when it is not needed so often.

function childOf(/*child node*/c, /*parent node*/p){ //returns boolean
  while((c=c.parentNode)&&c!==p); 
  return !!c; 
}

..or as one-liner (just 64 chars!):

function childOf(c,p){while((c=c.parentNode)&&c!==p);return !!c}

and jsfiddle here.


Usage:
childOf(child, parent) returns boolean true|false.

Explanation:
while evaluates as long as the while-condition evaluates to true.
The && (AND) operator returns this boolean true/false after evaluating the left-hand side and the right-hand side, but only if the left-hand side was true (left-hand && right-hand).

The left-hand side (of &&) is: (c=c.parentNode).
This will first assign the parentNode of c to c and then the AND operator will evaluate the resulting c as a boolean.
Since parentNode returns null if there is no parent left and null is converted to false, the while-loop will correctly stop when there are no more parents.

The right-hand side (of &&) is: c!==p.
The !== comparison operator is 'not exactly equal to'. So if the child's parent isn't the parent (you specified) it evaluates to true, but if the child's parent is the parent then it evaluates to false.
So if c!==p evaluates to false, then the && operator returns false as the while-condition and the while-loop stops. (Note there is no need for a while-body and the closing ; semicolon is required.)

So when the while-loop ends, c is either a node (not null) when it found a parent OR it is null (when the loop ran through to the end without finding a match).

Thus we simply return that fact (converted as boolean value, instead of the node) with: return !!c;: the ! (NOT operator) inverts a boolean value (true becomes false and vice-versa).
!c converts c (node or null) to a boolean before it can invert that value. So adding a second ! (!!c) converts this false back to true (which is why a double !! is often used to 'convert anything to boolean').


Extra:
The function's body/payload is so small that, depending on case (like when it is not used often and appears just once in the code), one could even omit the function (wrapping) and just use the while-loop:

var a=document.getElementById('child'),
    b=document.getElementById('parent'),
    c;

c=a; while((c=c.parentNode)&&c!==b); //c=!!c;

if(!!c){ //`if(c)` if `c=!!c;` was used after while-loop above
    //do stuff
}

instead of:

var a=document.getElementById('child'),
    b=document.getElementById('parent'),
    c;

function childOf(c,p){while((c=c.parentNode)&&c!==p);return !!c}

c=childOf(a, b);    

if(c){ 
    //do stuff
}

How to set a text box for inputing password in winforms?

I know the perfect answer:

  1. double click on The password TextBox.
  2. write your textbox name like textbox2.
  3. write PasswordChar = '*';.
  4. I prefer going to windows character map and find a perfect hide like ?.

    example:TextBox2.PasswordChar = '?';
    

PHP - Extracting a property from an array of objects

If you have PHP 5.5 or later, the best way is to use the built in function array_column():

$idCats = array_column($cats, 'id');

But the son has to be an array or converted to an array

"No rule to make target 'install'"... But Makefile exists

I was receiving the same error message, and my issue was that I was not in the correct directory when running the command make install. When I changed to the directory that had my makefile it worked.

So possibly you aren't in the right directory.

Crop image in PHP

You can use imagecrop function in (PHP 5 >= 5.5.0, PHP 7)

Example:

<?php
$im = imagecreatefrompng('example.png');
$size = min(imagesx($im), imagesy($im));
$im2 = imagecrop($im, ['x' => 0, 'y' => 0, 'width' => $size, 'height' => $size]);
if ($im2 !== FALSE) {
    imagepng($im2, 'example-cropped.png');
    imagedestroy($im2);
}
imagedestroy($im);
?>

How to get the connection String from a database

A very simple way to retrieve a connection string, is to create a text file, change the extension from .txt to .udl.

Double-clicking the .udl file will open the Data Link Properties wizard.

Configure and test the connection to your database server.

Close the wizard and open the .udl file with the text editor of your choice and simply copy the connection string (without the Provider=<driver>part) to use it in your C# application.

sample udl file content

[oledb]
; Everything after this line is an OLE DB initstring
Provider=SQLNCLI11.1;Integrated Security=SSPI;Persist Security Info=False;User ID="";Initial Catalog=YOURDATABASENAME;Data Source=YOURSERVERNAME;Initial File Name="";Server SPN=""

what you need to copy from it

Integrated Security=SSPI;Initial Catalog=YOURDATABASENAME;Data Source=YOURSERVERNAME;

If you want to specify username and password you can adopt from other answers.

Tutorial: https://teusje.wordpress.com/2012/02/21/how-to-test-an-sql-server-connection/

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

How do I make a file:// hyperlink that works in both IE and Firefox?

At least with Chrome, (I don't know about Firefox) You can drag the icon to the left of the URL in the browser to a folder location on your desktop and it will create a file that behaves as an internet shortcut.

I don't know if the file format is universal yet, however Chrome seems to know what to do with it.

The file produced is a .url file and contains the following:

[InternetShortcut] URL=http://www.accordingtothescriptures.org/prophecy/353prophecies.html

You can replace the URL with anything you'd like.

Tool to generate JSON schema from JSON data

There are a lot of tools mentioned, but one more called JSON Schema inferencer for the record:

https://github.com/rnd0101/json_schema_inferencer

(it's not a library or a product, but a Python script)

With the usual Full Disclosure: I am the author.

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

Note most of the other techniques described here break down if you're dealing with characters outside of the BMP (Unicode Basic Multilingual Plane), i.e. code points that are outside of the u0000-uFFFF range. This will only happen rarely, since the code points outside this are mostly assigned to dead languages. But there are some useful characters outside this, for example some code points used for mathematical notation, and some used to encode proper names in Chinese.

In that case your code will be:

String str = "....";
int offset = 0, strLen = str.length();
while (offset < strLen) {
  int curChar = str.codePointAt(offset);
  offset += Character.charCount(curChar);
  // do something with curChar
}

The Character.charCount(int) method requires Java 5+.

Source: http://mindprod.com/jgloss/codepoint.html

How to resolve "Server Error in '/' Application" error?

I just had the same issue on visual studio 2012. For a internet application project. How to resolve “Server Error in '/' Application” error?

Searching for answer I came across this post, but none of these answer help me. Than I found another post here on stackoverflow that has the answer for resolving this issue. Specified argument was out of the range of valid values. Parameter name: site

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

...but what about the previous round parenteses surrounding all the function declaration?

Specifically, it makes JavaScript interpret the 'function() {...}' construct as an inline anonymous function expression. If you omitted the brackets:

function() {
    alert('hello');
}();

You'd get a syntax error, because the JS parser would see the 'function' keyword and assume you're starting a function statement of the form:

function doSomething() {
}

...and you can't have a function statement without a function name.

function expressions and function statements are two different constructs which are handled in very different ways. Unfortunately the syntax is almost identical, so it's not just confusing to the programmer, even the parser has difficulty telling which you mean!

Java Date vs Calendar

Dates should be used as immutable points in time; Calendars are mutable, and can be passed around and modified if you need to collaborate with other classes to come up with a final date. Consider them analogous to String and StringBuilder and you'll understand how I consider they should be used.

(And yes, I know Date isn't actually technically immutable, but the intention is that it should not be mutable, and if nothing calls the deprecated methods then it is so.)

The executable was signed with invalid entitlements

John's answer is 99% correct. I found that (at least in my configuration), you have to open the Build settings inspector for the PROJECT. The build settings for the target do not contain "Code Signing Entitlements". Perhaps this doesn't make a difference if you have only one target in your project. But if you have multiple targets, you need to go to the project build settings. In any case, after doing what John said, my ad-hoc distribution build worked perfectly.

How to perform OR condition in django queryset?

from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))

via Documentation

keyword not supported data source

I know this is an old post but I got the same error recently so for what it's worth, here's another solution:

This is usually a connection string error, please check the format of your connection string, you can look up 'entity framework connectionstring' or follow the suggestions above.

However, in my case my connection string was fine and the error was caused by something completely different so I hope this helps someone:

  1. First I had an EDMX error: there was a new database table in the EDMX and the table did not exist in my database (funny thing is the error the error was not very obvious because it was not shown in my EDMX or output window, instead it was tucked away in visual studio in the 'Error List' window under the 'Warnings'). I resolved this error by adding the missing table to my database. But, I was actually busy trying to add a stored procedure and still getting the 'datasource' error so see below how i resolved it:

  2. Stored procedure error: I was trying to add a stored procedure and everytime I added it via the EDMX design window I got a 'datasource' error. The solution was to add the stored procedure as blank (I kept the stored proc name and declaration but deleted the contents of the stored proc and replaced it with 'select 1' and retried adding it to the EDMX). It worked! Presumably EF didn't like something inside my stored proc. Once I'd added the proc to EF I was then able to update the contents of the proc on my database to what I wanted it to be and it works, 'datasource' error resolved.

weirdness

The target principal name is incorrect. Cannot generate SSPI context

I ran into a new one for this: SQL 2012 hosted on Server 2012. Was tasked to create a cluster for SQL AlwaysOn.
Cluster was created everyone got the SSPI message.

To fix the problems ran following command:

setspn -D MSSQLSvc/SERVER_FQNName:1433 DomainNamerunningSQLService

DomainNamerunningSQLService == the domain account I set for SQL I needed a Domain Administrator to run the command. Only one server in the cluster had issues.

Then restarted SQL. To my surprise I was able to connect.

Uncaught ReferenceError: $ is not defined

I had this problem when tried to run different web-socket samples.

When pointing browser to 'http://localhost:8080/' I got this error, but pointing exactly to 'http://localhost:8080/index.html' gave no error since in 'index.html' all was fully ok - jquery was included before using $..

Somehow autoforwarding to index.html not fully worked

how to install gcc on windows 7 machine?

Download mingw-get and simply issue:

mingw-get install gcc.

See the Getting Started page.

How to enable mod_rewrite for Apache 2.2

If non of the above works try editing /etc/apache2/sites-enabled/000-default

almost at the top you will find

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

Change the AllowOverride None to AllowOverride All

this worked for me

Getting all request parameters in Symfony 2

Since you are in a controller, the action method is given a Request parameter.

You can access all POST data with $request->request->all();. This returns a key-value pair array.

When using GET requests you access data using $request->query->all();

Jquery selector input[type=text]')

If you have multiple inputs as text in a form or a table that you need to iterate through, I did this:

var $list = $("#tableOrForm :input[type='text']");

$list.each(function(){
    // Go on with your code.
});

What I did was I checked each input to see if the type is set to "text", then it'll grab that element and store it in the jQuery list. Then, it would iterate through that list. You can set a temp variable for the current iteration like this:

var $currentItem = $(this);

This will set the current item to the current iteration of your for each loop. Then you can do whatever you want with the temp variable.

Hope this helps anyone!

The type arguments for method cannot be inferred from the usage

Now my aim was to have one pair with an base type and a type definition (Requirement A). For the type definition I want to use inheritance (Requirement B). The use should be possible, without explicite knowledge over the base type (Requirement C).

After I know now that the gernic constraints are not used for solving the generic return type, I experimented a little bit:

Ok let's introducte Get2:

class ServiceGate
{
    public IAccess<C, T> Get1<C, T>(C control) where C : ISignatur<T>
    {
        throw new NotImplementedException();
    }

    public IAccess<ISignatur<T>, T> Get2<T>(ISignatur<T> control)
    {
        throw new NotImplementedException();
    }
}

class Test
{
    static void Main()
    {
        ServiceGate service = new ServiceGate();
        //var bla1 = service.Get1(new Signatur()); // CS0411
        var bla = service.Get2(new Signatur()); // Works
    }
}

Fine, but this solution reaches not requriement B.

Next try:

class ServiceGate
{
    public IAccess<C, T> Get3<C, T>(C control, ISignatur<T> iControl) where C : ISignatur<T>
    {
        throw new NotImplementedException();
    }

}

class Test
{
    static void Main()
    {
        ServiceGate service = new ServiceGate();
        //var bla1 = service.Get1(new Signatur()); // CS0411
        var bla = service.Get2(new Signatur()); // Works
        var c = new Signatur();
        var bla3 = service.Get3(c, c); // Works!! 
    }
}

Nice! Now the compiler can infer the generic return types. But i don't like it. Other try:

class IC<A, B>
{
    public IC(A a, B b)
    {
        Value1 = a;
        Value2 = b;
    }

    public A Value1 { get; set; }

    public B Value2 { get; set; }
}

class Signatur : ISignatur<bool>
{
    public string Test { get; set; }

    public IC<Signatur, ISignatur<bool>> Get()
    {
        return new IC<Signatur, ISignatur<bool>>(this, this);
    }
}

class ServiceGate
{
    public IAccess<C, T> Get4<C, T>(IC<C, ISignatur<T>> control) where C : ISignatur<T>
    {
        throw new NotImplementedException();
    }
}

class Test
{
    static void Main()
    {
        ServiceGate service = new ServiceGate();
        //var bla1 = service.Get1(new Signatur()); // CS0411
        var bla = service.Get2(new Signatur()); // Works
        var c = new Signatur();
        var bla3 = service.Get3(c, c); // Works!!
        var bla4 = service.Get4((new Signatur()).Get()); // Better...
    }
}

My final solution is to have something like ISignature<B, C>, where B ist the base type and C the definition...

Py_Initialize fails - unable to load the file system codec

For me this happened when I updated Python 64 bit from 3.6.4 to 3.6.5. It threw some error like "unable to extract python.dll. Do you have permissions."

Pycharm also failed to load interpreter, even though I reloaded it in settings. Running python command gave same error, with and without administrator mode.

Reason

There was error in installation of Python, include folder in python installation directory C:\Users\USERNAME\AppData\Local\Programs\Python\Python36 was missing

Reinstalling Python also dint solve the issue.(Not removal and install)

Solution

Uninstall Python and Install of Python again.

Because running installer was just extracting same files excluding include folder

How can I take a screenshot with Selenium WebDriver?

PHP (PHPUnit)

It uses PHPUnit_Selenium extension version 1.2.7:

class MyTestClass extends PHPUnit_Extensions_Selenium2TestCase {
    ...
    public function screenshot($filepath) {
        $filedata = $this->currentScreenshot();
        file_put_contents($filepath, $filedata);
    }

    public function testSomething() {
        $this->screenshot('/path/to/screenshot.png');
    }
    ...
}

How to uninstall Eclipse?

There is no automated uninstaller.

You have to remove Eclipse manually. At least Eclipse does not write anything in the system registry, so deleting some directories and files is enough.

Note: I use Unix style paths in this answer but the locations should be the same on Windows or Unix systems, so ~ refers to the user home directory even on Windows.

Why is there no uninstaller?

According to this discussion about uninstalling Eclipse, the reasoning for not providing an uninstaller is that the Eclipse installer is supposed to just automate a few tasks that in the past had to be done manually (like downloading and extracting Eclipse and adding shortcuts), so they also can be undone manually. There is no entry in "Programs and Features" because the installer does not register anything in the system registry.

How to quickly uninstall Eclipse

Just delete the Eclipse directory and any desktop and start menu shortcuts and be done with it, if you don't mind a few leftover files.

In my opinion this is generally enough and I would stop here, because multiple Eclipse installations can share some files and you don't accidentally want to delete those shared files. You also keep all your projects.

How to completely uninstall Eclipse

If you really want to remove Eclipse without leaving any traces, you have to manually delete

  • all desktop and start menu shortcuts
  • the installation directory (e.g. ~/eclipse/photon/)
  • the p2 bundle pool (which is often shared with other eclipse installations)

The installer has a "Bundle Pools" menu entry which lists the locations of all bundle pools. If you have other Eclipse installations on your system you can use the "Cleanup Agent" to clean up unused bundles. If you don't have any other Eclipse installations you can delete the whole bundle pool directory instead (by default ~/p2/).

If you want to completely remove the Eclipse installer too, delete the installer's executable and the ~/.eclipse/ directory.

Depending on what kind of work you did with Eclipse, there can be more directories that you may want to delete. If you used Maven, then ~/.m2/ contains the Maven cache and settings (shared with Maven CLI and other IDEs). If you develop Eclipse plugins, then there might be JUnit workspaces from test runs, next to you Eclipse workspace. Likewise other build tools and development environments used in Eclipse could have created similar directories.

How to delete all projects

If you want to delete your projects and workspace metadata, you have to delete your workspace(s). The default workspace location is ´~/workspace/´. You can also search for the .metadata directory to get all Eclipse workspaces on your machine.

If you are working with Git projects, these are generally not saved in the workspace but in the ~/git/ directory.

Aren't Python strings immutable? Then why does a + " " + b work?

>>> a = 'dogs'

>>> a.replace('dogs', 'dogs eat treats')

'dogs eat treats'

>>> print a

'dogs'

Immutable, isn't it?!

The variable change part has already been discussed.

Error importing SQL dump into MySQL: Unknown database / Can't create database

I create the database myself using the command line. Then try to import again, it works.

Does Python have a toString() equivalent, and can I convert a db.Model element to String?

str() is the equivalent.

However you should be filtering your query. At the moment your query is all() Todo's.

todos = Todo.all().filter('author = ', users.get_current_user().nickname()) 

or

todos = Todo.all().filter('author = ', users.get_current_user())

depending on what you are defining author as in the Todo model. A StringProperty or UserProperty.

Note nickname is a method. You are passing the method and not the result in template values.

DIV height set as percentage of screen?

This is the solution ,

Add the html also to 100%

html,body {

   height: 100%;
   width: 100%;

}

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

TypeScript or JavaScript type casting

This is called type assertion in TypeScript, and since TypeScript 1.6, there are two ways to express this:

// Original syntax
var markerSymbolInfo = <MarkerSymbolInfo> symbolInfo;

// Newer additional syntax
var markerSymbolInfo = symbolInfo as MarkerSymbolInfo;

Both alternatives are functionally identical. The reason for introducing the as-syntax is that the original syntax conflicted with JSX, see the design discussion here.

If you are in a position to choose, just use the syntax that you feel more comfortable with. I personally prefer the as-syntax as it feels more fluent to read and write.

Git: How to remove proxy

You config proxy settings for some network and now you connect another network. Now have to remove the proxy settings. For that use these commands:

git config --global --unset https.proxy
git config --global --unset http.proxy

Now you can push too. (If did not remove proxy configuration still you can use git commands like add , commit and etc)

Why are my CSS3 media queries not working on mobile devices?

I use a few methods depending. In the same stylesheet i use: @media (max-width: 450px), or for separate make sure you have the link in the header correctly. I had a look at your fixmeup and you have a confusing array of links to css. It acts as you say also on HTC desire S.

403 Forbidden error when making an ajax Post request in Django framework

For the lazy guys:

First download cookie: http://plugins.jquery.com/cookie/

Add it to your html:

<script src="{% static 'designer/js/jquery.cookie.js' %}"></script>

Now you can create a working POST request:

var csrftoken = $.cookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

$.ajax(save_url, {
    type : 'POST',
    contentType : 'application/json',
    data : JSON.stringify(canvas),
    success: function () {
        alert("Saved!");
    }

})

how to start the tomcat server in linux?

The command you have typed is /startup.sh, if you have to start a shell script you have to fire the command as shown below:

$ cd /home/mpatil/softwares/apache-tomcat-7.0.47/bin
$ sh startup.sh 
or 
$ ./startup.sh 

Please try that, you also have to go to your tomcat's bin-folder (by using the cd-command) to execute this shell script. In your case this is /home/mpatil/softwares/apache-tomcat-7.0.47/bin.

What is a regular expression which will match a valid domain name without a subdomain?

Not enough rep yet to comment. In response to paka's solution, I found I needed to adjust three items:

  • The dash and underscore were moved due to the dash being interpreted as a range (as in "0-9")
  • Added a full stop for domain names with many subdomains
  • Extended the potential length for the TLDs to 13

Before:

^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$

After:

^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][-_\.a-zA-Z0-9]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,13}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$

Deep cloning objects

The reason not to use ICloneable is not because it doesn't have a generic interface. The reason not to use it is because it's vague. It doesn't make clear whether you're getting a shallow or a deep copy; that's up to the implementer.

Yes, MemberwiseClone makes a shallow copy, but the opposite of MemberwiseClone isn't Clone; it would be, perhaps, DeepClone, which doesn't exist. When you use an object through its ICloneable interface, you can't know which kind of cloning the underlying object performs. (And XML comments won't make it clear, because you'll get the interface comments rather than the ones on the object's Clone method.)

What I usually do is simply make a Copy method that does exactly what I want.

How to run a PowerShell script without displaying a window?

I was having this same issue. I found out if you go to the Task in Task Scheduler that is running the powershell.exe script, you can click "Run whether user is logged on or not" and that will never show the powershell window when the task runs.

Enable/Disable Anchor Tags using AngularJS

For people not wanting a complicated answer, I used Ng-If to solve this for something similar:

<div style="text-align: center;">
 <a ng-if="ctrl.something != null" href="#" ng-click="ctrl.anchorClicked();">I'm An Anchor</a>
 <span ng-if="ctrl.something == null">I'm just text</span>
</div>

How do you implement a class in C?

In your case the good approximation of the class could be the an ADT. But still it won't be the same.

Source file not compiled Dev C++

You can always try doing it manually from the command prompt. Navigate to the path of the file and type:

gcc filename.c -o filename

Why is the use of alloca() not considered good practice?

I don't think anyone has mentioned this: Use of alloca in a function will hinder or disable some optimizations that could otherwise be applied in the function, since the compiler cannot know the size of the function's stack frame.

For instance, a common optimization by C compilers is to eliminate use of the frame pointer within a function, frame accesses are made relative to the stack pointer instead; so there's one more register for general use. But if alloca is called within the function, the difference between sp and fp will be unknown for part of the function, so this optimization cannot be done.

Given the rarity of its use, and its shady status as a standard function, compiler designers quite possibly disable any optimization that might cause trouble with alloca, if would take more than a little effort to make it work with alloca.

UPDATE: Since variable-length local arrays have been added to C, and since these present very similar code-generation issues to the compiler as alloca, I see that 'rarity of use and shady status' does not apply to the underlying mechanism; but I would still suspect that use of either alloca or VLA tends to compromise code generation within a function that uses them. I would welcome any feedback from compiler designers.

What is pipe() function in Angular

The Pipes you are talking about in the starting description are different from the pipe you showed in the example.

In Angular(2|4|5) Pipes are used to format view as you said. I think you have a basic understanding of pipes in Angular, you can learn more about that from this link - Angular Pipe Doc

The pipe() you have shown in the example is the pipe() method of RxJS 5.5 (RxJS is the default for all Angular apps). In Angular5 all the RxJS operators can be imported using single import and they are now combined using the pipe method.

tap() - RxJS tap operator will look at the Observable value and do something with that value. In other words, after a successful API request, the tap() operator will do any function you want it to perform with the response. In the example, it will just log that string.

catchError() - catchError does exactly the same thing but with error response. If you want to throw an error or want to call some function if you get an error, you can do it here. In the example, it will call handleError() and inside that, it will just log that string.

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

I ran into this issue when the number of <th> tags in the '' did not match the number of in the <tfoot> section

<thead>
    <tr>
        <th></th>
        <th>Subject Areas</th>
        <th></th>
        <th>Option(s)</th>
    <tr>
</thead>

<tbody></tbody>

<tfoot>
    <tr>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
    </tr>
</tfoot>

Which programming language for cloud computing?

As for what programming languages, any browser-based or server-based language is likely to be used. Javascript, PHP, ASP, AJAX, Perl, Java, SQL.

Let's say you need to implement a new programming language and BCL designed specifically for operating in the cloud (it won't be used on client machines ever). It should be optimized for cloud computing; easy to learn, fast, efficient, powerful, modern.

The biggest way i’ve seen cloud hosting products help out developers is the ability to launch and increase the size of a server, without having any kind of delay. Developers are able to create the application in a completely customized environment, and then expand it into a production machine with a significant hassle. If things don’t work as wanted, they can then destroy that machine with relative ease.

Most of the Cloud Computing Providers used JAVA and C-Sharp, to make cloud server.

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

How to use 'hover' in CSS

You need to concatenate the selector and pseudo selector. You'll also need a style element to contain your styles. Most people use an external stylesheet, for lots of benefits (caching for one).

<a class="hover">click</a>

<style type="text/css">

    a.hover:hover {
        text-decoration: underline;

    }

</style>

Just a note: the hover class is not necessary, unless you are defining only certain links to have this behavior (which may be the case)

Skip first couple of lines while reading lines in Python file

If it's a table.

pd.read_table("path/to/file", sep="\t", index_col=0, skiprows=17)

How to sort a data frame by date

The only way I found to work with hours, through an US format in source (mm-dd-yyyy HH-MM-SS PM/AM)...

df_dataSet$time <- as.POSIXct( df_dataSet$time , format = "%m/%d/%Y %I:%M:%S %p" , tz = "GMT")
class(df_dataSet$time)
df_dataSet <- df_dataSet[do.call(order, df_dataSet), ] 

How do I find the authoritative name-server for a domain name?

You'll want the SOA (Start of Authority) record for a given domain name, and this is how you accomplish it using the universally available nslookup command line tool:

command line> nslookup
> set querytype=soa
> stackoverflow.com
Server:         217.30.180.230
Address:        217.30.180.230#53

Non-authoritative answer:
stackoverflow.com
        origin = ns51.domaincontrol.com # ("primary name server" on Windows)
        mail addr = dns.jomax.net       # ("responsible mail addr" on Windows)
        serial = 2008041300
        refresh = 28800
        retry = 7200
        expire = 604800
        minimum = 86400
Authoritative answers can be found from:
stackoverflow.com       nameserver = ns52.domaincontrol.com.
stackoverflow.com       nameserver = ns51.domaincontrol.com.

The origin (or primary name server on Windows) line tells you that ns51.domaincontrol is the main name server for stackoverflow.com.

At the end of output all authoritative servers, including backup servers for the given domain, are listed.

TypeError: Router.use() requires middleware function but got a Object

In any one of your js pages you are missing

module.exports = router;

Check and verify all your JS pages

@angular/material/index.d.ts' is not a module

@angular/material has changed its folder structure. Now you need to use all the modules from their respective folders instead of just material folder

For example:

import { MatDialogModule } from "@angular/material";

has now changed to

import { MatDialogModule } from "@angular/material/dialog";

You can check the following to find the correct path for your module

https://material.angular.io/components/categories

Just navigate to the API tab of required module and find the correct path like this 1

How to obfuscate Python code effectively?

so that it isn't human-readable?

i mean all the file is encoded !! when you open it you can't understand anything .. ! that what i want

As maximum, you can compile your sources into bytecode and then distribute only bytecode. But even this is reversible. Bytecode can be decompiled into semi-readable sources.

Base64 is trivial to decode for anyone, so it cannot serve as actual protection and will 'hide' sources only from complete PC illiterates. Moreover, if you plan to actually run that code by any means, you would have to include decoder right into the script (or another script in your distribution, which would needed to be run by legitimate user), and that would immediately give away your encoding/encryption.

Obfuscation techniques usually involve comments/docs stripping, name mangling, trash code insertion, and so on, so even if you decompile bytecode, you get not very readable sources. But they will be Python sources nevertheless and Python is not good at becoming unreadable mess.

If you absolutely need to protect some functionality, I'd suggest going with compiled languages, like C or C++, compiling and distributing .so/.dll, and then using Python bindings to protected code.

Giving height to table and row in Bootstrap

What worked for me was adding a div around the content. Originally i had this. Css applied to the td had no effect.

        <td>           
             @Html.DisplayFor(modelItem => item.Message)           
        </td>

Then I wrapped the content in a div and the css worked as expected

       <td>
            <div class="largeContent">
                @Html.DisplayFor(modelItem => item.Message)
            </div>
        </td>

TypeError: Can't convert 'int' object to str implicitly

You cannot concatenate a string with an int. You would need to convert your int to a string using the str function, or use formatting to format your output.

Change: -

print("Ok. Your balance is now at " + balanceAfterStrength + " skill points.")

to: -

print("Ok. Your balance is now at {} skill points.".format(balanceAfterStrength))

or: -

print("Ok. Your balance is now at " + str(balanceAfterStrength) + " skill points.")

or as per the comment, use , to pass different strings to your print function, rather than concatenating using +: -

print("Ok. Your balance is now at ", balanceAfterStrength, " skill points.")

node.js require() cache - possible to invalidate?

requireUncached with relative path:

const requireUncached = require => module => {
  delete require.cache[require.resolve(module)];
  return require(module);
};

module.exports = requireUncached;

invoke requireUncached with relative path:

const requireUncached = require('../helpers/require_uncached')(require);
const myModule = requireUncached('./myModule');

Java - What does "\n" mean?

(as per http://java.sun.com/...ex/Pattern.html)

The backslash character ('\') serves to introduce escaped constructs, as defined in the table above, as well as to quote characters that otherwise would be interpreted as unescaped constructs. Thus the expression \\ matches a single backslash and { matches a left brace.

Other examples of usage :

\\ The backslash character<br>
\t The tab character ('\u0009')<br>
\n The newline (line feed) character ('\u000A')<br>
\r The carriage-return character ('\u000D')<br>
\f The form-feed character ('\u000C')<br>
\a The alert (bell) character ('\u0007')<br>
\e The escape character ('\u001B')<br>
\cx The control character corresponding to x <br>

How to implement static class member functions in *.cpp file?

The #include directive literally means "copy all the data in that file to this spot." So when you include the header file, it's textually within the code file, and everything in it will be there, give or take the effect of other directives or macro replacements, when the code file (now called the compilation unit or translation unit) is handed off from the preprocessor module to the compiler module.

Which means the declaration and definition of your static member function were really in the same file all along...

How to fire a button click event from JavaScript in ASP.NET

I can make things work this way:

inside javascript junction that is executed by the html button:

document.getElementById("<%= Button2.ClientID %>").click();

ASP button inside div:

<div id="submitBtn" style="display: none;">
   <asp:Button ID="Button2" runat="server" Text="Submit" ValidationGroup="AllValidators" OnClick="Button2_Click" />
</div>

Everything runs from the .cs file except that the code below doesn't execute. There is no message box and redirect to the same page (refresh all boxes):

 int count = cmd.ExecuteNonQuery();
 if (count > 0)
 {
   cmd2.CommandText = insertSuperRoster;
   cmd2.Connection = con;
   cmd2.ExecuteNonQuery();
   string url = "VaccineRefusal.aspx";
   ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "alert('Data Inserted Successfully!');window.location.href = '" + url + "';", true);
  }

Any ideas why these lines won't execute?

JRE installation directory in Windows

where java works for me to list all java exe but java -verbose tells you which rt.jar is used and thus which jre (full path):

[Opened C:\Program Files\Java\jre6\lib\rt.jar]
...

Edit: win7 and java:

java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) 64-Bit Server VM (build 16.3-b01, mixed mode)

How to listen state changes in react.js?

It's been a while but for future reference: the method shouldComponentUpdate() can be used.

An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:

static getDerivedStateFromProps() 
shouldComponentUpdate() 
render()
getSnapshotBeforeUpdate() 
componentDidUpdate()

ref: https://reactjs.org/docs/react-component.html

Ajax Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

I think setting your header to Access-Control-Allow-Origin: * would do the trick here. Had the same issue and I resolved it like that.

Meaning of @classmethod and @staticmethod for beginner?

When to use each

@staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It’s definition is immutable via inheritance.

  • Python does not have to instantiate a bound-method for object.
  • It eases the readability of the code: seeing @staticmethod, we know that the method does not depend on the state of object itself;

@classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance, can be overridden by subclass. That’s because the first argument for @classmethod function must always be cls (class).

  • Factory methods, that are used to create an instance for a class using for example some sort of pre-processing.
  • Static methods calling static methods: if you split a static methods in several static methods, you shouldn't hard-code the class name but use class methods

here is good link to this topic.

Options for HTML scraping?

There is this solution too: netty HttpClient

How can I remove a commit on GitHub?

It is not very good to re-write the history. If we use git revert <commit_id>, it creates a clean reverse-commit of the said commit id.

This way, the history is not re-written, instead, everyone knows that there has been a revert.

Use a list of values to select rows from a pandas dataframe

You can use isin method:

In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})

In [2]: df
Out[2]:
   A  B
0  5  1
1  6  2
2  3  3
3  4  5

In [3]: df[df['A'].isin([3, 6])]
Out[3]:
   A  B
1  6  2
2  3  3

And to get the opposite use ~:

In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
   A  B
0  5  1
3  4  5

Can I remove the URL from my print css, so the web address doesn't print?

Sadly, no. The header and footer are generated by the browser. Only the end-user can change the footer - it might be an idea to give the user a step-by-step for each browser what to do. See for example here for a set of illustrated walk-throughs for windows based browsers.

The only alternative I know of is generating PDFs, with which you have full control over the printed output.

How do I assert equality on two classes without an equals method?

This is a generic compare method , that compares two objects of a same class for its values of it fields(keep in mind those are accessible by get method)

public static <T> void compare(T a, T b) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    AssertionError error = null;
    Class A = a.getClass();
    Class B = a.getClass();
    for (Method mA : A.getDeclaredMethods()) {
        if (mA.getName().startsWith("get")) {
            Method mB = B.getMethod(mA.getName(),null );
            try {
                Assert.assertEquals("Not Matched = ",mA.invoke(a),mB.invoke(b));
            }catch (AssertionError e){
                if(error==null){
                    error = new AssertionError(e);
                }
                else {
                    error.addSuppressed(e);
                }
            }
        }
    }
    if(error!=null){
        throw error ;
    }
}

Why does the Visual Studio editor show dots in blank spaces?

In Visual Studio 2012
Go to
Edit -> Advanced -> View White Spaces
Or
Press Ctrl+R, Ctrl+W

Plotting time in Python with Matplotlib

You must first convert your timestamps to Python datetime objects (use datetime.strptime). Then use date2num to convert the dates to matplotlib format.

Plot the dates and values using plot_date:

dates = matplotlib.dates.date2num(list_of_datetimes)
matplotlib.pyplot.plot_date(dates, values)

Cannot open output file, permission denied

Hello I realize this post is old, but here is my opinion anyway. This error arises when you close the console output window using the close icon instead of pressing "any key to continue"

Send POST data via raw json with postman

Install Postman native app, Chrome extension has been deprecated. (Mine was opening in own window but still ran as Chrome app)

Integer division: How do you produce a double?

If you change the type of one the variables you have to remember to sneak in a double again if your formula changes, because if this variable stops being part of the calculation the result is messed up. I make a habit of casting within the calculation, and add a comment next to it.

double d = 5 / (double) 20; //cast to double, to do floating point calculations

Note that casting the result won't do it

double d = (double)(5 / 20); //produces 0.0

What's the yield keyword in JavaScript?

Before you learn about yield you need to know about generators. Generators are created using the function* syntax. Generator functions do not execute code but instead returns a type of iterator called a generator. When a value is given using the next method, the generator function keeps executing until it comes across a yield keyword. Using yield gives you back an object containing two values, one is value and the other is done (boolean). The value can be an array, object etc.

AND/OR in Python?

As Matt Ball's answer explains, or is "and/or". But or doesn't work with in the way you use it above. You have to say if "a" in someList or "á" in someList or.... Or better yet,

if any(c in someList for c in ("a", "á", "à", "ã", "â")):
    ...

That's the answer to your question as asked.

Other Notes

However, there are a few more things to say about the example code you've posted. First, the chain of someList.remove... or someList remove... statements here is unnecessary, and may result in unexpected behavior. It's also hard to read! Better to break it into individual lines:

someList.remove("a")
someList.remove("á")
...

Even that's not enough, however. As you observed, if the item isn't in the list, then an error is thrown. On top of that, using remove is very slow, because every time you call it, Python has to look at every item in the list. So if you want to remove 10 different characters, and you have a list that has 100 characters, you have to perform 1000 tests.

Instead, I would suggest a very different approach. Filter the list using a set, like so:

chars_to_remove = set(("a", "á", "à", "ã", "â"))
someList = [c for c in someList if c not in chars_to_remove]

Or, change the list in-place without creating a copy:

someList[:] = (c for c in someList if c not in chars_to_remove)

These both use list comprehension syntax to create a new list. They look at every character in someList, check to see of the character is in chars_to_remove, and if it is not, they include the character in the new list.

This is the most efficient version of this code. It has two speed advantages:

  1. It only passes through someList once. Instead of performing 1000 tests, in the above scenario, it performs only 100.
  2. It can test all characters with a single operation, because chars_to_remove is a set. If it chars_to_remove were a list or tuple, then each test would really be 10 tests in the above scenario -- because each character in the list would need to be checked individually.

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available

In my case, I reinstalled Python. It solved the problem.

brew reinstall python

Where can I find jenkins restful api reference?

Jenkins has a link to their REST API in the bottom right of each page. This link appears on every page of Jenkins and points you to an API output for the exact page you are browsing. That should provide some understanding into how to build the API URls.

You can additionally use some wrapper, like I do, in Python, using http://jenkinsapi.readthedocs.io/en/latest/

Here is their website: https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API

R: Comment out block of code

Wrap it in an unused function:

.f = function() {

## unwanted code here:

}

how do I make a single legend for many subplots with matplotlib?

This answer is a complement to @Evert's on the legend position.

My first try on @Evert's solution failed due to overlaps of the legend and the subplot's title.

In fact, the overlaps are caused by fig.tight_layout(), which changes the subplots' layout without considering the figure legend. However, fig.tight_layout() is necessary.

In order to avoid the overlaps, we can tell fig.tight_layout() to leave spaces for the figure's legend by fig.tight_layout(rect=(0,0,1,0.9)).

Description of tight_layout() parameters.

Which Java library provides base64 encoding/decoding?

Guava also has Base64 (among other encodings and incredibly useful stuff)

What is mapDispatchToProps?

mapStateToProps, mapDispatchToProps and connect from react-redux library provides a convenient way to access your state and dispatch function of your store. So basically connect is a higher order component, you can also think as a wrapper if this make sense for you. So every time your state is changed mapStateToProps will be called with your new state and subsequently as you props update component will run render function to render your component in browser. mapDispatchToProps also stores key-values on the props of your component, usually they take a form of a function. In such way you can trigger state change from your component onClick, onChange events.

From docs:

const TodoListComponent = ({ todos, onTodoClick }) => (
  <ul>
    {todos.map(todo =>
      <Todo
        key={todo.id}
        {...todo}
        onClick={() => onTodoClick(todo.id)}
      />
    )}
  </ul>
)

const mapStateToProps = (state) => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter)
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch(toggleTodo(id))
    }
  }
}

function toggleTodo(index) {
  return { type: TOGGLE_TODO, index }
}

const TodoList = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoList) 

Also make sure that you are familiar with React stateless functions and Higher-Order Components

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

At least 8 = {8,}:

str.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)

Batch script to find and replace a string in text file within a minute for files up to 12 MB

A variant using Bat/Powershell (need .net framework):

replace.bat :

@echo off

call:DoReplace "Findstr" "replacestr" test.txt test1.txt
exit /b

:DoReplace
echo ^(Get-Content "%3"^) ^| ForEach-Object { $_ -replace %1, %2 } ^| Set-Content %4>Rep.ps1
Powershell.exe -executionpolicy ByPass -File Rep.ps1
if exist Rep.ps1 del Rep.ps1
echo Done
pause

How do you define a class of constants in Java?

  1. One of the disadvantage of private constructor is the exists of method could never be tested.

  2. Enum by the nature concept good to apply in specific domain type, apply it to decentralized constants looks not good enough

The concept of Enum is "Enumerations are sets of closely related items".

  1. Extend/implement a constant interface is a bad practice, it is hard to think about requirement to extend a immutable constant instead of referring to it directly.

  2. If apply quality tool like SonarSource, there are rules force developer to drop constant interface, this is a awkward thing as a lot of projects enjoy the constant interface and rarely to see "extend" things happen on constant interfaces

Defining array with multiple types in TypeScript

TypeScript 3.9+ update (May 12, 2020)

Now, TypeScript also supports named tuples. This greatly increases the understandability and maintainability of the code. Check the official TS playground.


So, now instead of unnamed:

const a: [number, string] = [ 1, "message" ];

We can add names:

const b: [id: number, message: string] = [ 1, "message" ];

Note: you need to add all names at once, you can not omit some names, e.g:

type tIncorrect = [id: number, string]; // INCORRECT, 2nd element has no name, compile-time error.
type tCorrect = [id: number, msg: string]; // CORRECT, all have a names.

Tip: if you are not sure in the count of the last elements, you can write it like this:

type t = [msg: string, ...indexes: number];// means first element is a message and there are unknown number of indexes.

Rendering an array.map() in React

Dmitry Brin's answer worked for me, with one caveat. In my case, I needed to run a function between the list tags, which requires nested JSX braces. Example JSX below, which worked for me:

{this.props.data().map(function (object, i) { return <li>{JSON.stringify(object)}</li> })}

If you don't use nested JSX braces, for example:

{this.props.data().map(function (object, i) { return <li>JSON.stringify(object)</li>})}

then you get a list of "JSON.stringify(object)" in your HTML output, which probably isn't what you want.

The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

Use string instead of string? in all places in your code.

The Nullable<T> type requires that T is a non-nullable value type, for example int or DateTime. Reference types like string can already be null. There would be no point in allowing things like Nullable<string> so it is disallowed.

Also if you are using C# 3.0 or later you can simplify your code by using auto-implemented properties:

public class WordAndMeaning
{
    public string Word { get; set; }
    public string Meaning { get; set; }
}

Java balanced expressions check {[()]}

The improved method, from @Smartoop.

public boolean balancedParenthensies(String str) {
    List<Character> leftKeys = Arrays.asList('{', '(', '<', '[');
    List<Character> rightKeys = Arrays.asList('}', ')', '>', ']');

    Stack<Character> stack = new Stack<>();
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (leftKeys.contains(c)) {
            stack.push(c);
        } else if (rightKeys.contains(c)) {
            int index = rightKeys.indexOf(c);
            if (stack.isEmpty() || stack.pop() != leftKeys.get(index)) {
                return false;
            }
        }
    }
    return stack.isEmpty();
}

How to use classes from .jar files?

As workmad3 says, you need the jar file to be in your classpath. If you're compiling from the commandline, that will mean using the -classpath flag. (Avoid the CLASSPATH environment variable; it's a pain in the neck IMO.)

If you're using an IDE, please let us know which one and we can help you with the steps specific to that IDE.

Evaluating a mathematical expression in a string

I think I would use eval(), but would first check to make sure the string is a valid mathematical expression, as opposed to something malicious. You could use a regex for the validation.

eval() also takes additional arguments which you can use to restrict the namespace it operates in for greater security.

Convert XML to JSON (and back) using Javascript

Xml-to-json library has methods jsonToXml(json) and xmlToJson(xml).

How to merge rows in a column into one cell in excel?

For Excel 2011 on Mac it's different. I did it as a three step process.

  1. Create a column of values in column A.
  2. In column B, to the right of the first cell, create a rule that uses the concatenate function on the column value and ",". For example, assuming A1 is the first row, the formula for B1 is =B1. For the next row to row N, the formula is =Concatenate(",",A2). You end up with:
QA
,Sekuli
,Testing
,Applitools
,Visual Testing
,Test Automation
,Selenium
  1. In column C create a formula that concatenates all previous values. Because it is additive you will get all at the end. The formula for cell C1 is =B1. For all other rows to N, the formula is =Concatenate(C1,B2). And you get:
QA,Sekuli
QA,Sekuli,Testing
QA,Sekuli,Testing,Applitools
QA,Sekuli,Testing,Applitools,Visual Testing
QA,Sekuli,Testing,Applitools,Visual Testing,Test Automation
QA,Sekuli,Testing,Applitools,Visual Testing,Test Automation,Selenium

The last cell of the list will be what you want. This is compatible with Excel on Windows or Mac.

Difference between AutoPostBack=True and AutoPostBack=False?

AutoPostBack = true permits control to post back to the server. It is associated with an Event.

Example:

<asp:DropDownList id="id" runat="server" AutoPostBack="true" OnSelectIndexChanged="..."/>

The aspx page with the above drop down list does not need an asp:button to do the post back. When you change an option in the drop down list, the page gets posted back to the server.

Default value of AutoPostBack on control is false.

Composer update memory limit

I am facing problems with composer because it consumes all the available memory, and then, the process get killed ( actualy, the output message is "Killed")

So, I was looking for a solution to limit composer memory usage.

I tried ( from @Sven answers )

$ php -d memory_limit=512M /usr/local/bin/composer update

But it didn't work because

"Composer internally increases the memory_limit to 1.5G."

-> Thats from composer oficial website.

Then I found a command that works :

$ COMPOSER_MEMORY_LIMIT=512M php composer.phar update

Althought, in my case 512mb is not enough !

Source : https://www.agileana.com/blog/composer-memory-limit-troubleshooting/

Spring default behavior for lazy-init

For those coming here and are using Java config you can set the Bean to lazy-init using annotations like this:

In the configuration class:

@Configuration
// @Lazy - For all Beans to load lazily
public class AppConf {

    @Bean
    @Lazy
    public Demo demo() {
        return new Demo();
    }
}

For component scanning and auto-wiring:

@Component
@Lazy
public class Demo {
    ....
    ....
}

@Component
public class B {

    @Autowired
    @Lazy // If this is not here, Demo will still get eagerly instantiated to satisfy this request.
    private Demo demo;

    .......
 }

Copy struct to struct in C

copy structure in c you just need to assign the values as follow:

struct RTCclk RTCclk1;
struct RTCclk RTCclkBuffert;

RTCclk1.second=3;
RTCclk1.minute=4;
RTCclk1.hour=5;

RTCclkBuffert=RTCclk1;

now RTCclkBuffert.hour will have value 5,

RTCclkBuffert.minute will have value 4

RTCclkBuffert.second will have value 3

How do I set up HttpContent for my HttpClient PostAsync second parameter?

To add to Preston's answer, here's the complete list of the HttpContent derived classes available in the standard library:

Credit: https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/

Credit: https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/

There's also a supposed ObjectContent but I was unable to find it in ASP.NET Core.

Of course, you could skip the whole HttpContent thing all together with Microsoft.AspNet.WebApi.Client extensions (you'll have to do an import to get it to work in ASP.NET Core for now: https://github.com/aspnet/Home/issues/1558) and then you can do things like:

var response = await client.PostAsJsonAsync("AddNewArticle", new Article
{
    Title = "New Article Title",
    Body = "New Article Body"
});

Turn off axes in subplots

import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2)


To turn off axes for all subplots, do either:

[axi.set_axis_off() for axi in ax.ravel()]

or

map(lambda axi: axi.set_axis_off(), ax.ravel())

Save matplotlib file to a directory

You should be able to specify the whole path to the destination of your choice. E.g.:

plt.savefig('E:\New Folder\Name of the graph.jpg')

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

In iOS 5, the Manifest.mbdx file was eliminated. For the purpose of this article, it was redundant anyway, because the domain and path are in Manifest.mbdb and the ID hash can be generated with SHA1.

Here is my update of galloglass's code so it works with backups of iOS 5 devices. The only changes are elimination of process_mbdx_file() and addition of a few lines in process_mbdb_file().

Tested with backups of an iPhone 4S and an iPad 1, both with plenty of apps and files.

#!/usr/bin/env python
import sys
import hashlib

mbdx = {}

def getint(data, offset, intsize):
    """Retrieve an integer (big-endian) and new offset from the current offset"""
    value = 0
    while intsize > 0:
        value = (value<<8) + ord(data[offset])
        offset = offset + 1
        intsize = intsize - 1
    return value, offset

def getstring(data, offset):
    """Retrieve a string and new offset from the current offset into the data"""
    if data[offset] == chr(0xFF) and data[offset+1] == chr(0xFF):
        return '', offset+2 # Blank string
    length, offset = getint(data, offset, 2) # 2-byte length
    value = data[offset:offset+length]
    return value, (offset + length)

def process_mbdb_file(filename):
    mbdb = {} # Map offset of info in this file => file info
    data = open(filename).read()
    if data[0:4] != "mbdb": raise Exception("This does not look like an MBDB file")
    offset = 4
    offset = offset + 2 # value x05 x00, not sure what this is
    while offset < len(data):
        fileinfo = {}
        fileinfo['start_offset'] = offset
        fileinfo['domain'], offset = getstring(data, offset)
        fileinfo['filename'], offset = getstring(data, offset)
        fileinfo['linktarget'], offset = getstring(data, offset)
        fileinfo['datahash'], offset = getstring(data, offset)
        fileinfo['unknown1'], offset = getstring(data, offset)
        fileinfo['mode'], offset = getint(data, offset, 2)
        fileinfo['unknown2'], offset = getint(data, offset, 4)
        fileinfo['unknown3'], offset = getint(data, offset, 4)
        fileinfo['userid'], offset = getint(data, offset, 4)
        fileinfo['groupid'], offset = getint(data, offset, 4)
        fileinfo['mtime'], offset = getint(data, offset, 4)
        fileinfo['atime'], offset = getint(data, offset, 4)
        fileinfo['ctime'], offset = getint(data, offset, 4)
        fileinfo['filelen'], offset = getint(data, offset, 8)
        fileinfo['flag'], offset = getint(data, offset, 1)
        fileinfo['numprops'], offset = getint(data, offset, 1)
        fileinfo['properties'] = {}
        for ii in range(fileinfo['numprops']):
            propname, offset = getstring(data, offset)
            propval, offset = getstring(data, offset)
            fileinfo['properties'][propname] = propval
        mbdb[fileinfo['start_offset']] = fileinfo
        fullpath = fileinfo['domain'] + '-' + fileinfo['filename']
        id = hashlib.sha1(fullpath)
        mbdx[fileinfo['start_offset']] = id.hexdigest()
    return mbdb

def modestr(val):
    def mode(val):
        if (val & 0x4): r = 'r'
        else: r = '-'
        if (val & 0x2): w = 'w'
        else: w = '-'
        if (val & 0x1): x = 'x'
        else: x = '-'
        return r+w+x
    return mode(val>>6) + mode((val>>3)) + mode(val)

def fileinfo_str(f, verbose=False):
    if not verbose: return "(%s)%s::%s" % (f['fileID'], f['domain'], f['filename'])
    if (f['mode'] & 0xE000) == 0xA000: type = 'l' # symlink
    elif (f['mode'] & 0xE000) == 0x8000: type = '-' # file
    elif (f['mode'] & 0xE000) == 0x4000: type = 'd' # dir
    else: 
        print >> sys.stderr, "Unknown file type %04x for %s" % (f['mode'], fileinfo_str(f, False))
        type = '?' # unknown
    info = ("%s%s %08x %08x %7d %10d %10d %10d (%s)%s::%s" % 
            (type, modestr(f['mode']&0x0FFF) , f['userid'], f['groupid'], f['filelen'], 
             f['mtime'], f['atime'], f['ctime'], f['fileID'], f['domain'], f['filename']))
    if type == 'l': info = info + ' -> ' + f['linktarget'] # symlink destination
    for name, value in f['properties'].items(): # extra properties
        info = info + ' ' + name + '=' + repr(value)
    return info

verbose = True
if __name__ == '__main__':
    mbdb = process_mbdb_file("Manifest.mbdb")
    for offset, fileinfo in mbdb.items():
        if offset in mbdx:
            fileinfo['fileID'] = mbdx[offset]
        else:
            fileinfo['fileID'] = "<nofileID>"
            print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
        print fileinfo_str(fileinfo, verbose)

Referenced Project gets "lost" at Compile Time

Check your build types of each project under project properties - I bet one or the other will be set to build against .NET XX - Client Profile.

With inconsistent versions, specifically with one being Client Profile and the other not, then it works at design time but fails at compile time. A real gotcha.

There is something funny going on in Visual Studio 2010 for me, which keeps setting projects seemingly randomly to Client Profile, sometimes when I create a project, and sometimes a few days later. Probably some keyboard shortcut I'm accidentally hitting...

How to see top processes sorted by actual memory usage?

List and Sort Processes by Memory Usage:

ps -e -orss=,args= | sort -b -k1,1n | pr -TW$COLUMNS

Emulate Samsung Galaxy Tab

I found under website.

http://developer.samsung.com/android/tools-sdks/Samsung-GALAXY-Tab-Emulator

Extract zip file to add-ons under android sdk path. then launch Android SDK Manager. under "extras" folder check "Android + Google APIs for GALAXY Tab, API 8, revision 1" item and install package.

That's all.

Recursively list all files in a directory including files in symlink directories

Using ls:

  ls -LR

from 'man ls':

   -L, --dereference
          when showing file information for a symbolic link, show informa-
          tion  for  the file the link references rather than for the link
          itself

Or, using find:

find -L .

From the find manpage:

-L     Follow symbolic links.

If you find you want to only follow a few symbolic links (like maybe just the toplevel ones you mentioned), you should look at the -H option, which only follows symlinks that you pass to it on the commandline.

Sql script to find invalid email addresses

sel 'unismankur@yahoo#.co.in' as Email, 
case 
    when Email not like  '%@xx%' 
    AND  Email like  '%@%' 
    AND  CHAR_LENGTH(
     oTranslate(
      trim( Email),
      '._-@0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
      '')
     ) = 0
     then 'N' else 'Y'  end as Invalid_Email_Ind;

This works very well for me.

How do I add to the Windows PATH variable using setx? Having weird problems

This works perfectly:

for /f "usebackq tokens=2,*" %A in (`reg query HKCU\Environment /v PATH`) do set my_user_path=%B

setx PATH "C:\Python27;C:\Python27\Scripts;%my_user_path%"

The 1st command gets the USER environment variable 'PATH', into 'my_user_path' variable The 2nd line prepends the 'C:\Python27;C:\Python27\Scripts;' to the USER environment variable 'PATH'

Razor If/Else conditional operator syntax

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by")

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

Bash script error [: !=: unary operator expected

Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

#!/bin/sh
case $1 in
  '-v') if [ "$1" = -v ]; then
         echo "`ps -ef | grep -v '\['`"
        else
         echo "`ps -ef | grep '\[' | grep root`"
        fi;;
     *) echo "usage: $0 [-v]"
        exit 1;; #It is good practice to throw a code, hence allowing $? check
esac

If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

#!/bin/sh

usage ()
 {
  echo "usage: $0 [-v]"
  exit 1
 }

unset arg_match

for arg in $*
 do
  case $arg in
    '-v') if [ "$arg" = -v ]; then
           echo "`ps -ef | grep -v '\['`"
          else
           echo "`ps -ef | grep '\[' | grep root`"
          fi
          arg_match=1;; # this is set, but could increment.
       *) ;;
  esac
done

if [ ! $arg_match ]
 then
  usage
fi

But, allow multiple occurrences of an argument is convenient to use in situations such as:

$ adduser -u:sam -s -f -u:bob -trace -verbose

We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

$ adduser -u sam -s -f -u bob -trace -verbose

python - find index position in list based of partial string

spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"]

index=spell_list.index("Annual")
print(index)

Using CSS td width absolute, position

You're better off using table-layout: fixed

Auto is the default value and with large tables can cause a bit of client side lag as the browser iterates through it to check all the sizes fit.

Fixed is far better and renders quicker to the page. The structure of the table is dependent on the tables overall width and the width of each of the columns.

Here it is applied to the original example: JSFIDDLE, You'll note that the remaining columns are crushed and overlapping their content. We can fix that with some more CSS (all I've had to do is add a class to the first TR):

    table {
        width: 100%;
        table-layout: fixed;
    }

    .header-row > td {
        width: 100px;
    }

    td.rhead {
        width: 300px
    }

Seen in action here: JSFIDDLE

ESLint - "window" is not defined. How to allow global variables in package.json

There is a builtin environment: browser that includes window.

Example .eslintrc.json:

"env": {
    "browser": true,
    "node": true,
    "jasmine": true
  },

More information: http://eslint.org/docs/user-guide/configuring.html#specifying-environments

Also see the package.json answer by chevin99 below.

Interface or an Abstract Class: which one to use?

The main difference is an abstract class can contain default implementation whereas an interface cannot.

An interface is a contract of behaviour without any implementation.

React component initialize state from props

you could use key value to reset state when need, pass props to state it's not a good practice , because you have uncontrolled and controlled component in one place. Data should be in one place handled read this https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key

How to get the Touch position in android?

@Override
    public boolean onTouch(View v, MotionEvent event) {
       float x = event.getX();
       float y = event.getY();
       return true;
    }

'negative' pattern matching in python

and(re.search("bla_bla_pattern", str_item, re.IGNORECASE) == None)

is working.

Are there benefits of passing by pointer over passing by reference in C++?

I like the reasoning by an article from "cplusplus.com:"

  1. Pass by value when the function does not want to modify the parameter and the value is easy to copy (ints, doubles, char, bool, etc... simple types. std::string, std::vector, and all other STL containers are NOT simple types.)

  2. Pass by const pointer when the value is expensive to copy AND the function does not want to modify the value pointed to AND NULL is a valid, expected value that the function handles.

  3. Pass by non-const pointer when the value is expensive to copy AND the function wants to modify the value pointed to AND NULL is a valid, expected value that the function handles.

  4. Pass by const reference when the value is expensive to copy AND the function does not want to modify the value referred to AND NULL would not be a valid value if a pointer was used instead.

  5. Pass by non-cont reference when the value is expensive to copy AND the function wants to modify the value referred to AND NULL would not be a valid value if a pointer was used instead.

  6. When writing template functions, there isn't a clear-cut answer because there are a few tradeoffs to consider that are beyond the scope of this discussion, but suffice it to say that most template functions take their parameters by value or (const) reference, however because iterator syntax is similar to that of pointers (asterisk to "dereference"), any template function that expects iterators as arguments will also by default accept pointers as well (and not check for NULL since the NULL iterator concept has a different syntax).

http://www.cplusplus.com/articles/z6vU7k9E/

What I take from this is that the major difference between choosing to use a pointer or reference parameter is if NULL is an acceptable value. That's it.

Whether the value is input, output, modifiable etc. should be in the documentation / comments about the function, after all.

Method to find string inside of the text file. Then getting the following lines up to a certain limit

I am doing something similar but in C++. What you need to do is read the lines in one at a time and parse them (go over the words one by one). I have an outter loop that goes over all the lines and inside that is another loop that goes over all the words. Once the word you need is found, just exit the loop and return a counter or whatever you want.

This is my code. It basically parses out all the words and adds them to the "index". The line that word was in is then added to a vector and used to reference the line (contains the name of the file, the entire line and the line number) from the indexed words.

ifstream txtFile;
txtFile.open(path, ifstream::in);
char line[200];
//if path is valid AND is not already in the list then add it
if(txtFile.is_open() && (find(textFilePaths.begin(), textFilePaths.end(), path) == textFilePaths.end())) //the path is valid
{
    //Add the path to the list of file paths
    textFilePaths.push_back(path);
    int lineNumber = 1;
    while(!txtFile.eof())
    {
        txtFile.getline(line, 200);
        Line * ln = new Line(line, path, lineNumber);
        lineNumber++;
        myList.push_back(ln);
        vector<string> words = lineParser(ln);
        for(unsigned int i = 0; i < words.size(); i++)
        {
            index->addWord(words[i], ln);
        }
    }
    result = true;
}

Selecting only first-level elements in jquery

You can also use $("ul li:first-child") to only get the direct children of the UL.

I agree though, you need an ID or something else to identify the main UL otherwise it will just select them all. If you had a div with an ID around the UL the easiest thing to do would be$("#someDiv > ul > li")

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Follow the steps given below:

  1. Stop your MySQL server completely. This can be done by accessing the Services window inside Windows XP and Windows Server 2003, where you can stop the MySQL service.

  2. Open your MS-DOS command prompt using "cmd" inside the Run window. Inside it navigate to your MySQL bin folder, such as C:\MySQL\bin using the cd command.

  3. Execute the following command in the command prompt: mysqld.exe -u root --skip-grant-tables

  4. Leave the current MS-DOS command prompt as it is, and open a new MS-DOS command prompt window.

  5. Navigate to your MySQL bin folder, such as C:\MySQL\bin using the cd command.

  6. Enter mysql and press enter.

  7. You should now have the MySQL command prompt working. Type use mysql; so that we switch to the "mysql" database.

  8. Execute the following command to update the password:

    UPDATE user SET Password = PASSWORD('NEW_PASSWORD') WHERE User = 'root'; 
    

However, you can now run any SQL command that you wish.

After you are finished close the first command prompt and type exit; in the second command prompt windows to disconnect successfully. You can now start the MySQL service.

How to strip a specific word from a string?

Providing you know the index value of the beginning and end of each word you wish to replace in the character array, and you only wish to replace that particular chunk of data, you could do it like this.

>>> s = "papa is papa is papa"
>>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
>>> print(s)
papa is mama is papa

Alternatively, if you also wish to retain the original data structure, you could store it in a dictionary.

>>> bin = {}
>>> s = "papa is papa is papa"
>>> bin["0"] = s
>>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
>>> print(bin["0"])
papa is papa is papa
>>> print(s)
papa is mama is papa

Space between Column's children in Flutter

Column(
  children: <Widget>[
    FirstWidget(),
    Spacer(),
    SecondWidget(),
  ]
)

Spacer creates a flexible space to insert into a [Flexible] widget. (Like a column)

Setting multiple attributes for an element at once with JavaScript

You can create a function that takes a variable number of arguments:

function setAttributes(elem /* attribute, value pairs go here */) {
    for (var i = 1; i < arguments.length; i+=2) {
        elem.setAttribute(arguments[i], arguments[i+1]);
    }
}

setAttributes(elem, 
    "src", "http://example.com/something.jpeg",
    "height", "100%",
    "width", "100%");

Or, you pass the attribute/value pairs in on an object:

 function setAttributes(elem, obj) {
     for (var prop in obj) {
         if (obj.hasOwnProperty(prop)) {
             elem[prop] = obj[prop];
         }
     }
 }

setAttributes(elem, {
    src: "http://example.com/something.jpeg",
    height: "100%",
    width: "100%"
});

You could also make your own chainable object wrapper/method:

function $$(elem) {
    return(new $$.init(elem));
}

$$.init = function(elem) {
    if (typeof elem === "string") {
        elem = document.getElementById(elem);
    }
    this.elem = elem;
}

$$.init.prototype = {
    set: function(prop, value) {
        this.elem[prop] = value;
        return(this);
    }
};

$$(elem).set("src", "http://example.com/something.jpeg").set("height", "100%").set("width", "100%");

Working example: http://jsfiddle.net/jfriend00/qncEz/

Using regular expressions to do mass replace in Notepad++ and Vim

Everything before the A, B, C, etc.

That seems so simple I must be misinterpreting you. It's just

:%s/<.*>//

Real mouse position in canvas

Refer this question: The mouseEvent.offsetX I am getting is much larger than actual canvas size .I have given a function there which will exactly suit in your situation

How to get unique device hardware id in Android?

Update: 19 -11-2019

The below answer is no more relevant to present day.

So for any one looking for answers you should look at the documentation linked below

https://developer.android.com/training/articles/user-data-ids


Old Answer - Not relevant now. You check this blog in the link below

http://android-developers.blogspot.in/2011/03/identifying-app-installations.html

ANDROID_ID

import android.provider.Settings.Secure;

private String android_id = Secure.getString(getContext().getContentResolver(),
                                                    Secure.ANDROID_ID); 

The above is from the link @ Is there a unique Android device ID?

More specifically, Settings.Secure.ANDROID_ID. This is a 64-bit quantity that is generated and stored when the device first boots. It is reset when the device is wiped.

ANDROID_ID seems a good choice for a unique device identifier. There are downsides: First, it is not 100% reliable on releases of Android prior to 2.2 (“Froyo”). Also, there has been at least one widely-observed bug in a popular handset from a major manufacturer, where every instance has the same ANDROID_ID.

The below solution is not a good one coz the value survives device wipes (“Factory resets”) and thus you could end up making a nasty mistake when one of your customers wipes their device and passes it on to another person.

You get the imei number of the device using the below

  TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
  telephonyManager.getDeviceId();

http://developer.android.com/reference/android/telephony/TelephonyManager.html#getDeviceId%28%29

Add this is manifest

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

FontAwesome icons not showing. Why?

For seekers of missing font-awesome icons, I have collected a few ideas:

  • Assure you use a correct link to the CDN, such as:

    <link 
      href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.css" 
      rel="stylesheet"  type='text/css'>
    
  • If your page uses HTTPS, do you link to the font-awesome CSS using HTTPS (replace http:// with https:// in the link above).

  • Double check that you don't have AdBlock Plus or uBlock enabled. They might be blocking some of the icons.

  • Reset your browsers cache. (On Chrome do a looong click on the reload button and select Hard Cache Reset)

  • Assure that the <span> or <i> element you use, uses the FontAwesome font family. For example, it must not just

    <i class="fa-pencil" title="Edit"></i>
    

    but

    <i class="fa fa-pencil" title="Edit"></i>
    

    It won't work if you have something as the following in your CSS:

    * {
      font-family: 'Josefin Sans', sans-serif !important;   
    }
    
  • If you are using IE8, are you using a HTML5 Shim?

  • If this doesn't work, there are further Troubleshooting Ideas on the Font Awesome Wiki.

Relative instead of Absolute paths in Excel VBA

I think the problem is that opening the file without a path will only work if your "current directory" is set correctly.

Try typing "Debug.Print CurDir" in the Immediate Window - that should show the location for your default files as set in Tools...Options.

I'm not sure I'm completely happy with it, perhaps because it's somewhat of a legacy VB command, but you could do this:

ChDir ThisWorkbook.Path

I think I'd prefer to use ThisWorkbook.Path to construct a path to the HTML file. I'm a big fan of the FileSystemObject in the Scripting Runtime (which always seems to be installed), so I'd be happier to do something like this (after setting a reference to Microsoft Scripting Runtime):

Const HTML_FILE_NAME As String = "my_input.html"

With New FileSystemObject
    With .OpenTextFile(.BuildPath(ThisWorkbook.Path, HTML_FILE_NAME), ForReading)
        ' Now we have a TextStream object that we can use to read the file
    End With
End With

Ruby combining an array into one string

Use the Array#join method (the argument to join is what to insert between the strings - in this case a space):

@arr.join(" ")

TypeError: string indices must be integers, not str // working with dict

Actually I think that more general approach to loop through dictionary is to use iteritems():

# get tuples of term, courses
for term, term_courses in courses.iteritems():
    # get tuples of course number, info
    for course, info in term_courses.iteritems():
        # loop through info
        for k, v in info.iteritems():
            print k, v

output:

assistant Peter C.
prereq cs101
...
name Programming a Robotic Car
teacher Sebastian

Or, as Matthias mentioned in comments, if you don't need keys, you can just use itervalues():

for term_courses in courses.itervalues():
    for info in term_courses.itervalues():
        for k, v in info.iteritems():
            print k, v

How can I simulate a print statement in MySQL?

This is an old post, but thanks to this post I have found this:

\! echo 'some text';

Tested with MySQL 8 and working correctly. Cool right? :)

Why use Select Top 100 Percent?

...allow use of an ORDER BY in a view definition.

That's not a good idea. A view should never have an ORDER BY defined.

An ORDER BY has an impact on performance - using it a view means that the ORDER BY will turn up in the explain plan. If you have a query where the view is joined to anything in the immediate query, or referenced in an inline view (CTE/subquery factoring) - the ORDER BY is always run prior to the final ORDER BY (assuming it was defined). There's no benefit to ordering rows that aren't the final result set when the query isn't using TOP (or LIMIT for MySQL/Postgres).

Consider:

CREATE VIEW my_view AS
    SELECT i.item_id,
           i.item_description,
           it.item_type_description
      FROM ITEMS i
      JOIN ITEM_TYPES it ON it.item_type_id = i.item_type_id
  ORDER BY i.item_description

...

  SELECT t.item_id,
         t.item_description,
         t.item_type_description
    FROM my_view t
ORDER BY t.item_type_description

...is the equivalent to using:

  SELECT t.item_id,
         t.item_description,
         t.item_type_description
    FROM (SELECT i.item_id,
                 i.item_description,
                 it.item_type_description
            FROM ITEMS i
            JOIN ITEM_TYPES it ON it.item_type_id = i.item_type_id
        ORDER BY i.item_description) t
ORDER BY t.item_type_description

This is bad because:

  1. The example is ordering the list initially by the item description, and then it's reordered based on the item type description. It's wasted resources in the first sort - running as is does not mean it's running: ORDER BY item_type_description, item_description
  2. It's not obvious what the view is ordered by due to encapsulation. This does not mean you should create multiple views with different sort orders...

Windows 8.1 gets Error 720 on connect VPN

This solved my 720 problem. The idea is to change the driver of the faulty WAN to another network adaptar driver, and then we are able to uninstall the WAN device and then reboot the system.

https://forums.lenovo.com/t5/Windows-8-and-8-1/SOLVED-WAN-Miniport-2-yellow-exclamation-mark-in-Device-Manager/td-p/1051981

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

Here's my take experience with E7 async/await:

In case you have an async helperFunction() called from your test... (one explicilty with the ES7 async keyword, I mean)

? make sure, you call that as await helperFunction(whateverParams) (well, yeah, naturally, once you know...)

And for that to work (to avoid ‘await is a reserved word’), your test-function must have an outer async marker:

it('my test', async () => { ...

ssh: The authenticity of host 'hostname' can't be established

To disable (or control disabling), add the following lines to the beginning of /etc/ssh/ssh_config...

Host 192.168.0.*
   StrictHostKeyChecking=no
   UserKnownHostsFile=/dev/null

Options:

  • The Host subnet can be * to allow unrestricted access to all IPs.
  • Edit /etc/ssh/ssh_config for global configuration or ~/.ssh/config for user-specific configuration.

See http://linuxcommando.blogspot.com/2008/10/how-to-disable-ssh-host-key-checking.html

Similar question on superuser.com - see https://superuser.com/a/628801/55163

Apache won't run in xampp

Try stopping Apache and MySql and starting them again in the following order.

  1. Apache
  2. MySql
  3. Etc...

Wait for both services to stop properly before restarting. Turning them on and off too quickly gives the same problem.

Inspired by lansharks answer.

How to select distinct query using symfony2 doctrine query builder?

you could write

select DISTINCT f from t;

as

select f from t group by f;

thing is, I am just currently myself getting into Doctrine, so I cannot give you a real answer. but you could as shown above, simulate a distinct with group by and transform that into Doctrine. if you want add further filtering then use HAVING after group by.

"You have mail" message in terminal, os X

It means that a process or script you have created is sending mail to an account on your local machine (for example, a mail server running on localhost application).

Manage this mail with these commands:

t <message list>        type messages
n                       goto and type next message
e <message list>        edit messages
f <message list>        give head lines of messages
d <message list>        delete messages
s <message list>        file append messages to file
u <message list>        undelete messages
R <message list>        reply to message senders
r <message list>        reply to message senders and all recipients
pre <message list>      make messages go back to /var/mail
m <user list>           mail to specific users
q                       quit, saving unresolved messages in mbox
x                       quit, do not remove system mailbox
h                       print out active message headers
!                       shell escape
cd [directory]          chdir to directory or home if none given

A consists of integers, ranges of same, or user names separated by spaces. If omitted, Mail uses the last message typed.

A consists of user names or aliases separated by spaces. Aliases are defined in .mailrc in your home directory.

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

CSS: Hover one element, effect for multiple elements?

This is not difficult to achieve, but you need to use the javascript onmouseover function. Pseudoscript:

<div class="section ">

<div class="image"><img src="myImage.jpg" onmouseover=".layer {border: 1px solid black;} .image {border: 1px solid black;}" /></div>

<div class="layer">Lorem Ipsum</div>

</div>

Use your own colors. You can also reference javascript functions in the mouseover command.

How to convert a byte array to a hex string in Java?

I prefer to use this:

final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes, int offset, int count) {
    char[] hexChars = new char[count * 2];
    for ( int j = 0; j < count; j++ ) {
        int v = bytes[j+offset] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}

It is slightly more flexible adaptation of the accepted answer. Personally, I keep both the accepted answer and this overload along with it, usable in more contexts.

How to select a single column with Entity Framework?

You can use LINQ's .Select() to do that. In your case it would go something like:

string Name = yourDbContext
  .MyTable
  .Where(u => u.UserId == 1)
  .Select(u => u.Name)
  .SingleOrDefault(); // This is what actually executes the request and return a response

If you are expecting more than one entry in response, you can use .ToList() instead, to execute the request. Something like this, to get the Name of everyone with age 30:

string[] Names = yourDbContext
  .MyTable
  .Where(u => u.Age == 30)
  .Select(u => u.Name)
  .ToList();

How to state in requirements.txt a direct github source

“Editable” packages syntax can be used in requirements.txt to import packages from a variety of VCS (git, hg, bzr, svn):

-e git://github.com/mozilla/elasticutils.git#egg=elasticutils

Also, it is possible to point to particular commit:

-e git://github.com/mozilla/elasticutils.git@000b14389171a9f0d7d713466b32bc649b0bed8e#egg=elasticutils

use video as background for div

I believe this is what you're looking for. It automatically scaled the video to fit the container.

DEMO: http://jsfiddle.net/t8qhgxuy/

Video need to have height and width always set to 100% of the parent.

HTML:

<div class="one"> CONTENT OVER VIDEO
    <video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video>
</div>

<div class="two">
    <video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video> CONTENT OVER VIDEO
</div>

CSS:

body {
    overflow: scroll;
    padding:  60px 20px;
}

.one {
    width: 90%;
    height: 30vw;
    overflow: hidden;
    border: 15px solid red;
    margin-bottom: 40px;
    position: relative;
}

.two{
    width: 30%;
    height: 300px;
    overflow: hidden;
    border: 15px solid blue;
    position: relative;
}

.video-background { /* class name used in javascript too */
    width: 100%; /* width needs to be set to 100% */
    height: 100%; /* height needs to be set to 100% */
    position: absolute;
    left: 0;
    top: 0;
    z-index: -1;
}

JS:

function scaleToFill() {
    $('video.video-background').each(function(index, videoTag) {
       var $video = $(videoTag),
           videoRatio = videoTag.videoWidth / videoTag.videoHeight,
           tagRatio = $video.width() / $video.height(),
           val;

       if (videoRatio < tagRatio) {
           val = tagRatio / videoRatio * 1.02; <!-- size increased by 2% because value is not fine enough and sometimes leaves a couple of white pixels at the edges -->
       } else if (tagRatio < videoRatio) {
           val = videoRatio / tagRatio * 1.02;
       }

       $video.css('transform','scale(' + val  + ',' + val + ')');

    });    
}

$(function () {
    scaleToFill();

    $('.video-background').on('loadeddata', scaleToFill);

    $(window).resize(function() {
        scaleToFill();
    });
});

Sort an array in Java

just FYI, you can now use Java 8 new API for sorting any type of array using parallelSort

parallelSort uses Fork/Join framework introduced in Java 7 to assign the sorting tasks to multiple threads available in the thread pool.

the two methods that can be used to sort int array,

parallelSort(int[] a)
parallelSort(int[] a,int fromIndex,int toIndex)

Changing upload_max_filesize on PHP

You can't use shorthand notation to set configuration values outside of PHP.ini. I assume it's falling back to 2MB as the compiled default when confronted with a bad value.

On the other hand, I don't think upload_max_filesize could be set using ini_set(). The "official" list states that it is PHP_INI_PERDIR .

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

This could also be an issue of building the code using a 64 bit configuration. You can try to select x86 as the build platform which can solve this issue. To do this right-click the solution and select Configuration Manager From there you can change the Platform of the project using the 32-bit .dll to x86

Pass a string parameter in an onclick function

In Razor, you can pass parameters dynamically:

<a href='javascript:void(0);' onclick='showtotextbox(@Model.UnitNameVMs[i].UnitNameID, "@Model.UnitNameVMs[i].FarName","@Model.UnitNameVMs[i].EngName","@Model.UnitNameVMs[i].Symbol" );'>@Model.UnitNameVMs[i].UnitNameID</a>

How to run a .jar in mac?

You don't need JDK to run Java based programs. JDK is for development which stands for Java Development Kit.

You need JRE which should be there in Mac.

Try: java -jar Myjar_file.jar

EDIT: According to this article, for Mac OS 10

The Java runtime is no longer installed automatically as part of the OS installation.

Then, you need to install JRE to your machine.

PowerShell script to check the status of a URL

You must update the Windows PowerShell to minimum of version 4.0 for the script below to work.


[array]$SiteLinks = "http://mypage.global/Chemical/test.html"
"http://maypage2:9080/portal/site/hotpot/test.json"


foreach($url in $SiteLinks) {

   try {
      Write-host "Verifying $url" -ForegroundColor Yellow
      $checkConnection = Invoke-WebRequest -Uri $url
      if ($checkConnection.StatusCode -eq 200) {
         Write-Host "Connection Verified!" -ForegroundColor Green
      }

   } 
   catch [System.Net.WebException] {
      $exceptionMessage = $Error[0].Exception
      if ($exceptionMessage -match "503") {
         Write-Host "Server Unavaiable" -ForegroundColor Red
      }
      elseif ($exceptionMessage -match "404") {
         Write-Host "Page Not found" -ForegroundColor Red
      }


   }
}

Import JavaScript file and call functions using webpack, ES6, ReactJS

import * as utils from './utils.js'; 

If you do the above, you will be able to use functions in utils.js as

utils.someFunction()

How can I use ":" as an AWK field separator?

There isn't any need to write this much. Just put your desired field separator with the -F option in the AWK command and the column number you want to print segregated as per your mentioned field separator.

echo "1: " | awk -F: '{print $1}'
1

echo "1#2" | awk -F# '{print $1}'
1

How do I split a string on a delimiter in Bash?

If you don't mind processing them immediately, I like to do this:

for i in $(echo $IN | tr ";" "\n")
do
  # process
done

You could use this kind of loop to initialize an array, but there's probably an easier way to do it. Hope this helps, though.

What is an instance variable in Java?

An instance variable is a variable that is a member of an instance of a class (i.e., associated with something created with a new), whereas a class variable is a member of the class itself.

Every instance of a class will have its own copy of an instance variable, whereas there is only one of each static (or class) variable, associated with the class itself.

What’s the difference between a class variable and an instance variable?

This test class illustrates the difference:

public class Test {
   
    public static String classVariable = "I am associated with the class";
    public String instanceVariable = "I am associated with the instance";
    
    public void setText(String string){
        this.instanceVariable = string;
    }
    
    public static void setClassText(String string){
        classVariable = string;
    }
    
    public static void main(String[] args) {
        Test test1 = new Test();
        Test test2 = new Test();
        
        // Change test1's instance variable
        test1.setText("Changed");
        System.out.println(test1.instanceVariable); // Prints "Changed"
        // test2 is unaffected
        System.out.println(test2.instanceVariable); // Prints "I am associated with the instance"
        
        // Change class variable (associated with the class itself)
        Test.setClassText("Changed class text");
        System.out.println(Test.classVariable); // Prints "Changed class text"
        
        // Can access static fields through an instance, but there still is only one
        // (not best practice to access static variables through instance)
        System.out.println(test1.classVariable); // Prints "Changed class text"
        System.out.println(test2.classVariable); // Prints "Changed class text"
    }
}

How to update all MySQL table rows at the same time?

update mytable set online_status = 'online'

If you want to assign different values, you should use the TRANSACTION technique.

Using IS NULL or IS NOT NULL on join conditions - Theory question

Actually NULL filter is not being ignored. Thing is this is how joining two tables work.

I will try to walk down with the steps performed by database server to make it understand. For example when you execute the query which you said is ignoring the NULL condition. SELECT * FROM shipments s LEFT OUTER JOIN returns r
ON s.id = r.id AND r.id is null WHERE s.day >= CURDATE() - INTERVAL 10 DAY

1st thing happened is all the rows from table SHIPMENTS get selected

on next step database server will start selecting one by one record from 2nd(RETURNS) table.

on third step the record from RETURNS table will be qualified against the join conditions you have provided in the query which in this case is (s.id = r.id and r.id is NULL)

note that this qualification applied on third step only decides if server should accept or reject the current record of RETURNS table to append with the selected row of SHIPMENT table. It can in no way effect the selection of record from SHIPMENT table.

And once server is done with joining two tables which contains all the rows of SHIPMENT table and selected rows of RETURNS table it applies the where clause on the intermediate result. so when you put (r.id is NULL) condition in where clause than all the records from the intermediate result with r.id = null gets filtered out.

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

I know I'm coming to this very late. However, for anyone who's searching, I thought I'd publish what FINALLY worked for me. I'm not claiming it's the best solution - only that it worked.

Our WebApi service uses the config.EnableCors(corsAttribute) method. However, even with that, it would still fail on the pre-flight requests. @Mihai-Andrei Dinculescu's answer provided the clue for me. First of all, I added his Application_BeginRequest() code to flush the options requests. That STILL didn't work for me. The issue is that WebAPI still wasn't adding any of the expected headers to the OPTIONS request. Flushing it alone didn't work - but it gave me an idea. I added the custom headers that would otherwise be added via the web.config to the response for the OPTIONS request. Here's my code:

protected void Application_BeginRequest()
{
  if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
  {
    Response.Headers.Add("Access-Control-Allow-Origin", "https://localhost:44343");
    Response.Headers.Add("Access-Control-Allow-Headers",
      "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
    Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    Response.Headers.Add("Access-Control-Allow-Credentials", "true");
    Response.Flush();
  }
}

Obviously, this only applies to the OPTIONS requests. All other verbs are handled by the CORS configuration. If there's a better approach to this, I'm all ears. It feels like a cheat to me and I would prefer if the headers were added automatically, but this is what finally worked and allowed me to move on.

SQL Server after update trigger

First off, your trigger as you already see is going to update every record in the table. There is no filtering done to accomplish jus the rows changed.

Secondly, you're assuming that only one row changes in the batch which is incorrect as multiple rows could change.

The way to do this properly is to use the virtual inserted and deleted tables: http://msdn.microsoft.com/en-us/library/ms191300.aspx

JSON - Iterate through JSONArray

JsonArray jsonArray;
Iterator<JsonElement> it = jsonArray.iterator();
while(it.hasNext()){
    System.out.println(it.next());
}

How to compare DateTime without time via LINQ?

The Date property is not supported by LINQ to Entities -- you'll get an error if you try to use it on a DateTime field in a LINQ to Entities query. You can, however, trim dates using the DbFunctions.TruncateTime method.

var today = DateTime.Today;
var q = db.Games.Where(t => DbFunctions.TruncateTime(t.StartDate) >= today);

Simulate a specific CURL in PostMan

As per the above answers, it works well.

If we paste curl requests with Authorization data in import, Postman will set all headers automatically. We only just pass row JSON data in the request body if needed or Upload images through form-data in the body.

This is just an example. Your API should be a different one (if your API allows)

curl -X POST 'https://verifyUser.abc.com/api/v1/verification' \
    -H 'secret: secret' \
    -H 'email: [email protected]' \
    -H 'accept: application/json, text/plain, */*' \
    -H 'authorizationtoken: bearer' \
    -F 'referenceFilePath= Add file path' \
    --compressed

How can I send an Ajax Request on button click from a form with 2 buttons?

function sendAjaxRequest(element,urlToSend) {
             var clickedButton = element;
              $.ajax({type: "POST",
                  url: urlToSend,
                  data: { id: clickedButton.val(), access_token: $("#access_token").val() },
                  success:function(result){
                    alert('ok');
                  },
                 error:function(result)
                  {
                  alert('error');
                 }
             });
     }

       $(document).ready(function(){
          $("#button_1").click(function(e){
              e.preventDefault();
              sendAjaxRequest($(this),'/pages/test/');
          });

          $("#button_2").click(function(e){
              e.preventDefault();
              sendAjaxRequest($(this),'/pages/test/');
          });
        });
  1. created as separate function for sending the ajax request.
  2. Kept second parameter as URL because in future you want to send data to different URL

Maven: Failed to read artifact descriptor

I had the same issue with eclipse where the maven build command line worked just fine BUT try this

  • go into .m2/repository and wipe the directory associated
  • run update maven dependencies in eclipse

The error goes away....why my mvn command line worked with those directories and eclipse .m2eclipse could not, I have no idea and it kinda sucks. My project is now working in eclipse again.

Get the index of a certain value in an array in PHP

Could you be a little more specific?

$key = array_search('string2',$list)

works fine for me. Are you trying to accomplish something more complex?

How to convert string to integer in UNIX

The standard solution:

 expr $d1 - $d2

You can also do:

echo $(( d1 - d2 ))

but beware that this will treat 07 as an octal number! (so 07 is the same as 7, but 010 is different than 10).

Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

Source - http://coding.smashingmagazine.com/2009/06/02/fixed-vs-fluid-vs-elastic-layout-whats-the-right-one-for-you/

Pros

  • Fixed-width layouts are much easier to use and easier to customize in terms of design.
  • Widths are the same for every browser, so there is less hassle with images, forms, video and other content that are fixed-width.
  • There is no need for min-width or max-width, which isn’t supported by every browser anyway.
  • Even if a website is designed to be compatible with the smallest screen resolution, 800×600, the content will still be wide enough at a larger resolution to be easily legible.

Cons

  • A fixed-width layout may create excessive white space for users with larger screen resolutions, thus upsetting “divine proportion,” the “Rule of Thirds,” overall balance and other design principles.
  • Smaller screen resolutions may require a horizontal scroll bar, depending the fixed layout’s width.
  • Seamless textures, patterns and image continuation are needed to accommodate those with larger resolutions.
  • Fixed-width layouts generally have a lower overall score when it comes to usability.

What is the correct way to create a single-instance WPF application?

A time saving solution for C# Winforms...

Program.cs:

using System;
using System.Windows.Forms;
// needs reference to Microsoft.VisualBasic
using Microsoft.VisualBasic.ApplicationServices;  

namespace YourNamespace
{
    public class SingleInstanceController : WindowsFormsApplicationBase
    {
        public SingleInstanceController()
        {
            this.IsSingleInstance = true;
        }

        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e)
        {
            e.BringToForeground = true;
            base.OnStartupNextInstance(e);
        }

        protected override void OnCreateMainForm()
        {
            this.MainForm = new Form1();
        }
    }

    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            string[] args = Environment.GetCommandLineArgs();
            SingleInstanceController controller = new SingleInstanceController();
            controller.Run(args);
        }
    }
}

Running a single test from unittest.TestCase via the command line

TL;DR: This would very likely work:

python mypkg/tests/test_module.py MyCase.testItIsHot

The explanation:

  • The convenient way

      python mypkg/tests/test_module.py MyCase.testItIsHot
    

    would work, but its unspoken assumption is you already have this conventional code snippet inside (typically at the end of) your test file.

    if __name__ == "__main__":
        unittest.main()
    
  • The inconvenient way

      python -m unittest mypkg.tests.test_module.TestClass.test_method
    

    would always work, without requiring you to have that if __name__ == "__main__": unittest.main() code snippet in your test source file.

So why is the second method considered inconvenient? Because it would be a pain in the <insert one of your body parts here> to type that long, dot-delimited path by hand. While in the first method, the mypkg/tests/test_module.py part can be auto-completed, either by a modern shell, or by your editor.

How do I check if a number is a palindrome?

int is_palindrome(unsigned long orig)
{
    unsigned long reversed = 0, n = orig;

    while (n > 0)
    {
        reversed = reversed * 10 + n % 10;
        n /= 10;
    }

    return orig == reversed;
}

Test if registry value exists

If you are simply interested to know whether a registry value is present or not then how about:

[bool]((Get-itemproperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").PathName)

will return: $true while

[bool]((Get-itemproperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").ValueNotThere)

will return: $false as it's not there ;)

You could adapt it into a scriptblock like:

$CheckForRegValue = { Param([String]$KeyPath, [String]$KeyValue)
return [bool]((Get-itemproperty -Path $KeyPath).$KeyValue) }

and then just call it by:

& $CheckForRegValue "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" PathName

Have fun,

Porky

What is the dual table in Oracle?

It's a object to put in the from that return 1 empty row. For example: select 1 from dual; returns 1

select 21+44 from dual; returns 65

select [sequence].nextval from dual; returns the next value from the sequence.