Programs & Examples On #Profilecommon

Controller 'ngModel', required by directive '...', can't be found

I faced the same error, in my case I miss-spelled ng-model directive something like "ng-moel"

Wrong one: ng-moel="user.name" Right one: ng-model="user.name"

enter image description here

The network adapter could not establish the connection - Oracle 11g

I had the similar issue. its resolved for me with a simple command.

lsnrctl start

The Network Adapter exception is caused because:

  1. The database host name or port number is wrong (OR)
  2. The database TNSListener has not been started. The TNSListener may be started with the lsnrctl utility.

Try to start the listener using the command prompt:

  1. Click Start, type cmd in the search field, and when cmd shows up in the list of options, right click it and select ‘Run as Administrator’.
  2. At the Command Prompt window, type lsnrctl start without the quotes and press Enter.
  3. Type Exit and press Enter.

Hope it helps.

How do I get time of a Python program's execution?

Timeit is a class in Python used to calculate the execution time of small blocks of code.

Default_timer is a method in this class which is used to measure the wall clock timing, not CPU execution time. Thus other process execution might interfere with this. Thus it is useful for small blocks of code.

A sample of the code is as follows:

from timeit import default_timer as timer

start= timer()

# Some logic

end = timer()

print("Time taken:", end-start)

td widths, not working?

try this:

word-break: break-all;

How to integrate sourcetree for gitlab

If you have the generated SSH key for your project from GitLab you can add it to your keychain in OS X via terminal.

ssh-add -K <ssh_generated_key_file.txt>

Once executed you will be asked for the passphrase that you entered when creating the SSH key.

Once the SSH key is in the keychain you can paste the URL from GitLab into Sourcetree like you normally would to clone the project.

HTML input file selection event not firing upon selecting the same file

Use onClick event to clear value of target input, each time user clicks on field. This ensures that the onChange event will be triggered for the same file as well. Worked for me :)

onInputClick = (event) => {
    event.target.value = ''
}

<input type="file" onChange={onFileChanged} onClick={onInputClick} />

Using TypeScript

onInputClick = ( event: React.MouseEvent<HTMLInputElement, MouseEvent>) => {
    const element = event.target as HTMLInputElement
    element.value = ''
}

Clear text field value in JQuery

If you want to have element with visible blank text just do this:

$('#doc_title').html('&nbsp;');

ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

the problem might be that networkservice has no read rights

salution:

rightclick your upload folder -> poperty's -> security ->Edit -> add -> type :NETWORK SERVICE -> check box full control allow-> press ok or apply

How can I create a self-signed cert for localhost?

After spending a good amount of time on this issue I found whenever I followed suggestions of using IIS to make a self signed certificate, I found that the Issued To and Issued by was not correct. SelfSSL.exe was the key to solving this problem. The following website not only provided a step by step approach to making self signed certificates, but also solved the Issued To and Issued by problem. Here is the best solution I found for making self signed certificates. If you'd prefer to see the same tutorial in video form click here.

A sample use of SelfSSL would look something like the following:

SelfSSL /N:CN=YourWebsite.com /V:1000 /S:2

SelfSSL /? will provide a list of parameters with explanation.

How can I get an object's absolute position on the page in Javascript?

I would definitely suggest using element.getBoundingClientRect().

https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect

Summary

Returns a text rectangle object that encloses a group of text rectangles.

Syntax

var rectObject = object.getBoundingClientRect();

Returns

The returned value is a TextRectangle object which is the union of the rectangles returned by getClientRects() for the element, i.e., the CSS border-boxes associated with the element.

The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport.

Here's a browser compatibility table taken from the linked MDN site:

+---------------+--------+-----------------+-------------------+-------+--------+
|    Feature    | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
+---------------+--------+-----------------+-------------------+-------+--------+
| Basic support | 1.0    | 3.0 (1.9)       | 4.0               | (Yes) | 4.0    |
+---------------+--------+-----------------+-------------------+-------+--------+

It's widely supported, and is really easy to use, not to mention that it's really fast. Here's a related article from John Resig: http://ejohn.org/blog/getboundingclientrect-is-awesome/

You can use it like this:

var logo = document.getElementById('hlogo');
var logoTextRectangle = logo.getBoundingClientRect();

console.log("logo's left pos.:", logoTextRectangle.left);
console.log("logo's right pos.:", logoTextRectangle.right);

Here's a really simple example: http://jsbin.com/awisom/2 (you can view and edit the code by clicking "Edit in JS Bin" in the upper right corner).

Or here's another one using Chrome's console: Using element.getBoundingClientRect() in Chrome

Note:

I have to mention that the width and height attributes of the getBoundingClientRect() method's return value are undefined in Internet Explorer 8. It works in Chrome 26.x, Firefox 20.x and Opera 12.x though. Workaround in IE8: for width, you could subtract the return value's right and left attributes, and for height, you could subtract bottom and top attributes (like this).

Fastest way to convert an iterator to a list

since python 3.5 you can use * iterable unpacking operator:

user_list = [*your_iterator]

but the pythonic way to do it is:

user_list  = list(your_iterator)

Error - replacement has [x] rows, data has [y]

You could use cut

 df$valueBin <- cut(df$value, c(-Inf, 250, 500, 1000, 2000, Inf), 
    labels=c('<=250', '250-500', '500-1,000', '1,000-2,000', '>2,000'))

data

 set.seed(24)
 df <- data.frame(value= sample(0:2500, 100, replace=TRUE))

PHP Include for HTML?

Here is the step by step process to include php code in html file ( Tested )

If PHP is working there is only one step left to use PHP scripts in files with *.html or *.htm extensions as well. The magic word is ".htaccess". Please see the Wikipedia definition of .htaccess to learn more about it. According to Wikipedia it is "a directory-level configuration file that allows for decentralized management of web server configuration."

You can probably use such a .htaccess configuration file for your purpose. In our case you want the webserver to parse HTML files like PHP files.

First, create a blank text file and name it ".htaccess". You might ask yourself why the file name starts with a dot. On Unix-like systems this means it is a dot-file is a hidden file. (Note: If your operating system does not allow file names starting with a dot just name the file "xyz.htaccess" temporarily. As soon as you have uploaded it to your webserver in a later step you can rename the file online to ".htaccess") Next, open the file with a simple text editor like the "Editor" in MS Windows. Paste the following line into the file: AddType application/x-httpd-php .html .htm If this does not work, please remove the line above from your file and paste this alternative line into it, for PHP5: AddType application/x-httpd-php5 .html .htm Now upload the .htaccess file to the root directory of your webserver. Make sure that the name of the file is ".htaccess". Your webserver should now parse *.htm and *.html files like PHP files.

You can try if it works by creating a HTML-File like the following. Name it "php-in-html-test.htm", paste the following code into it and upload it to the root directory of your webserver:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
     <HTML>
 <HEAD>
 <TITLE>Use PHP in HTML files</TITLE>
 </HEAD>

   <BODY>
    <h1>
    <?php echo "It works!"; ?>
    </h1>
  </BODY>
 </HTML>

Try to open the file in your browser by typing in: http://www.your-domain.com/php-in-html-test.htm (once again, please replace your-domain.com by your own domain...) If your browser shows the phrase "It works!" everything works fine and you can use PHP in .*html and *.htm files from now on. However, if not, please try to use the alternative line in the .htaccess file as we showed above. If is still does not work please contact your hosting provider.

How to generate random number with the specific length in python

You could create a function who consumes an list of int, transforms in string to concatenate and cast do int again, something like this:

import random

def generate_random_number(length):
    return int(''.join([str(random.randint(0,10)) for _ in range(length)]))

Get single row result with Doctrine NativeQuery

You can use $query->getSingleResult(), which will throw an exception if more than one result are found, or if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L791)

There's also the less famous $query->getOneOrNullResult() which will throw an exception if more than one result are found, and return null if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L752)

Java, how to compare Strings with String Arrays

import java.util.Scanner;
import java.util.*;
public class Main
{
  public static void main (String[]args) throws Exception
  {
    Scanner in = new Scanner (System.in);
    /*Prints out the welcome message at the top of the screen */
      System.out.printf ("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
      System.out.printf ("%55s", "=================================\n");

      String[] codes =
    {
    "G22", "K13", "I30", "S20"};

      System.out.printf ("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2],
             codes[3]);
      System.out.printf ("Enter one of the above!\n");

    String usercode = in.nextLine ();
    for (int i = 0; i < codes.length; i++)
      {
    if (codes[i].equals (usercode))
      {
        System.out.printf ("What's the matter with you?\n");
      }
    else
      {
        System.out.printf ("Youda man!");
      }
      }

  }
}

Entityframework Join using join method and lambdas

You can find a few examples here:

// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);

DataTable contacts = ds.Tables["Contact"];
DataTable orders = ds.Tables["SalesOrderHeader"];

var query =
    contacts.AsEnumerable().Join(orders.AsEnumerable(),
    order => order.Field<Int32>("ContactID"),
    contact => contact.Field<Int32>("ContactID"),
    (contact, order) => new
    {
        ContactID = contact.Field<Int32>("ContactID"),
        SalesOrderID = order.Field<Int32>("SalesOrderID"),
        FirstName = contact.Field<string>("FirstName"),
        Lastname = contact.Field<string>("Lastname"),
        TotalDue = order.Field<decimal>("TotalDue")
    });


foreach (var contact_order in query)
{
    Console.WriteLine("ContactID: {0} "
                    + "SalesOrderID: {1} "
                    + "FirstName: {2} "
                    + "Lastname: {3} "
                    + "TotalDue: {4}",
        contact_order.ContactID,
        contact_order.SalesOrderID,
        contact_order.FirstName,
        contact_order.Lastname,
        contact_order.TotalDue);
}

Or just google for 'linq join method syntax'.

Reading a column from CSV file using JAVA

Splitting by comma doesn't work all the time for instance if you have csv file like

"Name" , "Job" , "Address"
"Pratiyush, Singh" , "Teacher" , "Berlin, Germany"

So, I would recommend using the Apache Commons CSV API:

    Reader in = new FileReader("input1.csv");
    Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
    for (CSVRecord record : records) {
      System.out.println(record.get(0));
    }

How do I make a simple makefile for gcc on Linux?

Depending on the number of headers and your development habits, you may want to investigate gccmakedep. This program examines your current directory and adds to the end of the makefile the header dependencies for each .c/cpp file. This is overkill when you have 2 headers and one program file. However, if you have 5+ little test programs and you are editing one of 10 headers, you can then trust make to rebuild exactly those programs which were changed by your modifications.

Java method: Finding object in array list given a known attribute value

I was interested to see that the original poster used a style that avoided early exits. Single Entry; Single Exit (SESE) is an interesting style that I've not really explored. It's late and I've got a bottle of cider, so I've written a solution (not tested) without an early exit.

I should have used an iterator. Unfortunately java.util.Iterator has a side-effect in the get method. (I don't like the Iterator design due to its exception ramifications.)

private Dog findDog(int id) {
    int i = 0;
    for (; i!=dogs.length() && dogs.get(i).getID()!=id; ++i) {
        ;
    }

    return i!=dogs.length() ? dogs.get(i) : null;
}

Note the duplication of the i!=dogs.length() expression (could have chosen dogs.get(i).getID()!=id).

UIScrollView not scrolling

If your scrollView is a subview of a containerView of some type, then make sure that your scrollView is within the frame or bounds of the containerView. I had containerView.clipsToBounds = NO which still allowed me see the scrollView, but because scrollView wasn't within the bounds of containerView it wouldn't detect touch events.

For example:

containerView.frame = CGRectMake(0, 0, 200, 200);
scrollView.frame = CGRectMake(0, 200, 200, 200);
[containerView addSubview:scrollView];
scrollView.userInteractionEnabled = YES;

You will be able to see the scrollView but it won't receive user interactions.

Regex, every non-alphanumeric character except white space or colon

In JavaScript:

/[^\w_]/g

^ negation, i.e. select anything not in the following set

\w any word character (i.e. any alphanumeric character, plus underscore)

_ negate the underscore, as it's considered a 'word' character

Usage example - const nonAlphaNumericChars = /[^\w_]/g;

Reactive forms - disabled attribute

in Angular-9 if you want to disable/enable on button click here is a simple solution if you are using reactive forms.

define a function in component.ts file

//enable example you can use the same approach for disable with .disable()

toggleEnable() {
  this.yourFormName.controls.formFieldName.enable();
  console.log("Clicked")
} 

Call it from your component.html

e.g

<button type="button" data-toggle="form-control" class="bg-primary text-white btn- 
                reset" style="width:100%"(click)="toggleEnable()">

Check if a string isn't nil or empty in Lua

Can this code be simplified in one if test instead two?

nil and '' are different values. If you need to test that s is neither, IMO you should just compare against both, because it makes your intent the most clear.

That and a few alternatives, with their generated bytecode:

if not foo or foo == '' then end
     GETGLOBAL       0 -1    ; foo
     TEST            0 0 0
     JMP             3       ; to 7
     GETGLOBAL       0 -1    ; foo
     EQ              0 0 -2  ; - ""
     JMP             0       ; to 7

if foo == nil or foo == '' then end
    GETGLOBAL       0 -1    ; foo
    EQ              1 0 -2  ; - nil
    JMP             3       ; to 7
    GETGLOBAL       0 -1    ; foo
    EQ              0 0 -3  ; - ""
    JMP             0       ; to 7

if (foo or '') == '' then end
   GETGLOBAL       0 -1    ; foo
   TEST            0 0 1
   JMP             1       ; to 5
   LOADK           0 -2    ; ""
   EQ              0 0 -2  ; - ""
   JMP             0       ; to 7

The second is fastest in Lua 5.1 and 5.2 (on my machine anyway), but difference is tiny. I'd go with the first for clarity's sake.

PHP - Notice: Undefined index:

How are you loading this page? Is it getting anything on POST to load? If it's not, then the $name = $_POST['Name']; assignation doesn't have any 'Name' on POST.

Cannot open include file with Visual Studio

If your problem is still there it's certainly because you are trying to compile a different version from your current settings.

For example if you set your Additional Include Directories in Debug x64, be sure that you are compiling with the same configuration.

Check this: Build > Configuration Manager... > There is problably something like this in your active solution configuration: Debug x86 (Win32) platform.

Top 5 time-consuming SQL queries in Oracle

The following query returns SQL statements that perform large numbers of disk reads (also includes the offending user and the number of times the query has been run):

SELECT t2.username, t1.disk_reads, t1.executions,
    t1.disk_reads / DECODE(t1.executions, 0, 1, t1.executions) as exec_ratio,
    t1.command_type, t1.sql_text
  FROM v$sqlarea t1, dba_users t2
  WHERE t1.parsing_user_id = t2.user_id
    AND t1.disk_reads > 100000
  ORDER BY t1.disk_reads DESC

Run the query as SYS and adjust the number of disk reads depending on what you deem to be excessive (100,000 works for me).

I have used this query very recently to track down users who refuse to take advantage of Explain Plans before executing their statements.

I found this query in an old Oracle SQL tuning book (which I unfortunately no longer have), so apologies, but no attribution.

Parsing query strings on Android

Just for reference, this is what I've ended up with (based on URLEncodedUtils, and returning a Map).

Features:

  • it accepts the query string part of the url (you can use request.getQueryString())
  • an empty query string will produce an empty Map
  • a parameter without a value (?test) will be mapped to an empty List<String>

Code:

public static Map<String, List<String>> getParameterMapOfLists(String queryString) {
    Map<String, List<String>> mapOfLists = new HashMap<String, List<String>>();
    if (queryString == null || queryString.length() == 0) {
        return mapOfLists;
    }
    List<NameValuePair> list = URLEncodedUtils.parse(URI.create("http://localhost/?" + queryString), "UTF-8");
    for (NameValuePair pair : list) {
        List<String> values = mapOfLists.get(pair.getName());
        if (values == null) {
            values = new ArrayList<String>();
            mapOfLists.put(pair.getName(), values);
        }
        if (pair.getValue() != null) {
            values.add(pair.getValue());
        }
    }

    return mapOfLists;
}

A compatibility helper (values are stored in a String array just as in ServletRequest.getParameterMap()):

public static Map<String, String[]> getParameterMap(String queryString) {
    Map<String, List<String>> mapOfLists = getParameterMapOfLists(queryString);

    Map<String, String[]> mapOfArrays = new HashMap<String, String[]>();
    for (String key : mapOfLists.keySet()) {
        mapOfArrays.put(key, mapOfLists.get(key).toArray(new String[] {}));
    }

    return mapOfArrays;
}

Create new XML file and write data to it?

PHP has several libraries for XML Manipulation.

The Document Object Model (DOM) approach (which is a W3C standard and should be familiar if you've used it in other environments such as a Web Browser or Java, etc). Allows you to create documents as follows

<?php
    $doc = new DOMDocument( );
    $ele = $doc->createElement( 'Root' );
    $ele->nodeValue = 'Hello XML World';
    $doc->appendChild( $ele );
    $doc->save('MyXmlFile.xml');
?>

Even if you haven't come across the DOM before, it's worth investing some time in it as the model is used in many languages/environments.

Where does Jenkins store configuration files for the jobs it runs?

Jenkins 1.627, OS X 10.10.5 /Users/Shared/Jenkins/Home/jobs/{project_name}/config.xml

How do I align a label and a textarea?

You need to put them both in some container element and then apply the alignment on it.

For example:

_x000D_
_x000D_
.formfield * {_x000D_
  vertical-align: middle;_x000D_
}
_x000D_
<p class="formfield">_x000D_
  <label for="textarea">Label for textarea</label>_x000D_
  <textarea id="textarea" rows="5">Textarea</textarea>_x000D_
</p>
_x000D_
_x000D_
_x000D_

Create dynamic URLs in Flask with url_for()

Refer to the Flask API document for flask.url_for()

Other sample snippets of usage for linking js or css to your template are below.

<script src="{{ url_for('static', filename='jquery.min.js') }}"></script>

<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">

How do you query for "is not null" in Mongo?

the Query Will be

db.mycollection.find({"IMAGE URL":{"$exists":"true"}})

it will return all documents having "IMAGE URL" as a key ...........

How to install maven on redhat linux

Installing maven in Amazon Linux / redhat

--> sudo wget http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo

--> sudo sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo

-->sudo yum install -y apache-maven

--> mvn --version

Output looks like


Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T07:58:13Z) Maven home: /usr/share/apache-maven Java version: 1.8.0_171, vendor: Oracle Corporation Java home: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.amzn2.x86_64/jre Default locale: en_US, platform encoding: UTF-8 OS name: "linux", version: "4.14.47-64.38.amzn2.x86_64", arch: "amd64", family: "unix"

*If its thrown error related to java please follow the below step to update java 8 *

Installing java 8 in amazon linux/redhat

--> yum search java | grep openjdk

--> yum install java-1.8.0-openjdk-headless.x86_64

--> yum install java-1.8.0-openjdk-devel.x86_64

--> update-alternatives --config java #pick java 1.8 and press 1

--> update-alternatives --config javac #pick java 1.8 and press 2

Thank You

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

Composer Update Laravel

write this command in your terminal :

composer update

Setting state on componentDidMount()

According to the React Documentation it's perfectly OK to call setState() from within the componentDidMount() function.

It will cause render() to be called twice, which is less efficient than only calling it once, but other than that it's perfectly fine.

You can find the documentation here:

https://reactjs.org/docs/react-component.html#componentdidmount

Here is the excerpt from the documentation:

You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues...

How to use execvp()

The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.

For example:

char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;

execvp(cmd, argv); //This will run "ls -la" as if it were a command

How do I install Python packages on Windows?

PS D:\simcut>  C:\Python27\Scripts\pip.exe install networkx
Collecting networkx
c:\python27\lib\site-packages\pip\_vendor\requests\packages\urllib3\util\ssl_.py:318: SNIMissingWarning: An HTTPS reques
t has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may caus
e the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer ve
rsion of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#snimissi
ngwarning.
  SNIMissingWarning
c:\python27\lib\site-packages\pip\_vendor\requests\packages\urllib3\util\ssl_.py:122: InsecurePlatformWarning: A true SS
LContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL con
nections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.
readthedocs.io/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
  Downloading networkx-1.11-py2.py3-none-any.whl (1.3MB)
    100% |################################| 1.3MB 664kB/s
Collecting decorator>=3.4.0 (from networkx)
  Downloading decorator-4.0.11-py2.py3-none-any.whl
Installing collected packages: decorator, networkx
Successfully installed decorator-4.0.11 networkx-1.11
c:\python27\lib\site-packages\pip\_vendor\requests\packages\urllib3\util\ssl_.py:122: InsecurePlatformWarning: A true SSLContext object i
s not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade
to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#insecureplat
formwarning.
  InsecurePlatformWarning

Or just put the directory to your pip executable in your system path.

How to declare an array inside MS SQL Server Stored Procedure?

Is there a reason why you aren't using a table variable and the aggregate SUM operator, instead of a cursor? SQL excels at set-oriented operations. 99.87% of the time that you find yourself using a cursor, there's a set-oriented alternative that's more efficient:

declare @MonthsSale table
(
MonthNumber int,
MonthName varchar(9),
MonthSale decimal(18,2)
)

insert into @MonthsSale
select
    1, 'January', 100.00
union select    
    2, 'February', 200.00
union select    
    3, 'March', 300.00
union select    
    4, 'April', 400.00
union select    
    5, 'May', 500.00
union select    
    6, 'June', 600.00
union select    
    7, 'July', 700.00
union select    
    8, 'August', 800.00
union select    
    9, 'September', 900.00
union select    
    10, 'October', 1000.00
union select    
    11, 'November', 1100.00
union select    
    12, 'December', 1200.00

select * from @MonthsSale   
select SUM(MonthSale) as [TotalSales] from @MonthsSale

Why is semicolon allowed in this python snippet?

Semicolons are part of valid syntax: 8. Compound statements (The Python Language Reference)

Microsoft.ACE.OLEDB.12.0 provider is not registered

I have a visual Basic program with Visual Studio 2008 that uses an Access 2007 database and was receiving the same error. I found some threads that advised changing the advanced compile configuration to x86 found in the programs properties if you're running a 64 bit system. So far I haven't had any problems with my program since.

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

Calculating and printing the nth prime number

I just added the missing lines in your own thought process.

static int nthPrimeFinder(int n) {

        int counter = 1; // For 1 and 2. assuming n is not 1 or 2.
        int i = 2;
        int x = 2;
        int tempLength = n;

        while (counter <= n) {
            for (; i <= tempLength; i++) {
                for (x = 2; x < i; x++) {
                    if (i % x == 0) {
                        break;
                    }
                }
                if (x == i && counter < n) {
                    //System.out.printf("\n%d is prime", x);
                    counter++;
                    if (counter == n) {
                        System.out.printf("\n%d is prime", x);
                        return counter;
                    }
                }
            }
            tempLength = tempLength+n;
        }
        return 0;
    }

How to call stopservice() method of Service class from the calling activity class

I actually used pretty much the same code as you above. My service registration in the manifest is the following

<service android:name=".service.MyService" android:enabled="true">
            <intent-filter android:label="@string/menuItemStartService" >
                <action android:name="it.unibz.bluedroid.bluetooth.service.MY_SERVICE"/>
            </intent-filter>
        </service>

In the service class I created an according constant string identifying the service name like:

public class MyService extends ForeGroundService {
    public static final String MY_SERVICE = "it.unibz.bluedroid.bluetooth.service.MY_SERVICE";
   ...
}

and from the according Activity I call it with

startService(new Intent(MyService.MY_SERVICE));

and stop it with

stopService(new Intent(MyService.MY_SERVICE));

It works perfectly. Try to check your configuration and if you don't find anything strange try to debug whether your stopService get's called properly.

Best way to check if a URL is valid

Using filter_var() will fail for urls with non-ascii chars, e.g. (http://pt.wikipedia.org/wiki/Guimarães). The following function encode all non-ascii chars (e.g. http://pt.wikipedia.org/wiki/Guimar%C3%A3es) before calling filter_var().

Hope this helps someone.

<?php

function validate_url($url) {
    $path = parse_url($url, PHP_URL_PATH);
    $encoded_path = array_map('urlencode', explode('/', $path));
    $url = str_replace($path, implode('/', $encoded_path), $url);

    return filter_var($url, FILTER_VALIDATE_URL) ? true : false;
}

// example
if(!validate_url("http://somedomain.com/some/path/file1.jpg")) {
    echo "NOT A URL";
}
else {
    echo "IS A URL";
}

How do I detect whether a Python variable is a function?

The solutions using hasattr(obj, '__call__') and callable(.) mentioned in some of the answers have a main drawback: both also return True for classes and instances of classes with a __call__() method. Eg.

>>> import collections
>>> Test = collections.namedtuple('Test', [])
>>> callable(Test)
True
>>> hasattr(Test, '__call__')
True

One proper way of checking if an object is a user-defined function (and nothing but a that) is to use isfunction(.):

>>> import inspect
>>> inspect.isfunction(Test)
False
>>> def t(): pass
>>> inspect.isfunction(t)
True

If you need to check for other types, have a look at inspect — Inspect live objects.

Setting Inheritance and Propagation flags with set-acl and powershell

Just because you're in PowerShell don't forgot about good ol' exes. Sometimes they can provide the easiest solution e.g.:

icacls.exe $folder /grant 'domain\user:(OI)(CI)(M)'

Create a new line in Java's FileWriter

If you mean use the same code but add a new line so that when you add something to the file it will be on a new line. You can simply use BufferedWriter's newLine().
Here I have Improved you code also: NumberFormatException was unnecessary as nothing was being cast to a number data type, saving variables to use once also was.

try {
    BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"));
        writer.write(jTextField1.getText());
        writer.write(jTextField2.getText());
        writer.newLine();
        writer.flush();
        writer.close();
} catch (IOException ex) {
    System.out.println("File could not be created");
}

Difference between del, remove, and pop on lists

The remove operation on a list is given a value to remove. It searches the list to find an item with that value and deletes the first matching item it finds. It is an error if there is no matching item, raises a ValueError.

>>> x = [1, 0, 0, 0, 3, 4, 5]
>>> x.remove(4)
>>> x
[1, 0, 0, 0, 3, 5]
>>> del x[7]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    del x[7]
IndexError: list assignment index out of range

The del statement can be used to delete an entire list. If you have a specific list item as your argument to del (e.g. listname[7] to specifically reference the 8th item in the list), it'll just delete that item. It is even possible to delete a "slice" from a list. It is an error if there index out of range, raises a IndexError.

>>> x = [1, 2, 3, 4]
>>> del x[3]
>>> x
[1, 2, 3]
>>> del x[4]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    del x[4]
IndexError: list assignment index out of range

The usual use of pop is to delete the last item from a list as you use the list as a stack. Unlike del, pop returns the value that it popped off the list. You can optionally give an index value to pop and pop from other than the end of the list (e.g listname.pop(0) will delete the first item from the list and return that first item as its result). You can use this to make the list behave like a queue, but there are library routines available that can provide queue operations with better performance than pop(0) does. It is an error if there index out of range, raises a IndexError.

>>> x = [1, 2, 3] 
>>> x.pop(2) 
3 
>>> x 
[1, 2]
>>> x.pop(4)
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    x.pop(4)
IndexError: pop index out of range

See collections.deque for more details.

Swift - Split string over multiple lines

You can using unicode equals for enter or \n and implement them inside you string. For example: \u{0085}.

strcpy() error in Visual studio 2012

Add this line top of the header

#pragma warning(disable : 4996)

In .NET, which loop runs faster, 'for' or 'foreach'?

you can read about it in Deep .NET - part 1 Iteration

it's cover the results (without the first initialization) from .NET source code all the way to the disassembly.

for example - Array Iteration with a foreach loop: enter image description here

and - list iteration with foreach loop: enter image description here

and the end results: enter image description here

enter image description here

Call method when home button pressed

The HOME button cannot be intercepted by applications. This is a by-design behavior in Android. The reason is to prevent malicious apps from gaining control over your phone (If the user cannot press back or home, he might never be able to exit the app). The Home button is considered the user's "safe zone" and will always launch the user's configured home app.

The only exception to the above is any app configured as home replacement. Which means it has the following declared in its AndroidManifest.xml for the relevant activity:

<intent-filter>
   <action android:name="android.intent.action.MAIN" />
   <category android:name="android.intent.category.HOME" />
   <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

When pressing the home button, the current home app's activity's onNewIntent will be called.

Embed Youtube video inside an Android app

Embedding the YouTube player in Android is very simple & it hardly takes you 10 minutes,

1) Enable YouTube API from Google API console
2) Download YouTube player Jar file
3) Start using it in Your app

Here are the detailed steps http://www.feelzdroid.com/2017/01/embed-youtube-video-player-android-app-example.html.

Just refer it & if you face any problem, let me know, ill help you

How to upload a project to Github

It took me like 2 hours to realize that I'm supposed to create Repo to GitHub (http://github.com/new) before trying to push my local files to github.

After trying to push errors were like:

remote: Repository not found.
fatal: repository 'https://github.com/username/project.git/' not found

I feel like an idiot, but I really would like to emphasize this. I just thought that my repo will be created automatically during the first push. I was so wrong.

Excel to JSON javascript code?

js-xlsx library makes it easy to convert Excel/CSV files into JSON objects.

Download the xlsx.full.min.js file from here. Write below code on your HTML page Edit the referenced js file link (xlsx.full.min.js) and link of Excel file

<!doctype html>
<html>

<head>
    <title>Excel to JSON Demo</title>
    <script src="xlsx.full.min.js"></script>
</head>

<body>

    <script>
        /* set up XMLHttpRequest */
        var url = "http://myclassbook.org/wp-content/uploads/2017/12/Test.xlsx";
        var oReq = new XMLHttpRequest();
        oReq.open("GET", url, true);
        oReq.responseType = "arraybuffer";

        oReq.onload = function(e) {
            var arraybuffer = oReq.response;

            /* convert data to binary string */
            var data = new Uint8Array(arraybuffer);
            var arr = new Array();
            for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
            var bstr = arr.join("");

            /* Call XLSX */
            var workbook = XLSX.read(bstr, {
                type: "binary"
            });

            /* DO SOMETHING WITH workbook HERE */
            var first_sheet_name = workbook.SheetNames[0];
            /* Get worksheet */
            var worksheet = workbook.Sheets[first_sheet_name];
            console.log(XLSX.utils.sheet_to_json(worksheet, {
                raw: true
            }));
        }

        oReq.send();
    </script>
</body>
</html>

Input:
Click here to see the input Excel file

Output:
Click here to see the output of above code

How do I manage MongoDB connections in a Node.js web application?

I have implemented below code in my project to implement connection pooling in my code so it will create a minimum connection in my project and reuse available connection

/* Mongo.js*/

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/yourdatabasename"; 
var assert = require('assert');

var connection=[];
// Create the database connection
establishConnection = function(callback){

                MongoClient.connect(url, { poolSize: 10 },function(err, db) {
                    assert.equal(null, err);

                        connection = db
                        if(typeof callback === 'function' && callback())
                            callback(connection)

                    }

                )



}

function getconnection(){
    return connection
}

module.exports = {

    establishConnection:establishConnection,
    getconnection:getconnection
}

/*app.js*/
// establish one connection with all other routes will use.
var db = require('./routes/mongo')

db.establishConnection();

//you can also call with callback if you wanna create any collection at starting
/*
db.establishConnection(function(conn){
  conn.createCollection("collectionName", function(err, res) {
    if (err) throw err;
    console.log("Collection created!");
  });
};
*/

// anyother route.js

var db = require('./mongo')

router.get('/', function(req, res, next) {
    var connection = db.getconnection()
    res.send("Hello");

});

How to scroll the window using JQuery $.scrollTo() function

jQuery now supports scrollTop as an animation variable.

$("#id").animate({"scrollTop": $("#id").scrollTop() + 100});

You no longer need to setTimeout/setInterval to scroll smoothly.

datatable jquery - table header width not aligned with body width

CAUSE

Most likely your table is hidden initially which prevents jQuery DataTables from calculating column widths.

SOLUTION

  • If table is in the collapsible element, you need to adjust headers when collapsible element becomes visible.

    For example, for Bootstrap Collapse plugin:

    $('#myCollapsible').on('shown.bs.collapse', function () {
       $($.fn.dataTable.tables(true)).DataTable()
          .columns.adjust();
    });
    
  • If table is in the tab, you need to adjust headers when tab becomes visible.

    For example, for Bootstrap Tab plugin:

    $('a[data-toggle="tab"]').on('shown.bs.tab', function(e){
       $($.fn.dataTable.tables(true)).DataTable()
          .columns.adjust();
    });
    

Code above adjusts column widths for all tables on the page. See columns().adjust() API methods for more information.

RESPONSIVE, SCROLLER OR FIXEDCOLUMNS EXTENSIONS

If you're using Responsive, Scroller or FixedColumns extensions, you need to use additional API methods to solve this problem.

LINKS

See jQuery DataTables – Column width issues with Bootstrap tabs for solutions to the most common problems with columns in jQuery DataTables when table is initially hidden.

Opacity CSS not working in IE8

Using display: inline-block; works on IE8 to resolve this problem.

FWIW, opacity: 0.75 works on all standards-compliant browsers.

Get keys from HashMap in Java

As you would like to get argument (United) for which value is given (5) you might also consider using bidirectional map (e.g. provided by Guava: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/BiMap.html).

Update records in table from CTE

WITH CTE_DocTotal (DocTotal, InvoiceNumber)
AS
(
    SELECT  InvoiceNumber,
            SUM(Sale + VAT) AS DocTotal
    FROM    PEDI_InvoiceDetail
    GROUP BY InvoiceNumber
)    
UPDATE PEDI_InvoiceDetail
SET PEDI_InvoiceDetail.DocTotal = CTE_DocTotal.DocTotal
FROM CTE_DocTotal
INNER JOIN PEDI_InvoiceDetail ON ...

How to enable GZIP compression in IIS 7.5

GZip Compression can be enabled directly through IIS.

First, open up IIS,

go to the website you are hoping to tweak and hit the Compression page. If Gzip is not installed, you will see something like the following:

iis-gzip

“The dynamic content compression module is not installed.” We should fix this. So we go to the “Turn Windows features on or off” and select “Dynamic Content Compression” and click the OK button.

Now if we go back to IIS, we should see that the compression page has changed. At this point we need to make sure the dynamic compression checkbox is checked and we’re good to go. Compression is enabled and our dynamic content will be Gzipped.

Testing - Check if GZIP Compression is Enabled

To test whether compression is working or not, use the developer tools in Chrome or Firebug for Firefox and ensure the HTTP response header is set:

Content-Encoding: gzip

SQL Query for Student mark functionality

SELECT          subjectname,
                studentname 
FROM            student s 
INNER JOIN      mark m 
  ON            s.studid = m.studid 
INNER JOIN      subject su 
  ON            su.subjectid = m.subjectid 
INNER JOIN (
  SELECT        subjectid,
                max(value) AS maximum 
  FROM          mark 
  GROUP BY      subjectid
)               highmark h 
  ON            h.subjectid = m.subjectid 
  AND           h.maximum = m.value;

INSERT with SELECT

Sure, what do you want to use for the gid? a static value, PHP var, ...

A static value of 1234 could be like:

INSERT INTO courses (name, location, gid)
SELECT name, location, 1234
FROM courses
WHERE cid = $cid

How to obtain the start time and end time of a day?

For java 8 the following single line statements are working. In this example I use UTC timezone. Please consider to change TimeZone that you currently used.

System.out.println(new Date());

final LocalDateTime endOfDay       = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
final Date          endOfDayAsDate = Date.from(endOfDay.toInstant(ZoneOffset.UTC));

System.out.println(endOfDayAsDate);

final LocalDateTime startOfDay       = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
final Date          startOfDayAsDate = Date.from(startOfDay.toInstant(ZoneOffset.UTC));

System.out.println(startOfDayAsDate);

If no time difference with output. Try: ZoneOffset.ofHours(0)

Conditional Replace Pandas

The reason your original dataframe does not update is because chained indexing may cause you to modify a copy rather than a view of your dataframe. The docs give this advice:

When setting values in a pandas object, care must be taken to avoid what is called chained indexing.

You have a few alternatives:-

loc + Boolean indexing

loc may be used for setting values and supports Boolean masks:

df.loc[df['my_channel'] > 20000, 'my_channel'] = 0

mask + Boolean indexing

You can assign to your series:

df['my_channel'] = df['my_channel'].mask(df['my_channel'] > 20000, 0)

Or you can update your series in place:

df['my_channel'].mask(df['my_channel'] > 20000, 0, inplace=True)

np.where + Boolean indexing

You can use NumPy by assigning your original series when your condition is not satisfied; however, the first two solutions are cleaner since they explicitly change only specified values.

df['my_channel'] = np.where(df['my_channel'] > 20000, 0, df['my_channel'])

Trigger event on body load complete js/jquery

jQuery:

$(function(){
  // your code...this will run when DOM is ready
});

If you want to run your code after all page resources including images/frames/DOM have loaded, you need to use load event:

$(window).load(function(){
  // your code...
});

JavaScript:

window.onload = function(){
  // your code...
};

Cannot overwrite model once compiled Mongoose

The schema definition should be unique for a collection, it should not be more then one schema for a collection.

How do I UPDATE from a SELECT in SQL Server?

This may be a niche reason to perform an update (for example, mainly used in a procedure), or may be obvious to others, but it should also be stated that you can perform an update-select statement without using join (in case the tables you're updating between have no common field).

update
    Table
set
    Table.example = a.value
from
    TableExample a
where
    Table.field = *key value* -- finds the row in Table 
    AND a.field = *key value* -- finds the row in TableExample a

JQuery style display value

Well, for one thing your epression can be simplified:

$("#pDetails").attr("style")

since there should only be one element for any given ID and the ID selector will be much faster than the attribute id selector you're using.

If you just want to return the display value or something, use css():

$("#pDetails").css("display")

If you want to search for elements that have display none, that's a lot harder to do reliably. This is a rough example that won't be 100%:

$("[style*='display: none']")

but if you just want to find things that are hidden, use this:

$(":hidden")

Fatal error: Namespace declaration statement has to be the very first statement in the script in

If you look this file Namespace is not the first statement.

<?php
class BulletProofException extends Exception{}

namespace BulletProof;

You can try to move the namespace over the class definition.

Make absolute positioned div expand parent div height

Although stretching to elements with position: absolute is not possible, there are often solutions where you can avoid the absolute positioning while obtaining the same effect. Look at this fiddle that solves the problem in your particular case http://jsfiddle.net/gS9q7/

The trick is to reverse element order by floating both elements, the first to the right, the second to the left, so the second appears first.

.child1 {
    width: calc(100% - 160px);
    float: right;
}
.child2 {
    width: 145px;
    float: left;
}

Finally, add a clearfix to the parent and you're done (see the fiddle for the complete solution).

Generally, as long as the element with absolute position is positioned at the top of the parent element, chances are good that you find a workaround by floating the element.

Display unescaped HTML in Vue.js

You have to use v-html directive for displaying html content inside a vue component

<div v-html="html content data property"></div>

How to use mongoose findOne

You might want to consider using console.log with the built-in "arguments" object:

console.log(arguments); // would have shown you [0] null, [1] yourResult

This will always output all of your arguments, no matter how many arguments you have.

How to use OR condition in a JavaScript IF statement?

More then one condition statement is needed to use OR(||) operator in if conditions and notation is ||.

if(condition || condition){ 
   some stuff
}

Error handling in C code

Here is an approach which I think is interesting, while requiring some discipline.

This assumes a handle-type variable is the instance on which operate all API functions.

The idea is that the struct behind the handle stores the previous error as a struct with necessary data (code, message...), and the user is provided with a function that returns a pointer to this error object. Each operation will update the pointed object so the user can check its status without even calling functions. As opposed to the errno pattern, the error code is not global, which make the approach thread-safe, as long as each handle is properly used.

Example:

MyHandle * h = MyApiCreateHandle();

/* first call checks for pointer nullity, since we cannot retrieve error code
   on a NULL pointer */
if (h == NULL)
     return 0; 

/* from here h is a valid handle */

/* get a pointer to the error struct that will be updated with each call */
MyApiError * err = MyApiGetError(h);

MyApiFileDescriptor * fd = MyApiOpenFile("/path/to/file.ext");

/* we want to know what can go wrong */
if (err->code != MyApi_ERROR_OK) {
    fprintf(stderr, "(%d) %s\n", err->code, err->message);
    MyApiDestroy(h);
    return 0;
}

MyApiRecord record;

/* here the API could refuse to execute the operation if the previous one
   yielded an error, and eventually close the file descriptor itself if
   the error is not recoverable */
MyApiReadFileRecord(h, &record, sizeof(record));

/* we want to know what can go wrong, here using a macro checking for failure */
if (MyApi_FAILED(err)) {
    fprintf(stderr, "(%d) %s\n", err->code, err->message);
    MyApiDestroy(h);
    return 0;
}

SQL changing a value to upper or lower case

SQL SERVER 2005:

print upper('hello');
print lower('HELLO');

How to validate phone numbers using regex

You'll have a hard time dealing with international numbers with a single/simple regex, see this post on the difficulties of international (and even north american) phone numbers.

You'll want to parse the first few digits to determine what the country code is, then act differently based on the country.

Beyond that - the list you gave does not include another common US format - leaving off the initial 1. Most cell phones in the US don't require it, and it'll start to baffle the younger generation unless they've dialed internationally.

You've correctly identified that it's a tricky problem...

-Adam

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

c# replace \" characters

\ => \\ and " => \"

so Replace("\\\"","")

How to link html pages in same or different folders?

Use

../

For example if your file, lets say image is in folder1 in folder2 you locate it this way

../folder1/folder2/image

Is there any good dynamic SQL builder library in Java?

Hibernate Criteria API (not plain SQL though, but very powerful and in active development):

List sales = session.createCriteria(Sale.class)
         .add(Expression.ge("date",startDate);
         .add(Expression.le("date",endDate);
         .addOrder( Order.asc("date") )
         .setFirstResult(0)
         .setMaxResults(10)
         .list();

Why does JSON.parse fail with the empty string?

As an empty string is not valid JSON it would be incorrect for JSON.parse('') to return null because "null" is valid JSON. e.g.

JSON.parse("null");

returns null. It would be a mistake for invalid JSON to also be parsed to null.

While an empty string is not valid JSON two quotes is valid JSON. This is an important distinction.

Which is to say a string that contains two quotes is not the same thing as an empty string.

JSON.parse('""');

will parse correctly, (returning an empty string). But

JSON.parse('');

will not.

Valid minimal JSON strings are

The empty object '{}'

The empty array '[]'

The string that is empty '""'

A number e.g. '123.4'

The boolean value true 'true'

The boolean value false 'false'

The null value 'null'

Avoid trailing zeroes in printf()

To get rid of the trailing zeros, you should use the "%g" format:

float num = 1.33;
printf("%g", num); //output: 1.33

After the question was clarified a bit, that suppressing zeros is not the only thing that was asked, but limiting the output to three decimal places was required as well. I think that can't be done with sprintf format strings alone. As Pax Diablo pointed out, string manipulation would be required.

How to embed a PDF?

Here is the code you can use for every browser:

<embed src="pdfFiles/interfaces.pdf" width="600" height="500" alt="pdf" pluginspage="http://www.adobe.com/products/acrobat/readstep2.html">

Tested on firefox and chrome

Valid characters in a Java class name

Identifiers are used for class names, method names, and variable names. An identifiermay be any descriptive sequence of uppercase and lowercase letters, numbers, or theunderscore and dollar-sign characters. They must not begin with a number, lest they beconfused with a numeric literal. Again, Java is case-sensitive, so VALUE is a differentidentifier than Value. Some examples of valid identifiers are:

AvgTemp ,count a4 ,$test ,this_is_ok

Invalid variable names include:

2count, high-temp, Not/ok

Updating version numbers of modules in a multi-module Maven project

Use versions:set from the versions-maven plugin:

mvn versions:set -DnewVersion=2.50.1-SNAPSHOT

It will adjust all pom versions, parent versions and dependency versions in a multi-module project.

If you made a mistake, do

mvn versions:revert

afterwards, or

mvn versions:commit

if you're happy with the results.


Note: this solution assumes that all modules use the aggregate pom as parent pom also, a scenario that was considered standard at the time of this answer. If that is not the case, go for Garret Wilson's answer.

How can I get name of element with jQuery?

To read a property of an object you use .propertyName or ["propertyName"] notation.

This is no different for elements.

var name = $('#item')[0].name;
var name = $('#item')[0]["name"];

If you specifically want to use jQuery methods, then you'd use the .prop() method.

var name = $('#item').prop('name');

Please note that attributes and properties are not necessarily the same.

Vertically aligning text next to a radio button

This will give dead on alignment

input[type="radio"] {
  margin-top: 1px;
  vertical-align: top;
}

Converting double to string with N decimals, dot as decimal separator, and no thousand separator

You can simply use decimal.ToString()

For two decimals

myDecimal.ToString("0.00");

For four decimals

myDecimal.ToString("0.0000");

This gives dot as decimal separator, and no thousand separator regardless of culture.

Remove all elements contained in another array

ECMAScript 6 sets can permit faster computing of the elements of one array that aren't in the other:

_x000D_
_x000D_
const myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const toRemove = new Set(['b', 'c', 'g']);

const difference = myArray.filter( x => !toRemove.has(x) );

console.log(difference); // ["a", "d", "e", "f"]
_x000D_
_x000D_
_x000D_

Since the lookup complexity for the V8 engine browsers use these days is O(1), the time complexity of the whole algorithm is O(n).

How to determine whether a substring is in a different string

People mentioned string.find(), string.index(), and string.indexOf() in the comments, and I summarize them here (according to the Python Documentation):

First of all there is not a string.indexOf() method. The link posted by Deviljho shows this is a JavaScript function.

Second the string.find() and string.index() actually return the index of a substring. The only difference is how they handle the substring not found situation: string.find() returns -1 while string.index() raises an ValueError.

How can I preview a merge in git?

If you're like me, you're looking for equivalent to svn update -n. The following appears to do the trick. Note that make sure to do a git fetch first so that your local repo has the appropriate updates to compare against.

$ git fetch origin
$ git diff --name-status origin/master
D       TableAudit/Step0_DeleteOldFiles.sh
D       TableAudit/Step1_PopulateRawTableList.sh
A       manbuild/staff_companies.sql
M       update-all-slave-dbs.sh

or if you want a diff from your head to the remote:

$ git fetch origin
$ git diff origin/master

IMO this solution is much easier and less error prone (and therefore much less risky) than the top solution which proposes "merge then abort".

How to add images to README.md on GitHub?

Step by step process, First create a folder ( name your folder ) and add the image/images that you want to upload in Readme.md file. ( you can also add the image/images in any existing folder of your project. ) Now,Click on edit icon of Readme.md file,then

![](relative url where images is located/refrence_image.png)  // refrence_image is the name of image in my case.

After adding image, you can see preview of changes in the, "Preview Changes" tab.you will find your image here. for example like this, In my case,

![](app/src/main/res/drawable/refrence_image.png)

app folder -> src folder -> main folder -> res folder -> drawable folder -> and inside drawable folder refrence_image.png file is located. For adding multiple images, you can do it like this,

![](app/src/main/res/drawable/refrence_image1.png)
![](app/src/main/res/drawable/refrence_image2.png)
![](app/src/main/res/drawable/refrence_image3.png)

Note 1 - Make sure your image file name does not contain any spaces. If it contain spaces then you need to add %20 for each space between the file name. It's better to remove the spaces.

Note 2 - you can even resize the image using HTML tags, or there are other ways. you can google it for more. if you need it.

After this, write your commit changes message, and then commit your Changes.

There are many other hacks of doing it like, create a issue and etc and etc. By far this is the best method that I have came across.

jquery .live('click') vs .click()

In addition to T.J. Crowders answer, I have added some more handlers - including the newer .on(...) handler to the snippet so you can see which events are being hidden and which ones not.

What I also found is that .live() is not only deprecated, but was deleted since jQuery 1.9.x. But the other ones, i.e.
.click, .delegate/.undelegate and .on/.off
are still there.

Also note there is more discussion about this topic here on Stackoverflow.

If you need to fix legacy code that is relying on .live, but you require to use a new version of jQuery (> 1.8.3), you can fix it with this snippet:

// fix if legacy code uses .live, but you want to user newer jQuery library
if (!$.fn.live) {
    // in this case .live does not exist, emulate .live by calling .on
    $.fn.live = function(events, handler) {
      $(this).on(events, null, {}, handler);
    };
}

The intention of the snippet below, which is an extension of T.J.'s script, is that you can try out by yourself instantly what happens if you bind multiple handlers - so please run the snippet and click on the texts below:

_x000D_
_x000D_
jQuery(function($) {_x000D_
_x000D_
  // .live connects function with all spans_x000D_
  $('span').live('click', function() {_x000D_
    display("<tt>live</tt> caught a click!");_x000D_
  });_x000D_
_x000D_
  // --- catcher1 events ---_x000D_
_x000D_
  // .click connects function with id='catcher1'_x000D_
  $('#catcher1').click(function() {_x000D_
    display("Click Catcher1 caught a click and prevented <tt>live</tt> from seeing it.");_x000D_
    return false;_x000D_
  });_x000D_
_x000D_
  // --- catcher2 events ---_x000D_
_x000D_
  // .click connects function with id='catcher2'_x000D_
  $('#catcher2').click(function() {_x000D_
    display("Click Catcher2 caught a click and prevented <tt>live</tt>, <tt>delegate</tt> and <tt>on</tt> from seeing it.");_x000D_
    return false;_x000D_
  });_x000D_
_x000D_
  // .delegate connects function with id='catcher2'_x000D_
  $(document).delegate('#catcher2', 'click', function() {_x000D_
    display("Delegate Catcher2 caught a click and prevented <tt>live</tt> from seeing it.");_x000D_
    return false;_x000D_
  });_x000D_
_x000D_
  // .on connects function with id='catcher2'_x000D_
  $(document).on('click', '#catcher2', {}, function() {_x000D_
    display("On Catcher2 caught a click and prevented <tt>live</tt> from seeing it.");_x000D_
    return false;_x000D_
  });_x000D_
_x000D_
  // --- catcher3 events ---_x000D_
_x000D_
  // .delegate connects function with id='catcher3'_x000D_
  $(document).delegate('#catcher3', 'click', function() {_x000D_
    display("Delegate Catcher3 caught a click and <tt>live</tt> and <tt>on</tt> can see it.");_x000D_
    return false;_x000D_
  });_x000D_
_x000D_
  // .on connects function with id='catcher3'_x000D_
  $(document).on('click', '#catcher3', {}, function() {_x000D_
    display("On Catcher3 caught a click and and <tt>live</tt> and <tt>delegate</tt> can see it.");_x000D_
    return false;_x000D_
  });_x000D_
_x000D_
  function display(msg) {_x000D_
    $("<p>").html(msg).appendTo(document.body);_x000D_
  }_x000D_
_x000D_
});
_x000D_
<!-- with JQuery 1.8.3 it still works, but .live was removed since 1.9.0 -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">_x000D_
</script>_x000D_
_x000D_
<style>_x000D_
span.frame {_x000D_
    line-height: 170%; border-style: groove;_x000D_
}_x000D_
</style>_x000D_
_x000D_
<div>_x000D_
  <span class="frame">Click me</span>_x000D_
  <span class="frame">or me</span>_x000D_
  <span class="frame">or me</span>_x000D_
  <div>_x000D_
    <span class="frame">I'm two levels in</span>_x000D_
    <span class="frame">so am I</span>_x000D_
  </div>_x000D_
  <div id='catcher1'>_x000D_
    <span class="frame">#1 - I'm two levels in AND my parent interferes with <tt>live</tt></span>_x000D_
    <span class="frame">me too</span>_x000D_
  </div>_x000D_
  <div id='catcher2'>_x000D_
    <span class="frame">#2 - I'm two levels in AND my parent interferes with <tt>live</tt></span>_x000D_
    <span class="frame">me too</span>_x000D_
  </div>_x000D_
  <div id='catcher3'>_x000D_
    <span class="frame">#3 - I'm two levels in AND my parent interferes with <tt>live</tt></span>_x000D_
    <span class="frame">me too</span>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

UTF-8 encoding problem in Spring MVC

There are some similar questions: Spring MVC response encoding issue, Custom HttpMessageConverter with @ResponseBody to do Json things.

However, my simple solution:

@RequestMapping(method=RequestMethod.GET,value="/GetMyList")
public ModelAndView getMyList(){
  String test = "ccždš";
  ...
  ModelAndView mav = new ModelAndView("html_utf8");
  mav.addObject("responseBody", test);
}

and the view html_utf8.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>${responseBody}

No additional classes and configuration.
And You can also create another view (for example json_utf8) for other content type.

Python vs. Java performance (runtime speed)

There is no good answer as Python and Java are both specifications for which there are many different implementations. For example, CPython, IronPython, Jython, and PyPy are just a handful of Python implementations out there. For Java, there is the HotSpot VM, the Mac OS X Java VM, OpenJRE, etc. Jython generates Java bytecode, and so it would be using more-or-less the same underlying Java. CPython implements quite a handful of things directly in C, so it is very fast, but then again Java VMs also implement many functions in C. You would probably have to measure on a function-by-function basis and across a variety of interpreters and VMs in order to make any reasonable statement.

HTML / CSS How to add image icon to input type="button"?

<img src="http://www.pic4ever.com/images/2mpe5id.gif">
            <button class="btn btn-<?php echo $settings["button_background"]; ?>" type="submit"><?php echo $settings["submit_button_text"]; ?></button>

How can I use custom fonts on a website?

You have to import the font in your stylesheet like this:

@font-face{
    font-family: "Thonburi-Bold";
    src: url('Thonburi-Bold.ttf'),
    url('Thonburi-Bold.eot'); /* IE */
}

How to add default signature in Outlook

I have made this a Community Wiki answer because I could not have created it without PowerUser's research and the help in earlier comments.

I took PowerUser's Sub X and added

Debug.Print "n------"    'with different values for n
Debug.Print ObjMail.HTMLBody

after every statement. From this I discovered the signature is not within .HTMLBody until after ObjMail.Display and then only if I haven't added anything to the body.

I went back to PowerUser's earlier solution that used C:\Users\" & Environ("username") & "\AppData\Roaming\Microsoft\Signatures\Mysig.txt"). PowerUser was unhappy with this because he wanted his solution to work for others who would have different signatures.

My signature is in the same folder and I cannot find any option to change this folder. I have only one signature so by reading the only HTM file in this folder, I obtained my only/default signature.

I created an HTML table and inserted it into the signature immediately following the <body> element and set the html body to the result. I sent the email to myself and the result was perfectly acceptable providing you like my formatting which I included to check that I could.

My modified subroutine is:

Sub X()

  Dim OlApp As Outlook.Application
  Dim ObjMail As Outlook.MailItem

  Dim BodyHtml As String
  Dim DirSig As String
  Dim FileNameHTMSig As String
  Dim Pos1 As Long
  Dim Pos2 As Long
  Dim SigHtm As String

  DirSig = "C:\Users\" & Environ("username") & _
                               "\AppData\Roaming\Microsoft\Signatures"

  FileNameHTMSig = Dir$(DirSig & "\*.htm")

  ' Code to handle there being no htm signature or there being more than one

  SigHtm = GetBoiler(DirSig & "\" & FileNameHTMSig)
  Pos1 = InStr(1, LCase(SigHtm), "<body")

  ' Code to handle there being no body

  Pos2 = InStr(Pos1, LCase(SigHtm), ">")

  ' Code to handle there being no closing > for the body element

   BodyHtml = "<table border=0 width=""100%"" style=""Color: #0000FF""" & _
         " bgColor=#F0F0F0><tr><td align= ""center"">HTML table</td>" & _
         "</tr></table><br>"
  BodyHtml = Mid(SigHtm, 1, Pos2 + 1) & BodyHtml & Mid(SigHtm, Pos2 + 2)

  Set OlApp = Outlook.Application
  Set ObjMail = OlApp.CreateItem(olMailItem)
  ObjMail.BodyFormat = olFormatHTML
  ObjMail.Subject = "Subject goes here"
  ObjMail.Recipients.Add "my email address"
  ObjMail.Display

End Sub

Since both PowerUser and I have found our signatures in C:\Users\" & Environ("username") & "\AppData\Roaming\Microsoft\Signatures I suggest this is the standard location for any Outlook installation. Can this default be changed? I cannot find anything to suggest it can. The above code clearly needs some development but it does achieve PowerUser's objective of creating an email body containing an HTML table above a signature.

Create Table from View

To create a table on the fly us this syntax:

SELECT *
INTO A
FROM dbo.myView

node.js + mysql connection pooling

i always use connection.relase(); after pool.getconnetion like

pool.getConnection(function (err, connection) {
      connection.release();
        if (!err)
        {
            console.log('*** Mysql Connection established with ', config.database, ' and connected as id ' + connection.threadId);
            //CHECKING USERNAME EXISTENCE
            email = receivedValues.email
            connection.query('SELECT * FROM users WHERE email = ?', [email],
                function (err, rows) {
                    if (!err)
                    {
                        if (rows.length == 1)
                        {
                            if (bcrypt.compareSync(req.body.password, rows[0].password))
                            {
                                var alldata = rows;
                                var userid = rows[0].id;
                                var tokendata = (receivedValues, userid);
                                var token = jwt.sign(receivedValues, config.secret, {
                                    expiresIn: 1440 * 60 * 30 // expires in 1440 minutes
                                });
                                console.log("*** Authorised User");
                                res.json({
                                    "code": 200,
                                    "status": "Success",
                                    "token": token,
                                    "userData": alldata,
                                    "message": "Authorised User!"
                                });
                                logger.info('url=', URL.url, 'Responce=', 'User Signin, username', req.body.email, 'User Id=', rows[0].id);
                                return;
                            }
                            else
                            {
                                console.log("*** Redirecting: Unauthorised User");
                                res.json({"code": 200, "status": "Fail", "message": "Unauthorised User!"});
                                logger.error('*** Redirecting: Unauthorised User');
                                return;
                            }
                        }
                        else
                        {
                            console.error("*** Redirecting: No User found with provided name");
                            res.json({
                                "code": 200,
                                "status": "Error",
                                "message": "No User found with provided name"
                            });
                            logger.error('url=', URL.url, 'No User found with provided name');
                            return;
                        }
                    }
                    else
                    {
                        console.log("*** Redirecting: Error for selecting user");
                        res.json({"code": 200, "status": "Error", "message": "Error for selecting user"});
                        logger.error('url=', URL.url, 'Error for selecting user', req.body.email);
                        return;
                    }
                });
            connection.on('error', function (err) {
                console.log('*** Redirecting: Error Creating User...');
                res.json({"code": 200, "status": "Error", "message": "Error Checking Username Duplicate"});
                return;
            });
        }
        else
        {
            Errors.Connection_Error(res);
        }
    });

How to import multiple csv files in a single load?

val df = spark.read.option("header", "true").csv("C:spark\\sample_data\\*.csv)

will consider files tmp, tmp1, tmp2, ....

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

Encode converts a unicode object in to a string object. I think you are trying to encode a string object. first convert your result into unicode object and then encode that unicode object into 'utf-8'. for example

    result = yourFunction()
    result.decode().encode('utf-8')

Convert IQueryable<> type object to List<T> type?

Add the following:

using System.Linq

...and call ToList() on the IQueryable<>.

Which is faster: Stack allocation or Heap allocation

Probably the biggest problem of heap allocation versus stack allocation, is that heap allocation in the general case is an unbounded operation, and thus you can't use it where timing is an issue.

For other applications where timing isn't an issue, it may not matter as much, but if you heap allocate a lot, this will affect the execution speed. Always try to use the stack for short lived and often allocated memory (for instance in loops), and as long as possible - do heap allocation during application startup.

How can I find out the current route in Rails?

Simplest solution I can come up with in 2015 (verified using Rails 4, but should also work using Rails 3)

request.url
# => "http://localhost:3000/lists/7/items"
request.path
# => "/lists/7/items"

How do I iterate through each element in an n-dimensional matrix in MATLAB?

As pointed out in a few other answers, you can iterate over all elements in a matrix A (of any dimension) using a linear index from 1 to numel(A) in a single for loop. There are also a couple of functions you can use: arrayfun and cellfun.

Let's first assume you have a function that you want to apply to each element of A (called my_func). You first create a function handle to this function:

fcn = @my_func;

If A is a matrix (of type double, single, etc.) of arbitrary dimension, you can use arrayfun to apply my_func to each element:

outArgs = arrayfun(fcn, A);

If A is a cell array of arbitrary dimension, you can use cellfun to apply my_func to each cell:

outArgs = cellfun(fcn, A);

The function my_func has to accept A as an input. If there are any outputs from my_func, these are placed in outArgs, which will be the same size/dimension as A.

One caveat on outputs... if my_func returns outputs of different sizes and types when it operates on different elements of A, then outArgs will have to be made into a cell array. This is done by calling either arrayfun or cellfun with an additional parameter/value pair:

outArgs = arrayfun(fcn, A, 'UniformOutput', false);
outArgs = cellfun(fcn, A, 'UniformOutput', false);

Leave menu bar fixed on top when scrolled

try with sticky jquery plugin

https://github.com/garand/sticky

_x000D_
_x000D_
<script src="jquery.js"></script>_x000D_
<script src="jquery.sticky.js"></script>_x000D_
<script>_x000D_
  $(document).ready(function(){_x000D_
    $("#sticker").sticky({topSpacing:0});_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

Differences between Emacs and Vim

(the text below is my opinion, it should not be taken as fact or an insult)

With Emacs you are expected to have it open 24/7 and live inside the program, almost everything you do can be done from there. You write your own extensions, use it for note-taking, organization, games, programming, shell access, file access, listening to music, web browsing. It takes weeks and weeks till you will be happy with it and then you will learn new stuff all the time. You will be annoyed when you don't have access to it and constantly change your config. You won't be able to use other peoples emacs versions easily and it won't just be installed. It uses Lisp, which is great. You can make it into anything you want it to be. (anything, at all)

With Vim, it's almost always pre-installed. It's fast. You open up a file do a quick edit and then quit. You can work with the basic setup if you are on someone else's machine. It's not quite so editable, but it's still far better than most text editors. It recognizes that most of the time you are reading/editing not typing and makes that portion faster. You don't suffer from emacs pinkie. It's not so infuriating. It's easier to learn.

Even though I use Emacs all day every day (and love it) unless you intend to spend a lot of time in the program you choose I would pick vim

Add carriage return to a string

string s2 = s1.Replace(",", ",\n");

Error message: "'chromedriver' executable needs to be available in the path"

Add the webdriver(chromedriver.exe or geckodriver.exe) here C:\Windows. This worked in my case

Vertically align text within input field of fixed-height without display: table or padding?

I've not tried this myself, but try setting:

height : 36px; //for other browsers
line-height: 36px; // for IE

Where 36px is the height of your input.

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

I'll answer your question with an example. Suppose we had a Math class with a static method add. You would call this method like so:

Math.add(2, 3);

If Math were an interface instead of a class, it could not have any defined functions. As such, saying something like Math.add(2, 3) makes no sense.

How to delete all the rows in a table using Eloquent?

I've seen both methods been used in seed files.

// Uncomment the below to wipe the table clean before populating

DB::table('table_name')->truncate();

//or

DB::table('table_name')->delete();

Even though you can not use the first one if you want to set foreign keys.

Cannot truncate a table referenced in a foreign key constraint

So it might be a good idea to use the second one.

JAVA Unsupported major.minor version 51.0

The Java runtime you try to execute your program with is an earlier version than Java 7 which was the target you compile your program for.

For Ubuntu use

apt-get install openjdk-7-jdk

to get Java 7 as default. You may have to uninstall openjdk-6 first.

what is difference between success and .done() method of $.ajax

In short, decoupling success callback function from the ajax function so later you can add your own handlers without modifying the original code (observer pattern).

Please find more detailed information from here: https://stackoverflow.com/a/14754681/1049184

How to create folder with PHP code?

Purely basic folder creation

<?php mkdir("testing"); ?> <= this, actually creates a folder called "testing".



Basic file creation

<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
?>

Use the a or a+ switch to add/append to file.



EDIT:

This version will create a file and folder at the same time and show it on screen after.

<?php

// change the name below for the folder you want
$dir = "new_folder_name";

$file_to_write = 'test.txt';
$content_to_write = "The content";

if( is_dir($dir) === false )
{
    mkdir($dir);
}

$file = fopen($dir . '/' . $file_to_write,"w");

// a different way to write content into
// fwrite($file,"Hello World.");

fwrite($file, $content_to_write);

// closes the file
fclose($file);

// this will show the created file from the created folder on screen
include $dir . '/' . $file_to_write;

?>

How to do paging in AngularJS?

ng-repeat pagination

    <div ng-app="myApp" ng-controller="MyCtrl">
<input ng-model="q" id="search" class="form-control" placeholder="Filter text">
<select ng-model="pageSize" id="pageSize" class="form-control">
    <option value="5">5</option>
    <option value="10">10</option>
    <option value="15">15</option>
    <option value="20">20</option>
 </select>
<ul>
    <li ng-repeat="item in data | filter:q | startFrom:currentPage*pageSize | limitTo:pageSize">
        {{item}}
    </li>
</ul>
<button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
    Previous
</button>
{{currentPage+1}}/{{numberOfPages()}}
 <button ng-disabled="currentPage >= getData().length/pageSize - 1" ng-                 click="currentPage=currentPage+1">
    Next
    </button>
</div>

<script>

 var app=angular.module('myApp', []);

 app.controller('MyCtrl', ['$scope', '$filter', function ($scope, $filter) {
 $scope.currentPage = 0;
 $scope.pageSize = 10;
 $scope.data = [];
 $scope.q = '';

 $scope.getData = function () {

  return $filter('filter')($scope.data, $scope.q)

   }

   $scope.numberOfPages=function(){
    return Math.ceil($scope.getData().length/$scope.pageSize);                
   }

   for (var i=0; i<65; i++) {
    $scope.data.push("Item "+i);
   }
  }]);

        app.filter('startFrom', function() {
    return function(input, start) {
    start = +start; //parse to int
    return input.slice(start);
   }
  });
  </script>

How to Install Font Awesome in Laravel Mix

npm install font-awesome --save

add ~/ before path

@import "~/font-awesome/scss/font-awesome.scss";

Declaring a boolean in JavaScript using just var

How about something like this:

var MyNamespace = {
    convertToBoolean: function (value) {
        //VALIDATE INPUT
        if (typeof value === 'undefined' || value === null) return false;

        //DETERMINE BOOLEAN VALUE FROM STRING
        if (typeof value === 'string') {
            switch (value.toLowerCase()) {
                case 'true':
                case 'yes':
                case '1':
                    return true;
                case 'false':
                case 'no':
                case '0':
                    return false;
            }
        }

        //RETURN DEFAULT HANDLER
        return Boolean(value);
    }
};

Then you can use it like this:

MyNamespace.convertToBoolean('true') //true
MyNamespace.convertToBoolean('no') //false
MyNamespace.convertToBoolean('1') //true
MyNamespace.convertToBoolean(0) //false

I have not tested it for performance, but converting from type to type should not happen too often otherwise you open your app up to instability big time!

Remove space above and below <p> tag HTML

<p> elements generally have margins and / or padding. You can set those to zero in a stylesheet.

li p {
    margin: 0;
    padding: 0;
}

Semantically speaking, however, it is fairly unusual to have a list of paragraphs.

How to create and add users to a group in Jenkins for authentication?

According to this posting by the lead Jenkins developer, Kohsuke Kawaguchi, in 2009, there is no group support for the built-in Jenkins user database. Group support is only usable when integrating Jenkins with LDAP or Active Directory. This appears to be the same in 2012.

However, as Vadim wrote in his answer, you don't need group support for the built-in Jenkins user database, thanks to the Role strategy plug-in.

How to enable remote access of mysql in centos?

In case of Allow IP to mysql server linux machine. you can do following command--

 nano /etc/httpd/conf.d/phpMyAdmin.conf  and add Desired IP.

<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8
   Order allow,deny
   allow from all
   <IfModule mod_authz_core.c>
     # Apache 2.4
     <RequireAny>

    Require ip 192.168.9.1(Desired IP)

</RequireAny>
   </IfModule>
 <IfModule !mod_authz_core.c>
     # Apache 2.2
     Order Deny,Allow
     #Allow from All

     Allow from 192.168.9.1(Desired IP)

</IfModule>

And after Update, please restart using following command--

sudo systemctl restart httpd.service

How to set conditional breakpoints in Visual Studio?

Set the breakpoint as you do normally, right click the break point and select condion option and sets your condition.

Where is the default log location for SharePoint/MOSS?

For SharePoint 2016

%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\15\Logs

For SharePoint 2013

%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\15\Logs

For SharePoint 2010

%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\14\Logs

For SharePoint 2007

%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\12\Logs

Note: The sharePoint Trace log path can be changed by opening Central Administration > Monitoring > Reporting > Configure Diagnostic Logs

For more details check SHAREPOINT ULS VIEWER

Spring RequestMapping for controllers that produce and consume JSON

As of Spring 4.2.x, you can create custom mapping annotations, using @RequestMapping as a meta-annotation. So:

Is there a way to produce a "composite/inherited/aggregated" annotation with default values for consumes and produces, such that I could instead write something like:

@JSONRequestMapping(value = "/foo", method = RequestMethod.POST)

Yes, there is such a way. You can create a meta annotation like following:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@RequestMapping(consumes = "application/json", produces = "application/json")
public @interface JsonRequestMapping {
    @AliasFor(annotation = RequestMapping.class, attribute = "value")
    String[] value() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "method")
    RequestMethod[] method() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "params")
    String[] params() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "headers")
    String[] headers() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "consumes")
    String[] consumes() default {};

    @AliasFor(annotation = RequestMapping.class, attribute = "produces")
    String[] produces() default {};
}

Then you can use the default settings or even override them as you want:

@JsonRequestMapping(method = POST)
public String defaultSettings() {
    return "Default settings";
}

@JsonRequestMapping(value = "/override", method = PUT, produces = "text/plain")
public String overrideSome(@RequestBody String json) {
    return json;
}

You can read more about AliasFor in spring's javadoc and github wiki.

Comparing two vectors in an if statement

all is one option:

> A <- c("A", "B", "C", "D")
> B <- A
> C <- c("A", "C", "C", "E")

> all(A==B)
[1] TRUE
> all(A==C)
[1] FALSE

But you may have to watch out for recycling:

> D <- c("A","B","A","B")
> E <- c("A","B")
> all(D==E)
[1] TRUE
> all(length(D)==length(E)) && all(D==E)
[1] FALSE

The documentation for length says it currently only outputs an integer of length 1, but that it may change in the future, so that's why I wrapped the length test in all.

Can I disable a CSS :hover effect via JavaScript?

Try just setting the link color:

$("ul#mainFilter a").css('color','#000');

Edit: or better yet, use the CSS, as Christopher suggested

How to grep Git commit diffs or contents for a certain word?

To use boolean connector on regular expression:

git log --grep '[0-9]*\|[a-z]*'

This regular expression search for regular expression [0-9]* or [a-z]* on commit messages.

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

The following is needed:

  • MS Online Services Assistant needs to be downloaded and installed.
  • MS Online Module for PowerShell needs to be downloaded and installed
  • Connect to Microsoft Online in PowerShell

Source: http://www.msdigest.net/2012/03/how-to-connect-to-office-365-with-powershell/

Then Follow this one if you're running a 64bits computer: I’m running a x64 OS currently (Win8 Pro).

Copy the folder MSOnline from (1) –> (2) as seen here

1) C:\Windows\System32\WindowsPowerShell\v1.0\Modules(MSOnline)

2) C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules(MSOnline)

Source: http://blog.clauskonrad.net/2013/06/powershell-and-c-cant-load-msonline.html

Hope this is better and can save some people's time

How to make padding:auto work in CSS?

if you're goal is to reset EVERYTHING then @Björn's answer should be your goal but applied as:

* {
  padding: initial;
}

if this is loaded after your original reset.css should have the same weight and will rely on each browser's default padding as initial value.

JavaScript associative array to JSON

You might want to push the object into the array

enter code here

var AssocArray = new Array();

AssocArray.push( "The letter A");

console.log("a = " + AssocArray[0]);

// result: "a = The letter A"

console.log( AssocArray[0]);

JSON.stringify(AssocArray);

SQL Server: Importing database from .mdf?

If you do not have an LDF file then:

1) put the MDF in the C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\

2) In ssms, go to Databases -> Attach and add the MDF file. It will not let you add it this way but it will tell you the database name contained within.

3) Make sure the user you are running ssms.exe as has acccess to this MDF file.

4) Now that you know the DbName, run

EXEC sp_attach_single_file_db @dbname = 'DbName', 
@physname = N'C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\yourfile.mdf';

Reference: https://dba.stackexchange.com/questions/12089/attaching-mdf-without-ldf

not-null property references a null or transient value

I resolved by removing @Basic(optional = false) property or just update boolean @Basic(optional = true)

How to get position of a certain element in strings vector, to use it as an index in ints vector?

To get a position of an element in a vector knowing an iterator pointing to the element, simply subtract v.begin() from the iterator:

ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();

Now you need to check pos against Names.size() to see if it is out of bounds or not:

if(pos >= Names.size()) {
    //old_name_ not found
}

vector iterators behave in ways similar to array pointers; most of what you know about pointer arithmetic can be applied to vector iterators as well.

Starting with C++11 you can use std::distance in place of subtraction for both iterators and pointers:

ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));

Better techniques for trimming leading zeros in SQL Server?

cast(value as int) will always work if string is a number

Add element to a list In Scala

I will try to explain the results of all the commands you tried.

scala> val l = 1.0 :: 5.5 :: Nil
l: List[Double] = List(1.0, 5.5)

First of all, List is a type alias to scala.collection.immutable.List (defined in Predef.scala).

Using the List companion object is more straightforward way to instantiate a List. Ex: List(1.0,5.5)

scala> l
res0: List[Double] = List(1.0, 5.5)

scala> l ::: List(2.2, 3.7)
res1: List[Double] = List(1.0, 5.5, 2.2, 3.7)

::: returns a list resulting from the concatenation of the given list prefix and this list

The original List is NOT modified

scala> List(l) :+ 2.2
res2: List[Any] = List(List(1.0, 5.5), 2.2)

List(l) is a List[List[Double]] Definitely not what you want.

:+ returns a new list consisting of all elements of this list followed by elem.

The type is List[Any] because it is the common superclass between List[Double] and Double

scala> l
res3: List[Double] = List(1.0, 5.5)

l is left unmodified because no method on immutable.List modified the List.

ASP.NET MVC 3 Razor - Adding class to EditorFor

I used another solution using CSS attribute selectors to get what you need.

Indicate the HTML attribute you know and put in the relative style you want.

Like below:

input[type="date"]
{
     width: 150px;
}

Sleeping in a batch file

I like Aacini's response. I added to it to handle the day and also enable it to handle centiseconds (%TIME% outputs H:MM:SS.CC):

:delay
SET DELAYINPUT=%1
SET /A DAYS=DELAYINPUT/8640000
SET /A DELAYINPUT=DELAYINPUT-(DAYS*864000)

::Get ending centisecond (10 milliseconds)
FOR /F "tokens=1-4 delims=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, X=1%%D%%100, ENDING=((H*60+M)*60+S)*100+X+DELAYINPUT
SET /A DAYS=DAYS+ENDING/8640000
SET /A ENDING=ENDING-(DAYS*864000)

::Wait for such a centisecond
:delay_wait
FOR /F "tokens=1-4 delims=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, X=1%%D%%100, CURRENT=((H*60+M)*60+S)*100+X
IF DEFINED LASTCURRENT IF %CURRENT% LSS %LASTCURRENT% SET /A DAYS=DAYS-1
SET LASTCURRENT=%CURRENT%
IF %CURRENT% LSS %ENDING% GOTO delay_wait
IF %DAYS% GTR 0 GOTO delay_wait
GOTO :EOF

Get time in milliseconds using C#

I used DateTime.Now.TimeOfDay.TotalMilliseconds (for current day), hope it helps you out as well.

Finding out current index in EACH loop (Ruby)

X.each_with_index do |item, index|
  puts "current_index: #{index}"
end

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

difference between width auto and width 100 percent

  • width: auto; will try as hard as possible to keep an element the same width as its parent container when additional space is added from margins, padding, or borders.

  • width: 100%; will make the element as wide as the parent container. Extra spacing will be added to the element's size without regards to the parent. This typically causes problems.

enter image description here enter image description here

Bash script to check running process

This trick works for me. Hope this could help you. Let's save the followings as checkRunningProcess.sh

#!/bin/bash
ps_out=`ps -ef | grep $1 | grep -v 'grep' | grep -v $0`
result=$(echo $ps_out | grep "$1")
if [[ "$result" != "" ]];then
    echo "Running"
else
    echo "Not Running"
fi

Make the checkRunningProcess.sh executable.And then use it.
Example to use.

20:10 $ checkRunningProcess.sh proxy.py
Running
20:12 $ checkRunningProcess.sh abcdef
Not Running

Get the size of the screen, current web page and browser window

A non-jQuery way to get the available screen dimension. window.screen.width/height has already been put up, but for responsive webdesign and completeness sake I think its worth to mention those attributes:

alert(window.screen.availWidth);
alert(window.screen.availHeight);

http://www.quirksmode.org/dom/w3c_cssom.html#t10 :

availWidth and availHeight - The available width and height on the screen (excluding OS taskbars and such).

How to pad a string to a fixed length with spaces in Python?

string = ""
name = raw_input() #The value at the field
length = input() #the length of the field
string += name
string += " "*(length-len(name)) # Add extra spaces

This will add the number of spaces needed, provided the field has length >= the length of the name provided

How do you access the matched groups in a JavaScript regular expression?

Using your code:

console.log(arr[1]);  // prints: abc
console.log(arr[0]);  // prints:  format_abc

Edit: Safari 3, if it matters.

How to build a RESTful API?

As simon marc said, the process is much the same as it is for you or I browsing a website. If you are comfortable with using the Zend framework, there are some easy to follow tutorials to that make life quite easy to set things up. The hardest part of building a restful api is the design of the it, and making it truly restful, think CRUD in database terms.

It could be that you really want an xmlrpc interface or something else similar. What do you want this interface to allow you to do?

--EDIT

Here is where I got started with restful api and Zend Framework. Zend Framework Example

In short don't use Zend rest server, it's obsolete.

jQuery date formatting

You can add new user jQuery function 'getDate'

JSFiddle: getDate jQuery

Or you can run code snippet. Just press "Run code snippet" button below this post.

_x000D_
_x000D_
// Create user jQuery function 'getDate'_x000D_
(function( $ ){_x000D_
   $.fn.getDate = function(format) {_x000D_
_x000D_
 var gDate  = new Date();_x000D_
 var mDate  = {_x000D_
 'S': gDate.getSeconds(),_x000D_
 'M': gDate.getMinutes(),_x000D_
 'H': gDate.getHours(),_x000D_
 'd': gDate.getDate(),_x000D_
 'm': gDate.getMonth() + 1,_x000D_
 'y': gDate.getFullYear(),_x000D_
 }_x000D_
_x000D_
 // Apply format and add leading zeroes_x000D_
 return format.replace(/([SMHdmy])/g, function(key){return (mDate[key] < 10 ? '0' : '') + mDate[key];});_x000D_
_x000D_
 return getDate(str);_x000D_
   }; _x000D_
})( jQuery );_x000D_
_x000D_
_x000D_
// Usage: example #1. Write to '#date' div_x000D_
$('#date').html($().getDate("y-m-d H:M:S"));_x000D_
_x000D_
// Usage: ex2. Simple clock. Write to '#clock' div_x000D_
function clock(){_x000D_
 $('#clock').html($().getDate("H:M:S, m/d/y"))_x000D_
}_x000D_
clock();_x000D_
setInterval(clock, 1000); // One second_x000D_
_x000D_
// Usage: ex3. Simple clock 2. Write to '#clock2' div_x000D_
function clock2(){_x000D_
_x000D_
 var format = 'H:M:S'; // Date format_x000D_
 var updateInterval = 1000; // 1 second_x000D_
 var clock2Div = $('#clock2'); // Get div_x000D_
 var currentTime = $().getDate(format); // Get time_x000D_
 _x000D_
 clock2Div.html(currentTime); // Write to div_x000D_
 setTimeout(clock2, updateInterval); // Set timer 1 second_x000D_
 _x000D_
}_x000D_
// Run clock2_x000D_
clock2();_x000D_
_x000D_
// Just for fun_x000D_
// Usage: ex4. Simple clock 3. Write to '#clock3' span_x000D_
_x000D_
function clock3(){_x000D_
_x000D_
 var formatHM = 'H:M:'; // Hours, minutes_x000D_
 var formatS = 'S'; // Seconds_x000D_
 var updateInterval = 1000; // 1 second_x000D_
 var clock3SpanHM = $('#clock3HM'); // Get span HM_x000D_
 var clock3SpanS = $('#clock3S'); // Get span S_x000D_
 var currentHM = $().getDate(formatHM); // Get time H:M_x000D_
 var currentS = $().getDate(formatS); // Get seconds_x000D_
 _x000D_
 clock3SpanHM.html(currentHM); // Write to div_x000D_
 clock3SpanS.fadeOut(1000).html(currentS).fadeIn(1); // Write to span_x000D_
 setTimeout(clock3, updateInterval); // Set timer 1 second_x000D_
 _x000D_
}_x000D_
// Run clock2_x000D_
clock3();
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
_x000D_
<div id="date"></div><br>_x000D_
<div id="clock"></div><br>_x000D_
<span id="clock3HM"></span><span id="clock3S"></span>
_x000D_
_x000D_
_x000D_

Enjoy!

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

Add this line under the dependencies in your gradle file

compile 'com.android.support:support-annotations:27.1.1'

How do I use regex in a SQLite query?

A SQLite UDF in PHP/PDO for the REGEXP keyword that mimics the behavior in MySQL:

$pdo->sqliteCreateFunction('regexp',
    function ($pattern, $data, $delimiter = '~', $modifiers = 'isuS')
    {
        if (isset($pattern, $data) === true)
        {
            return (preg_match(sprintf('%1$s%2$s%1$s%3$s', $delimiter, $pattern, $modifiers), $data) > 0);
        }

        return null;
    }
);

The u modifier is not implemented in MySQL, but I find it useful to have it by default. Examples:

SELECT * FROM "table" WHERE "name" REGEXP 'sql(ite)*';
SELECT * FROM "table" WHERE regexp('sql(ite)*', "name", '#', 's');

If either $data or $pattern is NULL, the result is NULL - just like in MySQL.

How can I make a "color map" plot in matlab?

gevang's answer is great. There's another way as well to do this directly by using pcolor. Code:

[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
figure;
subplot(1,3,1);
pcolor(X,Y,Z); 
subplot(1,3,2);
pcolor(X,Y,Z); shading flat;
subplot(1,3,3);
pcolor(X,Y,Z); shading interp;

Output:

enter image description here

Also, pcolor is flat too, as show here (pcolor is the 2d base; the 3d figure above it is generated using mesh):

enter image description here

Is it safe to use Project Lombok?

I'm not recommend it. I used to use it, but then when I work with NetBeans 7.4 it was messing my codes. I've to remove lombok in all of files in my projects. There is delombok, but how can I be sure it would not screw my codes. I have to spends days just to remove lombok and back to ordinary Java styles. I just too spicy...

jquery find class and get the value

You can get value of id,name or value in this way. class name my_class

 var id_value = $('.my_class').$(this).attr('id'); //get id value
 var name_value = $('.my_class').$(this).attr('name'); //get name value
 var value = $('.my_class').$(this).attr('value'); //get value any input or tag

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

With the new @SpringBootTest annotation, I took this answer and modified it to use profiles with a @SpringBootApplication configuration class. The @Profile annotation is necessary so that this class is only picked up during the specific integration tests that need this, as other test configurations do different component scanning.

Here is the configuration class:

@Profile("specific-profile")
@SpringBootApplication(scanBasePackages={"com.myco.package1", "com.myco.package2"})
public class SpecificTestConfig {

}

Then, the test class references this configuration class:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { SpecificTestConfig.class })
@ActiveProfiles({"specific-profile"})
public class MyTest {

}

MVC [HttpPost/HttpGet] for Action

You cant combine this to attributes.

But you can put both on one action method but you can encapsulate your logic into a other method and call this method from both actions.

The ActionName Attribute allows to have 2 ActionMethods with the same name.

[HttpGet]
public ActionResult MyMethod()
{
    return MyMethodHandler();
}

[HttpPost]
[ActionName("MyMethod")]
public ActionResult MyMethodPost()
{
    return MyMethodHandler();
}

private ActionResult MyMethodHandler()
{
    // handle the get or post request
    return View("MyMethod");
}

Strip HTML from Text JavaScript

function stripHTML(my_string){
    var charArr   = my_string.split(''),
        resultArr = [],
        htmlZone  = 0,
        quoteZone = 0;
    for( x=0; x < charArr.length; x++ ){
     switch( charArr[x] + htmlZone + quoteZone ){
       case "<00" : htmlZone  = 1;break;
       case ">10" : htmlZone  = 0;resultArr.push(' ');break;
       case '"10' : quoteZone = 1;break;
       case "'10" : quoteZone = 2;break;
       case '"11' : 
       case "'12" : quoteZone = 0;break;
       default    : if(!htmlZone){ resultArr.push(charArr[x]); }
     }
    }
    return resultArr.join('');
}

Accounts for > inside attributes and <img onerror="javascript"> in newly created dom elements.

usage:

clean_string = stripHTML("string with <html> in it")

demo:

https://jsfiddle.net/gaby_de_wilde/pqayphzd/

demo of top answer doing the terrible things:

https://jsfiddle.net/gaby_de_wilde/6f0jymL6/1/

Android: remove notification from notification bar

If you are generating Notification from a Service that is started in the foreground using

startForeground(NOTIFICATION_ID, notificationBuilder.build());

Then issuing

notificationManager.cancel(NOTIFICATION_ID);

does't work canceling the Notification & notification still appears in the status bar. In this particular case, you will solve these by 2 ways:

1> Using stopForeground( false ) inside service:

stopForeground( false );
notificationManager.cancel(NOTIFICATION_ID);

2> Destroy that service class with calling activity:

Intent i = new Intent(context, Service.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
if(ServiceCallingActivity.activity != null) {
    ServiceCallingActivity.activity.finish();
}
context.stopService(i);

Second way prefer in music player notification more because thay way not only notification remove but remove player also...!!

Run a single test method with maven

To my knowledge, the surefire plugin doesn't provide any way to do this. But feel free to open an issue :)

UITableView - scroll to the top

Swift 5, iOS 13

I know this question already has a lot of answers but from my experience this method always works:

let last = IndexPath(row: someArray.count - 1, section: 0)
tableView.scrollToRow(at: last, at: .bottom, animated: true)

And this is especially true if you're working with animations (like keyboard) or certain async tasks—the other answers will often scroll to the almost bottom. If for some reason this doesn't get you all the way to the bottom, it's almost certainly because of a competing animation so the workaround is to dispatch this animation to the end of the main queue:

DispatchQueue.main.async {
    let last = IndexPath(row: self.someArray.count - 1, section: 0)
    self.tableView.scrollToRow(at: last, at: .bottom, animated: true)
}

This may seem redundant since you're already on the main queue but it's not because it serializes the animations.

When do I need to use Begin / End Blocks and the Go keyword in SQL Server?

GO isn't a keyword in SQL Server; it's a batch separator. GO ends a batch of statements. This is especially useful when you are using something like SQLCMD. Imagine you are entering in SQL statements on the command line. You don't necessarily want the thing to execute every time you end a statement, so SQL Server does nothing until you enter "GO".

Likewise, before your batch starts, you often need to have some objects visible. For example, let's say you are creating a database and then querying it. You can't write:

CREATE DATABASE foo;
USE foo;
CREATE TABLE bar;

because foo does not exist for the batch which does the CREATE TABLE. You'd need to do this:

CREATE DATABASE foo;
GO
USE foo;
CREATE TABLE bar;

One command to create a directory and file inside it linux command

You could create a function that parses argument with sed;

atouch() {
  mkdir -p $(sed 's/\(.*\)\/.*/\1/' <<< $1) && touch $1
}

and then, execute it with one argument:

atouch B/C/D/myfile.txt

Waiting until two async blocks are executed before starting another block

With Swift 5.1, Grand Central Dispatch offers many ways to solve your problem. According to your needs, you may choose one of the seven patterns shown in the following Playground snippets.


#1. Using DispatchGroup, DispatchGroup's notify(qos:flags:queue:execute:) and DispatchQueue's async(group:qos:flags:execute:)

The Apple Developer Concurrency Programming Guide states about DispatchGroup:

Dispatch groups are a way to block a thread until one or more tasks finish executing. You can use this behavior in places where you cannot make progress until all of the specified tasks are complete. For example, after dispatching several tasks to compute some data, you might use a group to wait on those tasks and then process the results when they are done.

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let queue = DispatchQueue(label: "com.company.app.queue", attributes: .concurrent)
let group = DispatchGroup()

queue.async(group: group) {
    print("#1 started")
    Thread.sleep(forTimeInterval: 5)
    print("#1 finished")
}

queue.async(group: group) {
    print("#2 started")
    Thread.sleep(forTimeInterval: 2)
    print("#2 finished")
}

group.notify(queue: queue) {
    print("#3 finished")
}

/*
 prints:
 #1 started
 #2 started
 #2 finished
 #1 finished
 #3 finished
 */

#2. Using DispatchGroup, DispatchGroup's wait(), DispatchGroup's enter() and DispatchGroup's leave()

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let queue = DispatchQueue(label: "com.company.app.queue", attributes: .concurrent)
let group = DispatchGroup()

group.enter()
queue.async {
    print("#1 started")
    Thread.sleep(forTimeInterval: 5)
    print("#1 finished")
    group.leave()
}

group.enter()
queue.async {
    print("#2 started")
    Thread.sleep(forTimeInterval: 2)
    print("#2 finished")
    group.leave()
}

queue.async {
    group.wait()
    print("#3 finished")
}

/*
 prints:
 #1 started
 #2 started
 #2 finished
 #1 finished
 #3 finished
 */

Note that you can also mix DispatchGroup wait() with DispatchQueue async(group:qos:flags:execute:) or mix DispatchGroup enter() and DispatchGroup leave() with DispatchGroup notify(qos:flags:queue:execute:).


#3. Using Dispatch?Work?Item?Flags barrier and DispatchQueue's async(group:qos:flags:execute:)

Grand Central Dispatch Tutorial for Swift 4: Part 1/2 article from Raywenderlich.com gives a definition for barriers:

Dispatch barriers are a group of functions acting as a serial-style bottleneck when working with concurrent queues. When you submit a DispatchWorkItem to a dispatch queue you can set flags to indicate that it should be the only item executed on the specified queue for that particular time. This means that all items submitted to the queue prior to the dispatch barrier must complete before the DispatchWorkItem will execute.

Usage:

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let queue = DispatchQueue(label: "com.company.app.queue", attributes: .concurrent)

queue.async {
    print("#1 started")
    Thread.sleep(forTimeInterval: 5)
    print("#1 finished")
}

queue.async {
    print("#2 started")
    Thread.sleep(forTimeInterval: 2)
    print("#2 finished")
}

queue.async(flags: .barrier) {
    print("#3 finished")
}

/*
 prints:
 #1 started
 #2 started
 #2 finished
 #1 finished
 #3 finished
 */

#4. Using DispatchWorkItem, Dispatch?Work?Item?Flags's barrier and DispatchQueue's async(execute:)

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let queue = DispatchQueue(label: "com.company.app.queue", attributes: .concurrent)

queue.async {
    print("#1 started")
    Thread.sleep(forTimeInterval: 5)
    print("#1 finished")
}

queue.async {
    print("#2 started")
    Thread.sleep(forTimeInterval: 2)
    print("#2 finished")
}

let dispatchWorkItem = DispatchWorkItem(qos: .default, flags: .barrier) {
    print("#3 finished")
}

queue.async(execute: dispatchWorkItem)

/*
 prints:
 #1 started
 #2 started
 #2 finished
 #1 finished
 #3 finished
 */

#5. Using DispatchSemaphore, DispatchSemaphore's wait() and DispatchSemaphore's signal()

Soroush Khanlou wrote the following lines in The GCD Handbook blog post:

Using a semaphore, we can block a thread for an arbitrary amount of time, until a signal from another thread is sent. Semaphores, like the rest of GCD, are thread-safe, and they can be triggered from anywhere. Semaphores can be used when there’s an asynchronous API that you need to make synchronous, but you can’t modify it.

Apple Developer API Reference also gives the following discussion for DispatchSemaphore init(value:?) initializer:

Passing zero for the value is useful for when two threads need to reconcile the completion of a particular event. Passing a value greater than zero is useful for managing a finite pool of resources, where the pool size is equal to the value.

Usage:

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let queue = DispatchQueue(label: "com.company.app.queue", attributes: .concurrent)
let semaphore = DispatchSemaphore(value: 0)

queue.async {
    print("#1 started")
    Thread.sleep(forTimeInterval: 5)
    print("#1 finished")
    semaphore.signal()
}

queue.async {
    print("#2 started")
    Thread.sleep(forTimeInterval: 2)
    print("#2 finished")
    semaphore.signal()
}

queue.async {
    semaphore.wait()
    semaphore.wait()    
    print("#3 finished")
}

/*
 prints:
 #1 started
 #2 started
 #2 finished
 #1 finished
 #3 finished
 */

#6. Using OperationQueue and Operation's addDependency(_:)

The Apple Developer API Reference states about Operation?Queue:

Operation queues use the libdispatch library (also known as Grand Central Dispatch) to initiate the execution of their operations.

Usage:

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let operationQueue = OperationQueue()

let blockOne = BlockOperation {
    print("#1 started")
    Thread.sleep(forTimeInterval: 5)
    print("#1 finished")
}

let blockTwo = BlockOperation {
    print("#2 started")
    Thread.sleep(forTimeInterval: 2)
    print("#2 finished")
}

let blockThree = BlockOperation {
    print("#3 finished")
}

blockThree.addDependency(blockOne)
blockThree.addDependency(blockTwo)

operationQueue.addOperations([blockThree, blockTwo, blockOne], waitUntilFinished: false)

/*
 prints:
 #1 started
 #2 started
 #2 finished
 #1 finished
 #3 finished
 or
 #2 started
 #1 started
 #2 finished
 #1 finished
 #3 finished
 */

#7. Using OperationQueue and OperationQueue's addBarrierBlock(_:) (requires iOS 13)

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let operationQueue = OperationQueue()

let blockOne = BlockOperation {
    print("#1 started")
    Thread.sleep(forTimeInterval: 5)
    print("#1 finished")
}

let blockTwo = BlockOperation {
    print("#2 started")
    Thread.sleep(forTimeInterval: 2)
    print("#2 finished")
}

operationQueue.addOperations([blockTwo, blockOne], waitUntilFinished: false)
operationQueue.addBarrierBlock {
    print("#3 finished")
}

/*
 prints:
 #1 started
 #2 started
 #2 finished
 #1 finished
 #3 finished
 or
 #2 started
 #1 started
 #2 finished
 #1 finished
 #3 finished
 */

How to printf "unsigned long" in C?

  • %lu for unsigned long
  • %llu for unsigned long long

Passing parameters from jsp to Spring Controller method

Your controller method should be like this:

@RequestMapping(value = " /<your mapping>/{id}", method=RequestMethod.GET)
public String listNotes(@PathVariable("id")int id,Model model) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    int id = 2323;  // Currently passing static values for testing
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes",this.notesService.listNotesBySectionId(id,person));
    return "note";
}

Use the id in your code, call the controller method from your JSP as:

/{your mapping}/{your id}

UPDATE:

Change your jsp code to:

<c:forEach items="${listNotes}" var="notices" varStatus="status">
    <tr>
        <td>${notices.noticesid}</td>
        <td>${notices.notetext}</td>
        <td>${notices.notetag}</td>
        <td>${notices.notecolor}</td>
        <td>${notices.sectionid}</td>
        <td>${notices.canvasid}</td>
        <td>${notices.canvasnName}</td>
        <td>${notices.personid}</td>
        <td><a href="<c:url value='/editnote/${listNotes[status.index].noticesid}' />" >Edit</a></td>
        <td><a href="<c:url value='/removenote/${listNotes[status.index].noticesid}' />" >Delete</a></td>
    </tr>
</c:forEach>

Uncaught TypeError: .indexOf is not a function

I was getting e.data.indexOf is not a function error, after debugging it, I found that it was actually a TypeError, which meant, indexOf() being a function is applicable to strings, so I typecasted the data like the following and then used the indexOf() method to make it work

e.data.toString().indexOf('<stringToBeMatchedToPosition>')

Not sure if my answer was accurate to the question, but yes shared my opinion as i faced a similar kind of situation.

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

You should consider to specify SMTP configuration data in config file and do not overwrite them in a code - see SMTP configuration data at http://www.systemnetmail.com/faq/4.1.aspx

<system.net>
            <mailSettings>
                <smtp deliveryMethod="Network" from="[email protected]">
                    <network defaultCredentials="false" host="smtp.example.com" port="25" userName="[email protected]" password="password"/>
                </smtp>
            </mailSettings>
        </system.net>

'printf' vs. 'cout' in C++

I'm surprised that everyone in this question claims that std::cout is way better than printf, even if the question just asked for differences. Now, there is a difference - std::cout is C++, and printf is C (however, you can use it in C++, just like almost anything else from C). Now, I'll be honest here; both printf and std::cout have their advantages.

Real differences

Extensibility

std::cout is extensible. I know that people will say that printf is extensible too, but such extension is not mentioned in the C standard (so you would have to use non-standard features - but not even common non-standard feature exists), and such extensions are one letter (so it's easy to conflict with an already-existing format).

Unlike printf, std::cout depends completely on operator overloading, so there is no issue with custom formats - all you do is define a subroutine taking std::ostream as the first argument and your type as second. As such, there are no namespace problems - as long you have a class (which isn't limited to one character), you can have working std::ostream overloading for it.

However, I doubt that many people would want to extend ostream (to be honest, I rarely saw such extensions, even if they are easy to make). However, it's here if you need it.

Syntax

As it could be easily noticed, both printf and std::cout use different syntax. printf uses standard function syntax using pattern string and variable-length argument lists. Actually, printf is a reason why C has them - printf formats are too complex to be usable without them. However, std::cout uses a different API - the operator << API that returns itself.

Generally, that means the C version will be shorter, but in most cases it won't matter. The difference is noticeable when you print many arguments. If you have to write something like Error 2: File not found., assuming error number, and its description is placeholder, the code would look like this. Both examples work identically (well, sort of, std::endl actually flushes the buffer).

printf("Error %d: %s.\n", id, errors[id]);
std::cout << "Error " << id << ": " << errors[id] << "." << std::endl;

While this doesn't appear too crazy (it's just two times longer), things get more crazy when you actually format arguments, instead of just printing them. For example, printing of something like 0x0424 is just crazy. This is caused by std::cout mixing state and actual values. I never saw a language where something like std::setfill would be a type (other than C++, of course). printf clearly separates arguments and actual type. I really would prefer to maintain the printf version of it (even if it looks kind of cryptic) compared to iostream version of it (as it contains too much noise).

printf("0x%04x\n", 0x424);
std::cout << "0x" << std::hex << std::setfill('0') << std::setw(4) << 0x424 << std::endl;

Translation

This is where the real advantage of printf lies. The printf format string is well... a string. That makes it really easy to translate, compared to operator << abuse of iostream. Assuming that the gettext() function translates, and you want to show Error 2: File not found., the code to get translation of the previously shown format string would look like this:

printf(gettext("Error %d: %s.\n"), id, errors[id]);

Now, let's assume that we translate to Fictionish, where the error number is after the description. The translated string would look like %2$s oru %1$d.\n. Now, how to do it in C++? Well, I have no idea. I guess you can make fake iostream which constructs printf that you can pass to gettext, or something, for purposes of translation. Of course, $ is not C standard, but it's so common that it's safe to use in my opinion.

Not having to remember/look-up specific integer type syntax

C has lots of integer types, and so does C++. std::cout handles all types for you, while printf requires specific syntax depending on an integer type (there are non-integer types, but the only non-integer type you will use in practice with printf is const char * (C string, can be obtained using to_c method of std::string)). For instance, to print size_t, you need to use %zd, while int64_t will require using %"PRId64". The tables are available at http://en.cppreference.com/w/cpp/io/c/fprintf and http://en.cppreference.com/w/cpp/types/integer.

You can't print the NUL byte, \0

Because printf uses C strings as opposed to C++ strings, it cannot print NUL byte without specific tricks. In certain cases it's possible to use %c with '\0' as an argument, although that's clearly a hack.

Differences nobody cares about

Performance

Update: It turns out that iostream is so slow that it's usually slower than your hard drive (if you redirect your program to file). Disabling synchronization with stdio may help, if you need to output lots of data. If the performance is a real concern (as opposed to writing several lines to STDOUT), just use printf.

Everyone thinks that they care about performance, but nobody bothers to measure it. My answer is that I/O is bottleneck anyway, no matter if you use printf or iostream. I think that printf could be faster from a quick look into assembly (compiled with clang using the -O3 compiler option). Assuming my error example, printf example does way fewer calls than the cout example. This is int main with printf:

main:                                   @ @main
@ BB#0:
        push    {lr}
        ldr     r0, .LCPI0_0
        ldr     r2, .LCPI0_1
        mov     r1, #2
        bl      printf
        mov     r0, #0
        pop     {lr}
        mov     pc, lr
        .align  2
@ BB#1:

You can easily notice that two strings, and 2 (number) are pushed as printf arguments. That's about it; there is nothing else. For comparison, this is iostream compiled to assembly. No, there is no inlining; every single operator << call means another call with another set of arguments.

main:                                   @ @main
@ BB#0:
        push    {r4, r5, lr}
        ldr     r4, .LCPI0_0
        ldr     r1, .LCPI0_1
        mov     r2, #6
        mov     r3, #0
        mov     r0, r4
        bl      _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
        mov     r0, r4
        mov     r1, #2
        bl      _ZNSolsEi
        ldr     r1, .LCPI0_2
        mov     r2, #2
        mov     r3, #0
        mov     r4, r0
        bl      _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
        ldr     r1, .LCPI0_3
        mov     r0, r4
        mov     r2, #14
        mov     r3, #0
        bl      _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
        ldr     r1, .LCPI0_4
        mov     r0, r4
        mov     r2, #1
        mov     r3, #0
        bl      _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
        ldr     r0, [r4]
        sub     r0, r0, #24
        ldr     r0, [r0]
        add     r0, r0, r4
        ldr     r5, [r0, #240]
        cmp     r5, #0
        beq     .LBB0_5
@ BB#1:                                 @ %_ZSt13__check_facetISt5ctypeIcEERKT_PS3_.exit
        ldrb    r0, [r5, #28]
        cmp     r0, #0
        beq     .LBB0_3
@ BB#2:
        ldrb    r0, [r5, #39]
        b       .LBB0_4
.LBB0_3:
        mov     r0, r5
        bl      _ZNKSt5ctypeIcE13_M_widen_initEv
        ldr     r0, [r5]
        mov     r1, #10
        ldr     r2, [r0, #24]
        mov     r0, r5
        mov     lr, pc
        mov     pc, r2
.LBB0_4:                                @ %_ZNKSt5ctypeIcE5widenEc.exit
        lsl     r0, r0, #24
        asr     r1, r0, #24
        mov     r0, r4
        bl      _ZNSo3putEc
        bl      _ZNSo5flushEv
        mov     r0, #0
        pop     {r4, r5, lr}
        mov     pc, lr
.LBB0_5:
        bl      _ZSt16__throw_bad_castv
        .align  2
@ BB#6:

However, to be honest, this means nothing, as I/O is the bottleneck anyway. I just wanted to show that iostream is not faster because it's "type safe". Most C implementations implement printf formats using computed goto, so the printf is as fast as it can be, even without compiler being aware of printf (not that they aren't - some compilers can optimize printf in certain cases - constant string ending with \n is usually optimized to puts).

Inheritance

I don't know why you would want to inherit ostream, but I don't care. It's possible with FILE too.

class MyFile : public FILE {}

Type safety

True, variable length argument lists have no safety, but that doesn't matter, as popular C compilers can detect problems with printf format string if you enable warnings. In fact, Clang can do that without enabling warnings.

$ cat safety.c

#include <stdio.h>

int main(void) {
    printf("String: %s\n", 42);
    return 0;
}

$ clang safety.c

safety.c:4:28: warning: format specifies type 'char *' but the argument has type 'int' [-Wformat]
    printf("String: %s\n", 42);
                    ~~     ^~
                    %d
1 warning generated.
$ gcc -Wall safety.c
safety.c: In function ‘main’:
safety.c:4:5: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
     printf("String: %s\n", 42);
     ^

what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?

In a Object Relational Mapping context, every object needs to have a unique identifier. You use the @Id annotation to specify the primary key of an entity.

The @GeneratedValue annotation is used to specify how the primary key should be generated. In your example you are using an Identity strategy which

Indicates that the persistence provider must assign primary keys for the entity using a database identity column.

There are other strategies, you can see more here.

One line if/else condition in linux shell scripting

It looks as if you were on the right track. You just need to add the else statement after the ";" following the "then" statement. Also I would split the first line from the second line with a semicolon instead of joining it with "&&".

maxline='cat journald.conf | grep "#SystemMaxUse="'; if [ $maxline == "#SystemMaxUse=" ]; then sed 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf > journald.conf2 && mv journald.conf2 journald.conf; else echo "This file has been edited. You'll need to do it manually."; fi

Also in your original script, when declaring maxline you used back-ticks "`" instead of single quotes "'" which might cause problems.

How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

Use Radium!

The following is an example from their website:

_x000D_
_x000D_
var Radium = require('radium');_x000D_
var React = require('react');_x000D_
var color = require('color');_x000D_
_x000D_
@Radium_x000D_
class Button extends React.Component {_x000D_
  static propTypes = {_x000D_
    kind: React.PropTypes.oneOf(['primary', 'warning']).isRequired_x000D_
  };_x000D_
_x000D_
  render() {_x000D_
    // Radium extends the style attribute to accept an array. It will merge_x000D_
    // the styles in order. We use this feature here to apply the primary_x000D_
    // or warning styles depending on the value of the `kind` prop. Since its_x000D_
    // all just JavaScript, you can use whatever logic you want to decide which_x000D_
    // styles are applied (props, state, context, etc)._x000D_
    return (_x000D_
      <button_x000D_
        style={[_x000D_
          styles.base,_x000D_
          styles[this.props.kind]_x000D_
        ]}>_x000D_
        {this.props.children}_x000D_
      </button>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
// You can create your style objects dynamically or share them for_x000D_
// every instance of the component._x000D_
var styles = {_x000D_
  base: {_x000D_
    color: '#fff',_x000D_
_x000D_
    // Adding interactive state couldn't be easier! Add a special key to your_x000D_
    // style object (:hover, :focus, :active, or @media) with the additional rules._x000D_
    ':hover': {_x000D_
      background: color('#0074d9').lighten(0.2).hexString()_x000D_
    }_x000D_
  },_x000D_
_x000D_
  primary: {_x000D_
    background: '#0074D9'_x000D_
  },_x000D_
_x000D_
  warning: {_x000D_
    background: '#FF4136'_x000D_
  }_x000D_
};
_x000D_
_x000D_
_x000D_

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

Since Django 2.x, on_delete is required.

Django Documentation

Deprecated since version 1.9: on_delete will become a required argument in Django 2.0. In older versions it defaults to CASCADE.

Routing HTTP Error 404.0 0x80070002

The problem for me was a new server that System.Web.Routing was of version 3.5 while web.config requested version 4.0.0.0. The resolution was

%WINDIR%\Framework\v4.0.30319\aspnet_regiis -i

%WINDIR%\Framework64\v4.0.30319\aspnet_regiis -i

adding 30 minutes to datetime php/mysql

MySQL has a function called ADDTIME for adding two times together - so you can do the whole thing in MySQL (provided you're using >= MySQL 4.1.3).

Something like (untested):

SELECT * FROM my_table WHERE ADDTIME(endTime + '0:30:00') < CONVERT_TZ(NOW(), @@global.time_zone, 'GMT')

How to connect to mysql with laravel?

In Laravel 5, there is a .env file,

It looks like

APP_ENV=local
APP_DEBUG=true
APP_KEY=YOUR_API_KEY

DB_HOST=YOUR_HOST
DB_DATABASE=YOUR_DATABASE
DB_USERNAME=YOUR_USERNAME
DB_PASSWORD=YOUR_PASSWORD

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null

Edit that .env There is .env.sample is there , try to create from that if no such .env file found.

C/C++ maximum stack size of program

In Visual Studio the default stack size is 1 MB i think, so with a recursion depth of 10,000 each stack frame can be at most ~100 bytes which should be sufficient for a DFS algorithm.

Most compilers including Visual Studio let you specify the stack size. On some (all?) linux flavours the stack size isn't part of the executable but an environment variable in the OS. You can then check the stack size with ulimit -s and set it to a new value with for example ulimit -s 16384.

Here's a link with default stack sizes for gcc.

DFS without recursion:

std::stack<Node> dfs;
dfs.push(start);
do {
    Node top = dfs.top();
    if (top is what we are looking for) {
       break;
    }
    dfs.pop();
    for (outgoing nodes from top) {
        dfs.push(outgoing node);
    }
} while (!dfs.empty())

How to create a Date in SQL Server given the Day, Month and Year as Integers

The following code should work on all versions of sql server I believe:

SELECT CAST(CONCAT(CAST(@Year AS VARCHAR(4)), '-',CAST(@Month AS VARCHAR(2)), '-',CAST(@Day AS VARCHAR(2))) AS DATE)

android set button background programmatically

R.color.red is an ID (which is also an int), but is not a color.

Use one of the following instead:

// If you're in an activity:
Button11.setBackgroundColor(getResources().getColor(R.color.red));
// OR, if you're not: 
Button11.setBackgroundColor(Button11.getContext().getResources().getColor(R.color.red));

Or, alternatively:

Button11.setBackgroundColor(Color.RED); // From android.graphics.Color

Or, for more pro skills:

Button11.setBackgroundColor(0xFFFF0000); // 0xAARRGGBB

ExecuteNonQuery doesn't return results

From MSDN: SqlCommand.ExecuteNonQuery Method

You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.

Although the ExecuteNonQuery returns no rows, any output parameters or return values mapped to parameters are populated with data.

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.

You are using SELECT query, thus you get -1

Format output string, right alignment

You can align it like that:

print('{:>8} {:>8} {:>8}'.format(*words))

where > means "align to right" and 8 is the width for specific value.

And here is a proof:

>>> for line in [[1, 128, 1298039], [123388, 0, 2]]:
    print('{:>8} {:>8} {:>8}'.format(*line))


       1      128  1298039
  123388        0        2

Ps. *line means the line list will be unpacked, so .format(*line) works similarly to .format(line[0], line[1], line[2]) (assuming line is a list with only three elements).

How to frame two for loops in list comprehension python

The appropriate LC would be

[entry for tag in tags for entry in entries if tag in entry]

The order of the loops in the LC is similar to the ones in nested loops, the if statements go to the end and the conditional expressions go in the beginning, something like

[a if a else b for a in sequence]

See the Demo -

>>> tags = [u'man', u'you', u'are', u'awesome']
>>> entries = [[u'man', u'thats'],[ u'right',u'awesome']]
>>> [entry for tag in tags for entry in entries if tag in entry]
[[u'man', u'thats'], [u'right', u'awesome']]
>>> result = []
    for tag in tags:
        for entry in entries:
            if tag in entry:
                result.append(entry)


>>> result
[[u'man', u'thats'], [u'right', u'awesome']]

EDIT - Since, you need the result to be flattened, you could use a similar list comprehension and then flatten the results.

>>> result = [entry for tag in tags for entry in entries if tag in entry]
>>> from itertools import chain
>>> list(chain.from_iterable(result))
[u'man', u'thats', u'right', u'awesome']

Adding this together, you could just do

>>> list(chain.from_iterable(entry for tag in tags for entry in entries if tag in entry))
[u'man', u'thats', u'right', u'awesome']

You use a generator expression here instead of a list comprehension. (Perfectly matches the 79 character limit too (without the list call))

Removing all line breaks and adding them after certain text

You can also try this in Notepad++

  • Highlight the lines you want to join (ctrl + a to select all)
  • Choose Edit -> Line Operations -> Join Lines

Finding all possible permutations of a given string in python

Here is another approach different from what @Adriano and @illerucis posted. This has a better runtime, you can check that yourself by measuring the time:

def removeCharFromStr(str, index):
    endIndex = index if index == len(str) else index + 1
    return str[:index] + str[endIndex:]

# 'ab' -> a + 'b', b + 'a'
# 'abc' ->  a + bc, b + ac, c + ab
#           a + cb, b + ca, c + ba
def perm(str):
    if len(str) <= 1:
        return {str}
    permSet = set()
    for i, c in enumerate(str):
        newStr = removeCharFromStr(str, i)
        retSet = perm(newStr)
        for elem in retSet:
            permSet.add(c + elem)
    return permSet

For an arbitrary string "dadffddxcf" it took 1.1336 sec for the permutation library, 9.125 sec for this implementation and 16.357 secs for @Adriano's and @illerucis' version. Of course you can still optimize it.

How to call Oracle MD5 hash function?

@user755806 I do not believe that your question was answered. I took your code but used the 'foo' example string, added a lower function and also found the length of the hash returned. In sqlplus or Oracle's sql developer Java database client you can use this to call the md5sum of a value. The column formats clean up the presentation.

column hash_key format a34;
column hash_key_len format 999999;
select dbms_obfuscation_toolkit.md5(
          input => UTL_RAW.cast_to_raw('foo')) as hash_key,
       length(dbms_obfuscation_toolkit.md5(
          input => UTL_RAW.cast_to_raw('foo'))) as hash_key_len
 from dual;

The result set

HASH_KEY                           HASH_KEY_LEN
---------------------------------- ------------
acbd18db4cc2f85cedef654fccc4a4d8             32

is the same value that is returned from a Linux md5sum command.

echo -n foo | md5sum
acbd18db4cc2f85cedef654fccc4a4d8  -
  1. Yes you can call or execute the sql statement directly in sqlplus or sql developer. I tested the sql statement in both clients against 11g.
  2. You can use any C, C#, Java or other programming language that can send a statement to the database. It is the database on the other end of the call that needs to be able to understand the sql statement. In the case of 11 g, the code will work.
  3. @tbone provides an excellent warning about the deprecation of the dbms_obfuscation_toolkit. However, that does not mean your code is unusable in 12c. It will work but you will want to eventually switch to dbms_crypto package. dbms_crypto is not available in my version of 11g.

Difference between View and Request scope in managed beans

A @ViewScoped bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null or void (and thus navigates back to the same view). Once you refresh the page, or return a non-null string (even an empty string!) navigation outcome, then the view scope will end.

A @RequestScoped bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.

A @ViewScoped bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped bean. Every view has its own unique @ViewScoped bean.

See also:

How can I initialize base class member variables in derived class constructor?

# include<stdio.h>
# include<iostream>
# include<conio.h>

using namespace std;

class Base{
    public:
        Base(int i, float f, double d): i(i), f(f), d(d)
        {
        }
    virtual void Show()=0;
    protected:
        int i;
        float f;
        double d;
};


class Derived: public Base{
    public:
        Derived(int i, float f, double d): Base( i, f, d)
        {
        }
        void Show()
        {
            cout<< "int i = "<<i<<endl<<"float f = "<<f<<endl <<"double d = "<<d<<endl;
        }
};

int main(){
    Base * b = new Derived(10, 1.2, 3.89);
    b->Show();
    return 0;
}

It's a working example in case you want to initialize the Base class data members present in the Derived class object, whereas you want to push these values interfacing via Derived class constructor call.

How to toggle (hide / show) sidebar div using jQuery

$(document).ready(function () {
    $(".trigger").click(function () {
        $("#sidebar").toggle("fast");
        $("#sidebar").toggleClass("active");
        return false;
    });
});


<div>
    <a class="trigger" href="#">
        <img id="icon-menu" alt='menu' height='50' src="Images/Push Pin.png" width='50' />
    </a>
</div>
<div id="sidebar">
</div>

Instead #sidebar give the id of ur div.

How can I get date in application run by node.js?

To create a new Date object in node.js, or JavaScript in general, just call it’s initializer

var d = new Date();

var d = new Date(dateString);

var d = new Date(jsonDate);

var d = new Date(year, month, day);

var d = new Date(year, month, day, hour, minute, second, millisecond);

Remember that Date objects can only be instantiated by calling Date or using it as a constructor; unlike other JavaScript object types, Date objects have no literal syntax

google maps v3 marker info window on mouseover

Thanks to duncan answer, I end up with this:

marker.addListener('mouseover', () => infoWindow.open(map, marker))
marker.addListener('mouseout', () => infoWindow.close())

How to duplicate a whole line in Vim?

If you want another way:

"ayy: This will store the line in buffer a.

"ap: This will put the contents of buffer a at the cursor.

There are many variations on this.

"a5yy: This will store the 5 lines in buffer a.

See "Vim help files for more fun.

Pretty Printing a pandas dataframe

A simple approach is to output as html, which pandas does out of the box:

df.to_html('temp.html')

Add an image in a WPF button

In the case of a 'missing' image there are several things to consider:

  1. When XAML can't locate a resource it might ignore it (when it won't throw a XamlParseException)

  2. The resource must be properly added and defined:

    • Make sure it exists in your project where expected.

    • Make sure it is built with your project as a resource.

      (Right click ? Properties ? BuildAction='Resource')

Snippet

Another thing to try in similar cases, which is also useful for reusing of the image (or any other resource):

Define your image as a resource in your XAML:

<UserControl.Resources>
     <Image x:Key="MyImage" Source.../>
</UserControl.Resources>

And later use it in your desired control(s):

<Button Content="{StaticResource MyImage}" />

SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns

I think you should make a subquery to do grouping. In this case inner subquery returns few rows and you don't need a CASE statement. So I think this is going to be faster:

select Detail.ReceiptDate AS 'DATE',
       SUM(TotalMailed),
       SUM(TotalReturnMail),
       SUM(TraceReturnedMail)

from
(

select SentDate AS 'ReceiptDate', 
       count('TotalMailed') AS TotalMailed, 
       0 as TotalReturnMail, 
       0 as TraceReturnedMail
from MailDataExtract
where sentdate is not null
GROUP BY SentDate

UNION ALL
select MDE.ReturnMailDate AS 'ReceiptDate', 
       0 AS TotalMailed, 
       count(TotalReturnMail) as TotalReturnMail, 
       0 as TraceReturnedMail
from MailDataExtract MDE
where MDE.ReturnMailDate is not null
GROUP BY  MDE.ReturnMailDate

UNION ALL

select MDE.ReturnMailDate AS 'ReceiptDate', 
       0 AS TotalMailed, 
       0 as TotalReturnMail, 
       count(TraceReturnedMail) as TraceReturnedMail

from MailDataExtract MDE
    inner join DTSharedData.dbo.ScanData SD 
        ON SD.ScanDataID = MDE.ReturnScanDataID
   where MDE.ReturnMailDate is not null AND SD.ReturnMailTypeID = 1
GROUP BY MDE.ReturnMailDate

) as Detail
GROUP BY Detail.ReceiptDate
ORDER BY 1