Programs & Examples On #Constructor chaining

Constructor chaining is the process of calling the super class constructor by the subclass constructors in the inheritance tree when creating an object.

How to do constructor chaining in C#

All those answers are good, but I'd like to add a note on constructors with a little more complex initializations.

class SomeClass {
    private int StringLength;
    SomeClass(string x) {
         // this is the logic that shall be executed for all constructors.
         // you dont want to duplicate it.
         StringLength = x.Length;
    }
    SomeClass(int a, int b): this(TransformToString(a, b)) {
    }
    private static string TransformToString(int a, int b) {
         var c = a + b;
         return $"{a} + {b} = {c}";
    }
}

Allthogh this example might as well be solved without this static function, the static function allows for more complex logic, or even calling methods from somewhere else.

JQuery confirm dialog

Have you tried using the official JQueryUI implementation (not jQuery only) : ?

Convert textbox text to integer

You don't need to write a converter, just do this in your handler/codebehind:

int i = Convert.ToInt32(txtMyTextBox.Text);

OR

int i = int.Parse(txtMyTextBox.Text);

The Text property of your textbox is a String type, so you have to perform the conversion in the code.

Matplotlib-Animation "No MovieWriters Available"

I had the following error while running the cell. enter image description here

This may be due to not having ffmpeg in your system. Try the following command in your terminal.

sudo apt install ffmpeg

This works for me. I hope it will work out for you too.

How do I make an HTTP request in Swift?

KISS answer:

URLSession.shared.dataTask(with: URL(string: "https://google.com")!) {(data, response, error) in
    print(String(data: data!, encoding: .utf8))
}.resume()

How do I add the contents of an iterable to a set?

for item in items:
   extant_set.add(item)

For the record, I think the assertion that "There should be one-- and preferably only one --obvious way to do it." is bogus. It makes an assumption that many technical minded people make, that everyone thinks alike. What is obvious to one person is not so obvious to another.

I would argue that my proposed solution is clearly readable, and does what you ask. I don't believe there are any performance hits involved with it--though I admit I might be missing something. But despite all of that, it might not be obvious and preferable to another developer.

MySQL match() against() - order by relevance and column?

Just adding for who might need.. Don't forget to alter the table!

ALTER TABLE table_name ADD FULLTEXT(column_name);

How to quietly remove a directory with content in PowerShell

This worked for me:

Remove-Item C:\folder_name -Force -Recurse

How to list AD group membership for AD users using input list?

Get-ADPrincipalGroupMembership username | select name

Got it from another answer but the script works magic. :)

ignoring any 'bin' directory on a git project

I didn't see it mentioned here, but this appears to be case sensitive. Once I changed to /Bin the files were ignored as expected.

Renaming Columns in an SQL SELECT Statement

You can alias the column names one by one, like so

SELECT col1 as `MyNameForCol1`, col2 as `MyNameForCol2` 
FROM `foobar`

Edit You can access INFORMATION_SCHEMA.COLUMNS directly to mangle a new alias like so. However, how you fit this into a query is beyond my MySql skills :(

select CONCAT('Foobar_', COLUMN_NAME)
from INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME = 'Foobar'

How to iterate over the files of a certain directory, in Java?

Use java.io.File.listFiles
Or
If you want to filter the list prior to iteration (or any more complicated use case), use apache-commons FileUtils. FileUtils.listFiles

How to increase timeout for a single test case in mocha

(since I ran into this today)

Be careful when using ES2015 fat arrow syntax:

This will fail :

it('accesses the network', done => {

  this.timeout(500); // will not work

  // *this* binding refers to parent function scope in fat arrow functions!
  // i.e. the *this* object of the describe function

  done();
});

EDIT: Why it fails:

As @atoth mentions in the comments, fat arrow functions do not have their own this binding. Therefore, it's not possible for the it function to bind to this of the callback and provide a timeout function.

Bottom line: Don't use arrow functions for functions that need an increased timeout.

How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

Half a second is 500,000,000 nanoseconds, so your code should read:

tim.tv_sec  = 0;
tim.tv_nsec = 500000000L;

As things stand, you code is sleeping for 1.0000005s (1s + 500ns).

Dead simple example of using Multiprocessing Queue, Pool and Locking

The best solution for your problem is to utilize a Pool. Using Queues and having a separate "queue feeding" functionality is probably overkill.

Here's a slightly rearranged version of your program, this time with only 2 processes coralled in a Pool. I believe it's the easiest way to go, with minimal changes to original code:

import multiprocessing
import time

data = (
    ['a', '2'], ['b', '4'], ['c', '6'], ['d', '8'],
    ['e', '1'], ['f', '3'], ['g', '5'], ['h', '7']
)

def mp_worker((inputs, the_time)):
    print " Processs %s\tWaiting %s seconds" % (inputs, the_time)
    time.sleep(int(the_time))
    print " Process %s\tDONE" % inputs

def mp_handler():
    p = multiprocessing.Pool(2)
    p.map(mp_worker, data)

if __name__ == '__main__':
    mp_handler()

Note that mp_worker() function now accepts a single argument (a tuple of the two previous arguments) because the map() function chunks up your input data into sublists, each sublist given as a single argument to your worker function.

Output:

Processs a  Waiting 2 seconds
Processs b  Waiting 4 seconds
Process a   DONE
Processs c  Waiting 6 seconds
Process b   DONE
Processs d  Waiting 8 seconds
Process c   DONE
Processs e  Waiting 1 seconds
Process e   DONE
Processs f  Waiting 3 seconds
Process d   DONE
Processs g  Waiting 5 seconds
Process f   DONE
Processs h  Waiting 7 seconds
Process g   DONE
Process h   DONE

Edit as per @Thales comment below:

If you want "a lock for each pool limit" so that your processes run in tandem pairs, ala:

A waiting B waiting | A done , B done | C waiting , D waiting | C done, D done | ...

then change the handler function to launch pools (of 2 processes) for each pair of data:

def mp_handler():
    subdata = zip(data[0::2], data[1::2])
    for task1, task2 in subdata:
        p = multiprocessing.Pool(2)
        p.map(mp_worker, (task1, task2))

Now your output is:

 Processs a Waiting 2 seconds
 Processs b Waiting 4 seconds
 Process a  DONE
 Process b  DONE
 Processs c Waiting 6 seconds
 Processs d Waiting 8 seconds
 Process c  DONE
 Process d  DONE
 Processs e Waiting 1 seconds
 Processs f Waiting 3 seconds
 Process e  DONE
 Process f  DONE
 Processs g Waiting 5 seconds
 Processs h Waiting 7 seconds
 Process g  DONE
 Process h  DONE

.Net System.Mail.Message adding multiple "To" addresses

You can do this either with multiple System.Net.Mail.MailAddress objects or you can provide a single string containing all of the addresses separated by commas

Finding three elements in an array whose sum is closest to a given number

Another solution that checks and fails early:

public boolean solution(int[] input) {
        int length = input.length;

        if (length < 3) {
            return false;
        }

        // x + y + z = 0  => -z = x + y
        final Set<Integer> z = new HashSet<>(length);
        int zeroCounter = 0, sum; // if they're more than 3 zeros we're done

        for (int element : input) {
            if (element < 0) {
                z.add(element);
            }

            if (element == 0) {
                ++zeroCounter;
                if (zeroCounter >= 3) {
                    return true;
                }
            }
        }

        if (z.isEmpty() || z.size() == length || (z.size() + zeroCounter == length)) {
            return false;
        } else {
            for (int x = 0; x < length; ++x) {
                for (int y = x + 1; y < length; ++y) {
                    sum = input[x] + input[y]; // will use it as inverse addition
                    if (sum < 0) {
                        continue;
                    }
                    if (z.contains(sum * -1)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

I added some unit tests here: GivenArrayReturnTrueIfThreeElementsSumZeroTest.

If the set is using too much space I can easily use a java.util.BitSet that will use O(n/w) space.

PHP parse/syntax errors; and how to solve them

Unexpected T_LNUMBER

The token T_LNUMBER refers to a "long" / number.

  1. Invalid variable names

    In PHP, and most other programming languages, variables cannot start with a number. The first character must be alphabetic or an underscore.

    $1   // Bad
    $_1  // Good
    

    *

    • Quite often comes up for using preg_replace-placeholders "$1" in PHP context:

      #                         ?            ?  ?
      preg_replace("/#(\w+)/e",  strtopupper($1) )
      

      Where the callback should have been quoted. (Now the /e regex flag has been deprecated. But it's sometimes still misused in preg_replace_callback functions.)

    • The same identifier constraint applies to object properties, btw.

             ?
      $json->0->value
      
    • While the tokenizer/parser does not allow a literal $1 as variable name, one could use ${1} or ${"1"}. Which is a syntactic workaround for non-standard identifiers. (It's best to think of it as a local scope lookup. But generally: prefer plain arrays for such cases!)

    • Amusingly, but very much not recommended, PHPs parser allows Unicode-identifiers; such that $? would be valid. (Unlike a literal 1).

  2. Stray array entry

    An unexpected long can also occur for array declarations - when missing , commas:

    #            ? ?
    $xy = array(1 2 3);
    

    Or likewise function calls and declarations, and other constructs:

    • func(1, 2 3);
    • function xy($z 2);
    • for ($i=2 3<$z)

    So usually there's one of ; or , missing for separating lists or expressions.

  3. Misquoted HTML

    And again, misquoted strings are a frequent source of stray numbers:

    #                 ? ?          
    echo "<td colspan="3">something bad</td>";
    

    Such cases should be treated more or less like Unexpected T_STRING errors.

  4. Other identifiers

    Neither functions, classes, nor namespaces can be named beginning with a number either:

             ?
    function 123shop() {
    

    Pretty much the same as for variable names.

Trying to start a service on boot on Android

I faced with this problem if i leave the empty constructor in the receiver class. After the removing the empty contsructor onRreceive methos started working fine.

How can I render HTML from another file in a React component?

It is common to have components that are only rendering from props. Like this:

class Template extends React.Component{
  render (){
    return <div>this.props.something</div>
  }
}

Then in your upper level component where you have the logic you just import the Template component and pass the needed props. All your logic stays in the higher level component, and the Template only renders. This is a possible way to achieve 'templates' like in Angular.

There is no way to have .jsx file with jsx only and use it in React because jsx is not really html but markup for a virtual DOM, which React manages.

Date difference in years using C#

I found this at TimeSpan for years, months and days:

DateTime target_dob = THE_DOB;
DateTime true_age = DateTime.MinValue + ((TimeSpan)(DateTime.Now - target_dob )); // Minimum value as 1/1/1
int yr = true_age.Year - 1;

Storing Form Data as a Session Variable

To use session variables, it's necessary to start the session by using the session_start function, this will allow you to store your data in the global variable $_SESSION in a productive way.

so your code will finally look like this :

<strong>Test Form</strong>
<form action="" method"post">
<input type="text" name="picturenum"/>
<input type="submit" name="Submit" value="Submit!" />
</form>

<?php 
 
 // starting the session
 session_start();


 if (isset($_POST['Submit'])) { 
 $_SESSION['picturenum'] = $_POST['picturenum'];
 } 
?> 

<strong><?php echo $_SESSION['picturenum'];?></strong>

to make it easy to use and to avoid forgetting it again, you can create a session_file.php which you will want to be included in all your codes and will start the session for you:

session_start.php

 <?php
   session_start();
 ?> 

and then include it wherever you like :

<strong>Test Form</strong>
<form action="" method"post">
<input type="text" name="picturenum"/>
<input type="submit" name="Submit" value="Submit!" />
</form>

<?php 
 
 // including the session file
 require_once("session_start.php");


 if (isset($_POST['Submit'])) { 
 $_SESSION['picturenum'] = $_POST['picturenum'];
 } 
?> 

that way it is more portable and easy to maintain in the future.

other remarks

  • if you are using Apache version 2 or newer, be careful. instead of
    <?
    to open php's tags, use <?php, otherwise your code will not be interpreted

  • variables names in php are case-sensitive, instead of write $_session, write $_SESSION in capital letters

good work!

Error: «Could not load type MvcApplication»

As dumb as it might sound, tried everything and it did not work and finally restarted VS2012 to see it working again.

Git submodule push

A submodule is nothing but a clone of a git repo within another repo with some extra meta data (gitlink tree entry, .gitmodules file )

$ cd your_submodule
$ git checkout master
<hack,edit>
$ git commit -a -m "commit in submodule"
$ git push
$ cd ..
$ git add your_submodule
$ git commit -m "Updated submodule"

Counting DISTINCT over multiple columns

How about this,

Select DocumentId, DocumentSessionId, count(*) as c 
from DocumentOutputItems 
group by DocumentId, DocumentSessionId;

This will get us the count of all possible combinations of DocumentId, and DocumentSessionId

Learning Ruby on Rails

I asked the same question when I started out - hoping for a somewhat prescriptive guide on learning Rails... couldn't find one so decided I would write one for others who might find themselves in a similar boat one day :) You can find it here:

Best Way to Learn Ruby & Rails

(It's now actually returned with the !learn factoid helper in the official Ruby on Rails IRC chat room.)

Unable to negotiate with XX.XXX.XX.XX: no matching host key type found. Their offer: ssh-dss

You either follow above approach or this one

Create the config file in the .ssh directory and add these line.

host xxx.xxx
 Hostname xxx.xxx
 IdentityFile ~/.ssh/id_rsa
 User xxx
 KexAlgorithms +diffie-hellman-group1-sha1

Best way to get value from Collection by index

You shouldn't. a Collection avoids talking about indexes specifically because it might not make sense for the specific collection. For example, a List implies some form of ordering, but a Set does not.

Collection<String> myCollection = new HashSet<String>();
myCollection.add("Hello");
myCollection.add("World");

for (String elem : myCollection) {
    System.out.println("elem = " + elem);
}

System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);

gives me:

elem = World
elem = Hello
myCollection.toArray()[0] = World

whilst:

myCollection = new ArrayList<String>();
myCollection.add("Hello");
myCollection.add("World");

for (String elem : myCollection) {
    System.out.println("elem = " + elem);
}

System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);

gives me:

elem = Hello
elem = World
myCollection.toArray()[0] = Hello

Why do you want to do this? Could you not just iterate over the collection?

Using msbuild to execute a File System Publish Profile

Found the answer here: http://www.digitallycreated.net/Blog/59/locally-publishing-a-vs2010-asp.net-web-application-using-msbuild

Visual Studio 2010 has great new Web Application Project publishing features that allow you to easy publish your web app project with a click of a button. Behind the scenes the Web.config transformation and package building is done by a massive MSBuild script that’s imported into your project file (found at: C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets). Unfortunately, the script is hugely complicated, messy and undocumented (other then some oft-badly spelled and mostly useless comments in the file). A big flowchart of that file and some documentation about how to hook into it would be nice, but seems to be sadly lacking (or at least I can’t find it).

Unfortunately, this means performing publishing via the command line is much more opaque than it needs to be. I was surprised by the lack of documentation in this area, because these days many shops use a continuous integration server and some even do automated deployment (which the VS2010 publishing features could help a lot with), so I would have thought that enabling this (easily!) would be have been a fairly main requirement for the feature.

Anyway, after digging through the Microsoft.Web.Publishing.targets file for hours and banging my head against the trial and error wall, I’ve managed to figure out how Visual Studio seems to perform its magic one click “Publish to File System” and “Build Deployment Package” features. I’ll be getting into a bit of MSBuild scripting, so if you’re not familiar with MSBuild I suggest you check out this crash course MSDN page.

Publish to File System

The VS2010 Publish To File System Dialog Publish to File System took me a while to nut out because I expected some sensible use of MSBuild to be occurring. Instead, VS2010 does something quite weird: it calls on MSBuild to perform a sort of half-deploy that prepares the web app’s files in your project’s obj folder, then it seems to do a manual copy of those files (ie. outside of MSBuild) into your target publish folder. This is really whack behaviour because MSBuild is designed to copy files around (and other build-related things), so it’d make sense if the whole process was just one MSBuild target that VS2010 called on, not a target then a manual copy.

This means that doing this via MSBuild on the command-line isn’t as simple as invoking your project file with a particular target and setting some properties. You’ll need to do what VS2010 ought to have done: create a target yourself that performs the half-deploy then copies the results to the target folder. To edit your project file, right click on the project in VS2010 and click Unload Project, then right click again and click Edit. Scroll down until you find the Import element that imports the web application targets (Microsoft.WebApplication.targets; this file itself imports the Microsoft.Web.Publishing.targets file mentioned earlier). Underneath this line we’ll add our new target, called PublishToFileSystem:

<Target Name="PublishToFileSystem"
        DependsOnTargets="PipelinePreDeployCopyAllFilesToOneFolder">
    <Error Condition="'$(PublishDestination)'==''"
           Text="The PublishDestination property must be set to the intended publishing destination." />
    <MakeDir Condition="!Exists($(PublishDestination))"
             Directories="$(PublishDestination)" />

    <ItemGroup>
        <PublishFiles Include="$(_PackageTempDir)\**\*.*" />
    </ItemGroup>

    <Copy SourceFiles="@(PublishFiles)"
          DestinationFiles="@(PublishFiles->'$(PublishDestination)\%(RecursiveDir)%(Filename)%(Extension)')"
          SkipUnchangedFiles="True" />
</Target>

This target depends on the PipelinePreDeployCopyAllFilesToOneFolder target, which is what VS2010 calls before it does its manual copy. Some digging around in Microsoft.Web.Publishing.targets shows that calling this target causes the project files to be placed into the directory specified by the property _PackageTempDir.

The first task we call in our target is the Error task, upon which we’ve placed a condition that ensures that the task only happens if the PublishDestination property hasn’t been set. This will catch you and error out the build in case you’ve forgotten to specify the PublishDestination property. We then call the MakeDir task to create that PublishDestination directory if it doesn’t already exist.

We then define an Item called PublishFiles that represents all the files found under the _PackageTempDir folder. The Copy task is then called which copies all those files to the Publish Destination folder. The DestinationFiles attribute on the Copy element is a bit complex; it performs a transform of the items and converts their paths to new paths rooted at the PublishDestination folder (check out Well-Known Item Metadata to see what those %()s mean).

To call this target from the command-line we can now simply perform this command (obviously changing the project file name and properties to suit you):

msbuild Website.csproj "/p:Platform=AnyCPU;Configuration=Release;PublishDestination=F:\Temp\Publish" /t:PublishToFileSystem

React: trigger onChange if input value is changing by state?

Try this code if state object has sub objects like this.state.class.fee. We can pass values using following code:

this.setState({ class: Object.assign({}, this.state.class, { [element]: value }) }

how to get the value of a textarea in jquery?

You can also get the value by element's name attribute.

var message = $("#formId textarea[name=message]").val();

How do you set a default value for a MySQL Datetime column?

For all those who lost heart trying to set a default DATETIME value in MySQL, I know exactly how you feel/felt. So here is is:

ALTER TABLE  `table_name` CHANGE `column_name` DATETIME NOT NULL DEFAULT 0

Carefully observe that I haven't added single quotes/double quotes around the 0

I'm literally jumping after solving this one :D

Is it a bad practice to use an if-statement without curly braces?

I have always tried to make my code standard and look as close to the same as possible. This makes it easier for others to read it when they are in charge of updating it. If you do your first example and add a line to it in the middle it will fail.

Won't work:

if(statement) do this; and this; else do this;

Replace specific text with a redacted version using Python

You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.

NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.

Example:

Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.

Returns:

NER with spacy

Just be aware that this is not 100%!

Here are a little snippet for you to try out:

import spacy

phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
   doc = nlp(phrase)
   replaced = ""
   for token in doc:
      if token in doc.ents:
         replaced+="XXXX "
      else:
         replaced+=token.text+" "

Read more here: https://spacy.io/usage/linguistic-features#named-entities

You could, instead of replacing with XXXX, replace based on the entity type, like:

if ent.label_ == "PERSON":
   replaced += "<PERSON> "

Then:

import re, random

personames = ["Jack", "Mike", "Bob", "Dylan"]

phrase = re.replace("<PERSON>", random.choice(personames), phrase)

Object reference not set to an instance of an object.

The correct way in .NET 4.0 is:

if (String.IsNullOrWhiteSpace(strSearch))

The String.IsNullOrWhiteSpace method used above is equivalent to:

if (strSearch == null || strSearch == String.Empty || strSearch.Trim().Length == 0) 
// String.Empty is the same as ""

Reference for IsNullOrWhiteSpace method

http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx

Indicates whether a specified string is Nothing, empty, or consists only of white-space characters.

In earlier versions, you could do something like this:

if (String.IsNullOrEmpty(strSearch) || strSearch.Trim().Length == 0)

The String.IsNullOrEmpty method used above is equivalent to:

if (strSearch == null || strSearch == String.Empty)

Which means you still need to check for your "IsWhiteSpace" case with the .Trim().Length == 0 as per the example.

Reference for IsNullOrEmpty method

http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx

Indicates whether the specified string is Nothing or an Empty string.

Explanation:

You need to ensure strSearch (or any variable for that matter) is not null before you dereference it using the dot character (.) - i.e. before you do strSearch.SomeMethod() or strSearch.SomeProperty you need to check that strSearch != null.

In your example you want to make sure your string has a value, which means you want to ensure the string:

  • Is not null
  • Is not the empty string (String.Empty / "")
  • Is not just whitespace

In the cases above, you must put the "Is it null?" case first, so it doesn't go on to check the other cases (and error) when the string is null.

iloc giving 'IndexError: single positional indexer is out-of-bounds'

This happens when you index a row/column with a number that is larger than the dimensions of your dataframe. For instance, getting the eleventh column when you have only three.

import pandas as pd

df = pd.DataFrame({'Name': ['Mark', 'Laura', 'Adam', 'Roger', 'Anna'],
                   'City': ['Lisbon', 'Montreal', 'Lisbon', 'Berlin', 'Glasgow'],
                   'Car': ['Tesla', 'Audi', 'Porsche', 'Ford', 'Honda']})

You have 5 rows and three columns:

    Name      City      Car
0   Mark    Lisbon    Tesla
1  Laura  Montreal     Audi
2   Adam    Lisbon  Porsche
3  Roger    Berlin     Ford
4   Anna   Glasgow    Honda

Let's try to index the eleventh column (it doesn't exist):

df.iloc[:, 10] # there is obviously no 11th column

IndexError: single positional indexer is out-of-bounds

If you are a beginner with Python, remember that df.iloc[:, 10] would refer to the eleventh column.

Difference between OpenJDK and Adoptium/AdoptOpenJDK

In short:

  • OpenJDK has multiple meanings and can refer to:
    • free and open source implementation of the Java Platform, Standard Edition (Java SE)
    • open source repository — the Java source code aka OpenJDK project
    • prebuilt OpenJDK binaries maintained by Oracle
    • prebuilt OpenJDK binaries maintained by the OpenJDK community
  • AdoptOpenJDK — prebuilt OpenJDK binaries maintained by community (open source licensed)

Explanation:

Prebuilt OpenJDK (or distribution) — binaries, built from http://hg.openjdk.java.net/, provided as an archive or installer, offered for various platforms, with a possible support contract.

OpenJDK, the source repository (also called OpenJDK project) - is a Mercurial-based open source repository, hosted at http://hg.openjdk.java.net. The Java source code. The vast majority of Java features (from the VM and the core libraries to the compiler) are based solely on this source repository. Oracle have an alternate fork of this.

OpenJDK, the distribution (see the list of providers below) - is free as in beer and kind of free as in speech, but, you do not get to call Oracle if you have problems with it. There is no support contract. Furthermore, Oracle will only release updates to any OpenJDK (the distribution) version if that release is the most recent Java release, including LTS (long-term support) releases. The day Oracle releases OpenJDK (the distribution) version 12.0, even if there's a security issue with OpenJDK (the distribution) version 11.0, Oracle will not release an update for 11.0. Maintained solely by Oracle.

Some OpenJDK projects - such as OpenJDK 8 and OpenJDK 11 - are maintained by the OpenJDK community and provide releases for some OpenJDK versions for some platforms. The community members have taken responsibility for releasing fixes for security vulnerabilities in these OpenJDK versions.

AdoptOpenJDK, the distribution is very similar to Oracle's OpenJDK distribution (in that it is free, and it is a build produced by compiling the sources from the OpenJDK source repository). AdoptOpenJDK as an entity will not be backporting patches, i.e. there won't be an AdoptOpenJDK 'fork/version' that is materially different from upstream (except for some build script patches for things like Win32 support). Meaning, if members of the community (Oracle or others, but not AdoptOpenJDK as an entity) backport security fixes to updates of OpenJDK LTS versions, then AdoptOpenJDK will provide builds for those. Maintained by OpenJDK community.

OracleJDK - is yet another distribution. Starting with JDK12 there will be no free version of OracleJDK. Oracle's JDK distribution offering is intended for commercial support. You pay for this, but then you get to rely on Oracle for support. Unlike Oracle's OpenJDK offering, OracleJDK comes with longer support for LTS versions. As a developer you can get a free license for personal/development use only of this particular JDK, but that's mostly a red herring, as 'just the binary' is basically the same as the OpenJDK binary. I guess it means you can download security-patched versions of LTS JDKs from Oracle's websites as long as you promise not to use them commercially.

Note. It may be best to call the OpenJDK builds by Oracle the "Oracle OpenJDK builds".

Donald Smith, Java product manager at Oracle writes:

Ideally, we would simply refer to all Oracle JDK builds as the "Oracle JDK", either under the GPL or the commercial license, depending on your situation. However, for historical reasons, while the small remaining differences exist, we will refer to them separately as Oracle’s OpenJDK builds and the Oracle JDK.


OpenJDK Providers and Comparison

----------------------------------------------------------------------------------------
|     Provider      | Free Builds | Free Binary   | Extended | Commercial | Permissive |
|                   | from Source | Distributions | Updates  | Support    | License    |
|--------------------------------------------------------------------------------------|
| AdoptOpenJDK      |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Amazon – Corretto |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Azul Zulu         |    No       |    Yes        |   Yes    |   Yes      |   Yes      |
| BellSoft Liberica |    No       |    Yes        |   Yes    |   Yes      |   Yes      |
| IBM               |    No       |    No         |   Yes    |   Yes      |   Yes      |
| jClarity          |    No       |    No         |   Yes    |   Yes      |   Yes      |
| OpenJDK           |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Oracle JDK        |    No       |    Yes        |   No**   |   Yes      |   No       |
| Oracle OpenJDK    |    Yes      |    Yes        |   No     |   No       |   Yes      |
| ojdkbuild         |    Yes      |    Yes        |   No     |   No       |   Yes      |
| RedHat            |    Yes      |    Yes        |   Yes    |   Yes      |   Yes      |
| SapMachine        |    Yes      |    Yes        |   Yes    |   Yes      |   Yes      |
----------------------------------------------------------------------------------------

Free Builds from Source - the distribution source code is publicly available and one can assemble its own build

Free Binary Distributions - the distribution binaries are publicly available for download and usage

Extended Updates - aka LTS (long-term support) - Public Updates beyond the 6-month release lifecycle

Commercial Support - some providers offer extended updates and customer support to paying customers, e.g. Oracle JDK (support details)

Permissive License - the distribution license is non-protective, e.g. Apache 2.0


Which Java Distribution Should I Use?

In the Sun/Oracle days, it was usually Sun/Oracle producing the proprietary downstream JDK distributions based on OpenJDK sources. Recently, Oracle had decided to do their own proprietary builds only with the commercial support attached. They graciously publish the OpenJDK builds as well on their https://jdk.java.net/ site.

What is happening starting JDK 11 is the shift from single-vendor (Oracle) mindset to the mindset where you select a provider that gives you a distribution for the product, under the conditions you like: platforms they build for, frequency and promptness of releases, how support is structured, etc. If you don't trust any of existing vendors, you can even build OpenJDK yourself.

Each build of OpenJDK is usually made from the same original upstream source repository (OpenJDK “the project”). However each build is quite unique - $free or commercial, branded or unbranded, pure or bundled (e.g., BellSoft Liberica JDK offers bundled JavaFX, which was removed from Oracle builds starting JDK 11).

If no environment (e.g., Linux) and/or license requirement defines specific distribution and if you want the most standard JDK build, then probably the best option is to use OpenJDK by Oracle or AdoptOpenJDK.


Additional information

Time to look beyond Oracle's JDK by Stephen Colebourne

Java Is Still Free by Java Champions community (published on September 17, 2018)

Java is Still Free 2.0.0 by Java Champions community (published on March 3, 2019)

Aleksey Shipilev about JDK updates interview by Opsian (published on June 27, 2019)

What is the SSIS package and what does it do?

For Latest Info About SSIS > https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services

From the above referenced site:

Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. Use Integration Services to solve complex business problems by copying or downloading files, loading data warehouses, cleansing and mining data, and managing SQL Server objects and data.

Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.

Integration Services includes a rich set of built-in tasks and transformations, graphical tools for building packages, and the Integration Services Catalog database, where you store, run, and manage packages.

You can use the graphical Integration Services tools to create solutions without writing a single line of code. You can also program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.

Getting Started with SSIS - http://msdn.microsoft.com/en-us/sqlserver/bb671393.aspx

If you are Integration Services Information Worker - http://msdn.microsoft.com/en-us/library/ms141667.aspx

If you are Integration Services Administrator - http://msdn.microsoft.com/en-us/library/ms137815.aspx

If you are Integration Services Developer - http://msdn.microsoft.com/en-us/library/ms137709.aspx

If you are Integration Services Architect - http://msdn.microsoft.com/en-us/library/ms142161.aspx

Overview of SSIS - http://msdn.microsoft.com/en-us/library/ms141263.aspx

Integration Services How-to Topics - http://msdn.microsoft.com/en-us/library/ms141767.aspx

Working with UTF-8 encoding in Python source

Do not forget to verify if your text editor encodes properly your code in UTF-8.

Otherwise, you may have invisible characters that are not interpreted as UTF-8.

PHP preg_match - only allow alphanumeric strings and - _ characters

Code:

if(preg_match('/[^a-z_\-0-9]/i', $string))
{
  echo "not valid string";
}

Explanation:

  • [] => character class definition
  • ^ => negate the class
  • a-z => chars from 'a' to 'z'
  • _ => underscore
  • - => hyphen '-' (You need to escape it)
  • 0-9 => numbers (from zero to nine)

The 'i' modifier at the end of the regex is for 'case-insensitive' if you don't put that you will need to add the upper case characters in the code before by doing A-Z

How to convert C# nullable int to int

If you know that v1 has a value, you can use the Value property:

v2 = v1.Value;

Using the GetValueOrDefault method will assign the value if there is one, otherwise the default for the type, or a default value that you specify:

v2 = v1.GetValueOrDefault(); // assigns zero if v1 has no value

v2 = v1.GetValueOrDefault(-1); // assigns -1 if v1 has no value

You can use the HasValue property to check if v1 has a value:

if (v1.HasValue) {
  v2 = v1.Value;
}

There is also language support for the GetValueOrDefault(T) method:

v2 = v1 ?? -1;

Is it possible to append to innerHTML without destroying descendants' event listeners?

You could do it like this:

var anchors = document.getElementsByTagName('a'); 
var index_a = 0;
var uls = document.getElementsByTagName('UL'); 
window.onload=function()          {alert(anchors.length);};
for(var i=0 ; i<uls.length;  i++)
{
    lis = uls[i].getElementsByTagName('LI');
    for(var j=0 ;j<lis.length;j++)
    {
        var first = lis[j].innerHTML; 
        string = "<img src=\"http://g.etfv.co/" +  anchors[index_a++] + 
            "\"  width=\"32\" 
        height=\"32\" />   " + first;
        lis[j].innerHTML = string;
    }
}

Where does Chrome store extensions?

For my Mac, extensions were here:

~/Library/Application Support/Google/Chrome/Default/Extensions/

if you go to chrome://extensions you'll find the "ID" of each extension. That is going to be a directory within Extensions directory. It is there you'll find all of the extension's files.

How to write a multiline Jinja statement

According to the documentation: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements you may use multi-line statements as long as the code has parens/brackets around it. Example:

{% if ( (foo == 'foo' or bar == 'bar') and 
        (fooo == 'fooo' or baar == 'baar') ) %}
    <li>some text</li>
{% endif %}

Edit: Using line_statement_prefix = '#'* the code would look like this:

# if ( (foo == 'foo' or bar == 'bar') and 
       (fooo == 'fooo' or baar == 'baar') )
    <li>some text</li>
# endif

*Here's an example of how you'd specify the line_statement_prefix in the Environment:

from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
    loader=PackageLoader('yourapplication', 'templates'),
    autoescape=select_autoescape(['html', 'xml']),
    line_statement_prefix='#'
)

Or using Flask:

from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'

How to get the part of a file after the first line that matches a regular expression?

These will print all lines from the last found line "TERMINATE" till end of file:

LINE_NUMBER=`grep -o -n TERMINATE $OSCAM_LOG|tail -n 1|sed "s/:/ \\'/g"|awk -F" " '{print $1}'`
tail -n +$LINE_NUMBER $YOUR_FILE_NAME

Strings in C, how to get subString

Generalized:

char* subString (const char* input, int offset, int len, char* dest)
{
  int input_len = strlen (input);

  if (offset + len > input_len)
  {
     return NULL;
  }

  strncpy (dest, input + offset, len);
  return dest;
}

char dest[80];
const char* source = "hello world";

if (subString (source, 0, 5, dest))
{
  printf ("%s\n", dest);
}

Java - escape string to prevent SQL injection

If you are using PL/SQL you can also use DBMS_ASSERT it can sanitize your input so you can use it without worrying about SQL injections.

see this answer for instance: https://stackoverflow.com/a/21406499/1726419

How to host material icons offline?

As of 2020, my approach is to use the material-icons-font package. It simplifies the usage of Google's material-design-icons package and the community based material-design-icons-iconfont.

  1. Install the package. npm install material-icons-font --save

  2. Add the path of the package's CSS file to the style property of your project's angular.json file.

    ... "styles": [ "./node_modules/material-icons-font/material-icons-font.css" ], ...

  3. If using SCSS, copy content below to the top of your styles.scss file.

    @import '~material-icons-font/sass/variables'; @import '~material-icons-font/sass/mixins'; $MaterialIcons_FontPath: "~material-icons-font/fonts"; @import '~material-icons-font/sass/main'; @import '~material-icons-font/sass/Regular';

  4. Use the icons in the HTML file of your project.

    // Using icon tag
    <i class="material-icons">face</i>
    <i class="material-icons md-48">face</i>
    <i class="material-icons md-light md-inactive">face</i>
    
    // Using Angular Material's <mat-icon> tag
    <mat-icon>face</mat-icon>
    <mat-icon>add_circle</mat-icon>
    <mat-icon>add_circle_outline</mat-icon>
    

Icons from @angular/material tend to break when developing offline. Adding material-icons-font package in conjunction with @angular/material allows you to use the tag while developing offline.

Using sessions & session variables in a PHP Login Script

$session_start();

extract($_POST);         
//extract data from submit post 

if(isset($submit))  
  {    
    if($user=="user" && $pass=="pass")    
      {     
        $_SESSION['user']= $user;       
        //if correct password and name store in session 
    } else {
        echo "Invalid user and password";
        header("Locatin:form.php")
    }
if(isset($_SESSION['user']))     
  {
  }

Why won't bundler install JSON gem?

Run this command then everything will be ok

sudo apt-get install libgmp-dev

Javascript: formatting a rounded number to N decimals

I think that there is a more simple approach to all given here, and is the method Number.toFixed() already implemented in JavaScript.

simply write:

var myNumber = 2;

myNumber.toFixed(2); //returns "2.00"
myNumber.toFixed(1); //returns "2.0"

etc...

How to recompile with -fPIC

I hit this same issue trying to install Dashcast on Centos 7. The fix was adding -fPIC at the end of each of the CFLAGS in the x264 Makefile. Then I had to run make distclean for both x264 and ffmpeg and rebuild.

How to check whether a string contains a substring in Ruby

Ternary way

my_string.include?('ahr') ? (puts 'String includes ahr') : (puts 'String does not include ahr')

OR

puts (my_string.include?('ahr') ? 'String includes ahr' : 'String not includes ahr')

Access all Environment properties as a Map or Properties object

I had the requirement to retrieve all properties whose key starts with a distinct prefix (e.g. all properties starting with "log4j.appender.") and wrote following Code (using streams and lamdas of Java 8).

public static Map<String,Object> getPropertiesStartingWith( ConfigurableEnvironment aEnv,
                                                            String aKeyPrefix )
{
    Map<String,Object> result = new HashMap<>();

    Map<String,Object> map = getAllProperties( aEnv );

    for (Entry<String, Object> entry : map.entrySet())
    {
        String key = entry.getKey();

        if ( key.startsWith( aKeyPrefix ) )
        {
            result.put( key, entry.getValue() );
        }
    }

    return result;
}

public static Map<String,Object> getAllProperties( ConfigurableEnvironment aEnv )
{
    Map<String,Object> result = new HashMap<>();
    aEnv.getPropertySources().forEach( ps -> addAll( result, getAllProperties( ps ) ) );
    return result;
}

public static Map<String,Object> getAllProperties( PropertySource<?> aPropSource )
{
    Map<String,Object> result = new HashMap<>();

    if ( aPropSource instanceof CompositePropertySource)
    {
        CompositePropertySource cps = (CompositePropertySource) aPropSource;
        cps.getPropertySources().forEach( ps -> addAll( result, getAllProperties( ps ) ) );
        return result;
    }

    if ( aPropSource instanceof EnumerablePropertySource<?> )
    {
        EnumerablePropertySource<?> ps = (EnumerablePropertySource<?>) aPropSource;
        Arrays.asList( ps.getPropertyNames() ).forEach( key -> result.put( key, ps.getProperty( key ) ) );
        return result;
    }

    // note: Most descendants of PropertySource are EnumerablePropertySource. There are some
    // few others like JndiPropertySource or StubPropertySource
    myLog.debug( "Given PropertySource is instanceof " + aPropSource.getClass().getName()
                 + " and cannot be iterated" );

    return result;

}

private static void addAll( Map<String, Object> aBase, Map<String, Object> aToBeAdded )
{
    for (Entry<String, Object> entry : aToBeAdded.entrySet())
    {
        if ( aBase.containsKey( entry.getKey() ) )
        {
            continue;
        }

        aBase.put( entry.getKey(), entry.getValue() );
    }
}

Note that the starting point is the ConfigurableEnvironment which is able to return the embedded PropertySources (the ConfigurableEnvironment is a direct descendant of Environment). You can autowire it by:

@Autowired
private ConfigurableEnvironment  myEnv;

If you not using very special kinds of property sources (like JndiPropertySource, which is usually not used in spring autoconfiguration) you can retrieve all properties held in the environment.

The implementation relies on the iteration order which spring itself provides and takes the first found property, all later found properties with the same name are discarded. This should ensure the same behaviour as if the environment were asked directly for a property (returning the first found one).

Note also that the returned properties are not yet resolved if they contain aliases with the ${...} operator. If you want to have a particular key resolved you have to ask the Environment directly again:

myEnv.getProperty( key );

How do I setup a SSL certificate for an express.js server?

See the Express docs as well as the Node docs for https.createServer (which is what express recommends to use):

var privateKey = fs.readFileSync( 'privatekey.pem' );
var certificate = fs.readFileSync( 'certificate.pem' );

https.createServer({
    key: privateKey,
    cert: certificate
}, app).listen(port);

Other options for createServer are at: http://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener

How can I see the current value of my $PATH variable on OS X?

Use the command:

 echo $PATH

and you will see all path:

/Users/name/.rvm/gems/ruby-2.5.1@pe/bin:/Users/name/.rvm/gems/ruby-2.5.1@global/bin:/Users/sasha/.rvm/rubies/ruby-2.5.1/bin:/Users/sasha/.rvm/bin:

HTML encoding issues - "Â" character showing up instead of "&nbsp;"

Problem: Even I was facing the problem where we were sending '£' with some string in POST request to CRM System, but when we were doing the GET call from CRM , it was returning '£' with some string content. So what we have analysed is that '£' was getting converted to '£'.

Analysis: The glitch which we have found after doing research is that in POST call we have set HttpWebRequest ContentType as "text/xml" while in GET Call it was "text/xml; charset:utf-8".

Solution: So as the part of solution we have included the charset:utf-8 in POST request and it works.

how to add a day to a date using jquery datepicker

This answer really helped me get started (noob) - but I encountered some weird behavior when I set a start date of 12/31/2014 and added +1 to default the end date. Instead of giving me an end date of 01/01/2015 I was getting 02/01/2015 (!!!). This version parses the components of the start date to avoid these end of year oddities.


 $( "#date_start" ).datepicker({

   minDate: 0,
   dateFormat: "mm/dd/yy",

   onSelect: function(selected) {
         $("#date_end").datepicker("option","minDate", selected); //  mindate on the End datepicker cannot be less than start date already selected.
         var date = $(this).datepicker('getDate');
         var tempStartDate = new Date(date);
         var default_end = new Date(tempStartDate.getFullYear(), tempStartDate.getMonth(), tempStartDate.getDate()+1); //this parses date to overcome new year date weirdness
         $('#date_end').datepicker('setDate', default_end); // Set as default                           
   }

 });

 $( "#date_end" ).datepicker({

   minDate: 0,
   dateFormat: "mm/dd/yy",

   onSelect: function(selected) {
     $("#date_start").datepicker("option","maxDate", selected); //  maxdate on the Start datepicker cannot be more than end date selected.

  }

});

AppendChild() is not a function javascript

 function createQuestionPanel() {

        var element = document.createElement("Input");
        element.setAttribute("type", "button");
        element.setAttribute("value", "button");
        element.setAttribute("name", "button");


        var div = document.createElement("div"); <------- Create DIv Node
        div.appendChild(element);<--------------------
        document.body.appendChild(div) <------------- Then append it to body

    }

    function formvalidate() {

    }

React-Native: Module AppRegistry is not a registered callable module

In my case, my index.js just points to another js instead of my Launcher js mistakenly, which does not contain AppRegistry.registerComponent().

So, make sure the file yourindex.jspoint to register the class.

powershell - extract file name and extension

If is from a text file and and presuming name file are surrounded by white spaces this is a way:

$a = get-content c:\myfile.txt

$b = $a | select-string -pattern "\s.+\..{3,4}\s" | select -ExpandProperty matches | select -ExpandProperty value

$b | % {"File name:{0} - Extension:{1}" -f $_.substring(0, $_.lastindexof('.')) , $_.substring($_.lastindexof('.'), ($_.length - $_.lastindexof('.'))) }

If is a file you can use something like this based on your needs:

$a = dir .\my.file.xlsx # or $a = get-item c:\my.file.xlsx 

$a
    Directory: Microsoft.PowerShell.Core\FileSystem::C:\ps


Mode           LastWriteTime       Length Name
----           -------------       ------ ----
-a---      25/01/10    11.51          624 my.file.xlsx


$a.BaseName
my.file
$a.Extension
.xlsx

How do I check in python if an element of a list is empty?

Try:

if l[i]:
    print 'Found element!'
else:
    print 'Empty element.'

How to check if a registry value exists using C#?

Of course, "Fagner Antunes Dornelles" is correct in its answer. But it seems to me that it is worth checking the registry branch itself in addition, or be sure of the part that is exactly there.

For example ("dirty hack"), i need to establish trust in the RMS infrastructure, otherwise when i open Word or Excel documents, i will be prompted for "Active Directory Rights Management Services". Here's how i can add remote trust to me servers in the enterprise infrastructure.

foreach (var strServer in listServer)
{
    try
    {
        RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC\\{strServer}", false);
        if (regCurrentUser == null)
            throw new ApplicationException("Not found registry SubKey ...");
        if (regCurrentUser.GetValueNames().Contains("UserConsent") == false)
            throw new ApplicationException("Not found value in SubKey ...");
    }
    catch (ApplicationException appEx)
    {
        Console.WriteLine(appEx);
        try
        {
            RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC", true);
            RegistryKey newKey = regCurrentUser.CreateSubKey(strServer, true);
            newKey.SetValue("UserConsent", 1, RegistryValueKind.DWord);
        }
        catch(Exception ex)
        {
            Console.WriteLine($"{ex} Pipec kakoito ...");
        }
    }
}

Convert Object to JSON string

Convert JavaScript object to json data

$("form").submit(function(event){
  event.preventDefault();
  var formData = $("form").serializeArray(); // Create array of object
  var jsonConvertedData = JSON.stringify(formData);  // Convert to json
  consol.log(jsonConvertedData);
});

You can validate json data using http://jsonlint.com

In the shell, what does " 2>&1 " mean?

0 for input, 1 for stdout and 2 for stderr.

One Tip: somecmd >1.txt 2>&1 is correct, while somecmd 2>&1 >1.txt is totally wrong with no effect!

Is 'bool' a basic datatype in C++?

Yes, bool is a built-in type.

WIN32 is C code, not C++, and C does not have a bool, so they provide their own typedef BOOL.

Bootstrap 3 Flush footer to bottom. not fixed

This method uses minimal markup. Just put all your content in a .wrapper which has a padding-bottom and negative margin-bottom equal to the footer height (in my example 100px).

html, body {
    height: 100%;
}

/* give the wrapper a padding-bottom and negative margin-bottom equal to the footer height */

.wrapper {
    min-height: 100%;
    height: auto;
    margin: 0 auto -100px;
    padding-bottom: 100px;
}
.footer {
    height: 100px;
}

<body>

<div class="wrapper">
  <p>Your website content here.</p>
</div>
<div class="footer">
   <p>Copyright (c) 2014</p>
</div>

</body>

"multiple target patterns" Makefile error

I had it on the Makefile

MAPS+=reverse/db.901:550:2001.ip6.arpa 
lastserial:  ${MAPS}
    ./updateser ${MAPS}

It's because of the : in the file name. I solved this with

                      -------- notice
                     /    /
                    v    v
MAPS+=reverse/db.901\:550\:2001.ip6.arpa
lastserial:  ${MAPS}
    ./updateser ${MAPS}

Insert value into a string at a certain position?

var sb = new StringBuilder();
sb.Append(beforeText);
sb.Insert(2, insertText);
afterText = sb.ToString();

Rename all files in a folder with a prefix in a single command

With rnm (you will need to install it):

rnm -ns 'Unix_/fn/' *

Or

rnm -rs '/^/Unix_/' *

P.S : I am the author of this tool.

How to convert a DataFrame back to normal RDD in pyspark?

Answer given by kennyut/Kistian works very well but to get exact RDD like output when RDD consist of list of attributes e.g. [1,2,3,4] we can use flatmap command as below,

rdd = df.rdd.flatMap(list)
or 
rdd = df.rdd.flatmap(lambda x: list(x))

dictionary update sequence element #0 has length 3; 2 is required

One of the fast ways to create a dict from equal-length tuples:

>>> t1 = (a,b,c,d)
>>> t2 = (1,2,3,4)
>>> dict(zip(t1, t2))
{'a':1, 'b':2, 'c':3, 'd':4, }

How to use multiple conditions (With AND) in IIF expressions in ssrs

Could you try this out?

=IIF((Fields!OpeningStock.Value=0) AND (Fields!GrossDispatched.Value=0) AND 
(Fields!TransferOutToMW.Value=0) AND (Fields!TransferOutToDW.Value=0) AND 
(Fields!TransferOutToOW.Value=0) AND (Fields!NetDispatched.Value=0) AND (Fields!QtySold.Value=0) 
AND (Fields!StockAdjustment.Value=0) AND (Fields!ClosingStock.Value=0),True,False)

Note: Setting Hidden to False will make the row visible

class << self idiom in Ruby

Usually, instance methods are global methods. That means they are available in all instances of the class on which they were defined. In contrast, a singleton method is implemented on a single object.

Ruby stores methods in classes and all methods must be associated with a class. The object on which a singleton method is defined is not a class (it is an instance of a class). If only classes can store methods, how can an object store a singleton method? When a singleton method is created, Ruby automatically creates an anonymous class to store that method. These anonymous classes are called metaclasses, also known as singleton classes or eigenclasses. The singleton method is associated with the metaclass which, in turn, is associated with the object on which the singleton method was defined.

If multiple singleton methods are defined within a single object, they are all stored in the same metaclass.

class Zen
end

z1 = Zen.new
z2 = Zen.new

class << z1
  def say_hello
    puts "Hello!"
  end
end

z1.say_hello    # Output: Hello!
z2.say_hello    # Output: NoMethodError: undefined method `say_hello'…

In the above example, class << z1 changes the current self to point to the metaclass of the z1 object; then, it defines the say_hello method within the metaclass.

Classes are also objects (instances of the built-in class called Class). Class methods are nothing more than singleton methods associated with a class object.

class Zabuton
  class << self
    def stuff
      puts "Stuffing zabuton…"
    end
  end
end

All objects may have metaclasses. That means classes can also have metaclasses. In the above example, class << self modifies self so it points to the metaclass of the Zabuton class. When a method is defined without an explicit receiver (the class/object on which the method will be defined), it is implicitly defined within the current scope, that is, the current value of self. Hence, the stuff method is defined within the metaclass of the Zabuton class. The above example is just another way to define a class method. IMHO, it's better to use the def self.my_new_clas_method syntax to define class methods, as it makes the code easier to understand. The above example was included so we understand what's happening when we come across the class << self syntax.

Additional info can be found at this post about Ruby Classes.

rsync - mkstemp failed: Permission denied (13)

I had a similar issue, but in my case it was because storage has only SFTP, without ssh or rsync daemons on it. I could not change anything, bcs this server was provided by my customer.

rsync could not change the date and time for the file, some other utilites (like csync) showed me other errors: "Unable to create temporary file Clock skew detected". If you have access to the storage-server - just install openssh-server or launch rsync as a daemon here.

In my case - I could not do this and solution was: lftp. lftp's usage for syncronization is below:

lftp -c "open -u login,password sftp://sft.domain.tld/; mirror -c --verbose=9 -e -R -L /srs/folder /rem/folder"

/src/folder - is the folder on my PC, /rem/folder - is sftp://sft.domain.tld/rem/folder.

you may find mans by the link lftp.yar.ru/lftp-man.html

How do I undo a checkout in git?

To undo git checkout do git checkout -, similarly to cd and cd - in shell.

Remove part of a string

Here's the strsplit solution if s is a vector:

> s <- c("TGAS_1121", "MGAS_1432")
> s1 <- sapply(strsplit(s, split='_', fixed=TRUE), function(x) (x[2]))
> s1
[1] "1121" "1432"

How to import set of icons into Android Studio project

Since Android Studio 3.4, there is a new tool called Resource manager. It supports importing many drawables at once (vectors, pngs, ...) . Follow the official documentation.

PyCharm import external library

updated on May 26-2018

If the external library is in a folder that is under the project then

File -> Settings -> Project -> Project structure -> select the folder and Mark as Sources!

If not, add content root, and do similar things.

How to change sa password in SQL Server 2008 express?

You need to follow the steps described in Troubleshooting: Connecting to SQL Server When System Administrators Are Locked Out and add your own Windows user as a member of sysadmin:

  • shutdown MSSQL$EXPRESS service (or whatever the name of your SQL Express service is)
  • start add the -m and -f startup parameters (or you can start sqlservr.exe -c -sEXPRESS -m -f from console)
  • connect to DAC: sqlcmd -E -A -S .\EXPRESS or from SSMS use admin:.\EXPRESS
  • run create login [machinename\username] from windows to create your Windows login in SQL
  • run sp_addsrvrolemember 'machinename\username', 'sysadmin'; to make urself sysadmin member
  • restart service w/o the -m -f

To delay JavaScript function call using jQuery

Very easy, just call the function within a specific amount of milliseconds using setTimeout()

setTimeout(myFunction, 2000)

function myFunction() {
    alert('Was called after 2 seconds');
}

Or you can even initiate the function inside the timeout, like so:

setTimeout(function() {
    alert('Was called after 2 seconds');
}, 2000)

How do I call paint event?

use Control.InvokePaint you can also use it for manual double buffering

What do I need to do to get Internet Explorer 8 to accept a self signed certificate?

I tried all mentioned solutions but none of them worked. Using Internet Explorer 11 (11.0.9600.17914), there was no way of accepting invalid certificates as the error looked exactly as an 404.

What helped was the following: - add host to trusted sites (as mentioned a couple of times here) - disable TLS 1.2 and enable SSL 1.0 & SSL 2.0

The last step is something you should ONLY DO if you know what you're doing. We need to use a pretty strange setup here at work, thus we couldn't find another way of getting access to the system. Usually, downgrading security like that should not be done.

Best Regular Expression for Email Validation in C#

I would like to suggest new EmailAddressAttribute().IsValid(emailTxt) for additional validation before/after validating using RegEx

Remember EmailAddressAttribute is part of System.ComponentModel.DataAnnotations namespace.

Export MySQL data to Excel in PHP

try this code

data.php

    <table border="1">
<tr>
    <th>NO.</th>
    <th>NAME</th>
    <th>Major</th>
</tr>
<?php
//connection to mysql
mysql_connect("localhost", "root", ""); //server , username , password
mysql_select_db("codelution");

//query get data
$sql = mysql_query("SELECT * FROM student ORDER BY id ASC");
$no = 1;
while($data = mysql_fetch_assoc($sql)){
    echo '
    <tr>
        <td>'.$no.'</td>
        <td>'.$data['name'].'</td>
        <td>'.$data['major'].'</td>
    </tr>
    ';
    $no++;
}
?>

code for excel file

export.php

<?php
// The function header by sending raw excel
header("Content-type: application/vnd-ms-excel");
// Defines the name of the export file "codelution-export.xls"
header("Content-Disposition: attachment; filename=codelution-export.xls");
// Add data table
include 'data.php';
?>

if mysqli version

$sql="SELECT * FROM user_details";
$result=mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0)
{
    $no = 1;
            while($data = mysqli_fetch_assoc($result))
            {echo '
    <tr>
        <<td>'.$no.'</td>
        <td>'.$data['name'].'</td>
        <td>'.$data['major'].'</td>

    </tr>
    ';
    $no++;

http://codelution.com/development/web/easy-ways-to-export-data-from-mysql-to-excel-with-php/

Can I multiply strings in Java to repeat sequences?

Similar to what has already been said:

public String multStuff(String first, String toAdd, int amount) { 
    String append = "";
    for (int i = 1; i <= amount; i++) {
        append += toAdd;               
    }
    return first + append;
}

Input multStuff("123", "0", 3);

Output "123000"

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

How to run the Python program forever?

I have a small script interruptableloop.py that runs the code at an interval (default 1sec), it pumps out a message to the screen while it's running, and traps an interrupt signal that you can send with CTL-C:

#!/usr/bin/python3
from interruptableLoop import InterruptableLoop

loop=InterruptableLoop(intervalSecs=1) # redundant argument
while loop.ShouldContinue():
   # some python code that I want 
   # to keep on running
   pass

When you run the script and then interrupt it you see this output, (the periods pump out on every pass of the loop):

[py36]$ ./interruptexample.py
CTL-C to stop   (or $kill -s SIGINT pid)
......^C
Exiting at  2018-07-28 14:58:40.359331

interruptableLoop.py:

"""
    Use to create a permanent loop that can be stopped ...

    ... from same terminal where process was started and is running in foreground: 
        CTL-C

    ... from same user account but through a different terminal 
        $ kill -2 <pid> 
        or $ kill -s SIGINT <pid>

"""
import signal
import time
from datetime import datetime as dtt
__all__=["InterruptableLoop",]
class InterruptableLoop:
    def __init__(self,intervalSecs=1,printStatus=True):
        self.intervalSecs=intervalSecs
        self.shouldContinue=True
        self.printStatus=printStatus
        self.interrupted=False
        if self.printStatus:
            print ("CTL-C to stop\t(or $kill -s SIGINT pid)")
        signal.signal(signal.SIGINT, self._StopRunning)
        signal.signal(signal.SIGQUIT, self._Abort)
        signal.signal(signal.SIGTERM, self._Abort)

    def _StopRunning(self, signal, frame):
        self.shouldContinue = False

    def _Abort(self, signal, frame):
        raise 

    def ShouldContinue(self):
        time.sleep(self.intervalSecs)
        if self.shouldContinue and self.printStatus: 
            print( ".",end="",flush=True)
        elif not self.shouldContinue and self.printStatus:
            print ("Exiting at ",dtt.now())
        return self.shouldContinue

cmake error 'the source does not appear to contain CMakeLists.txt'

Since you add .. after cmake, it will jump up and up (just like cd ..) in the directory. But if you want to run cmake under the same folder with CMakeLists.txt, please use . instead of ...

Why is $$ returning the same id as the parent process?

You can use one of the following.

  • $! is the PID of the last backgrounded process.
  • kill -0 $PID checks whether it's still running.
  • $$ is the PID of the current shell.

How to get the seconds since epoch from the time + date output of gmtime()?

t = datetime.strptime('Jul 9, 2009 @ 20:02:58 UTC',"%b %d, %Y @ %H:%M:%S %Z")

What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?

That's because you defined your own version of name for your enum, and getByName doesn't use that.

getByName("COLUMN_HEADINGS") would probably work.

Monitor the Graphics card usage

From Unix.SE: A simple command-line utility called gpustat now exists: https://github.com/wookayin/gpustat.

It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi.

How to add a scrollbar to an HTML5 table?

I first tried the accepted answer by Mr Green, but I found my columns didn't align, that float:left seems very suspicious. When I went from no scollbar to scrollbar -- my table body shifted a few pixels and I lost alignment.

CODE PEN https://codepen.io/majorp/pen/gjrRMx

CSS

.width50px {
    width: 100px !important;
}

.width100px {
    width: 100px !important;
}


.fixed_headers {
    width: 100%;
    table-layout: fixed;
    border-collapse: collapse;
}

th {
    padding: 5px;
    text-align: left;
    font-weight:bold;
    height:50px;
}

td {
    padding: 5px;
    text-align: left;
}

thead, tr 
{
    display: block;
    position: relative;
}


tbody {
    display: block;
    overflow: auto;
    width: 100%;
    height: 500px;
}

.tableColumnHeader {
    height: 50px;
    font-weight: bold;
}




.lime {
    background-color: lime;
}

Return a string method in C#

Use x.fullNameMethod() to call the method.

How to import an Excel file into SQL Server?

You can also use OPENROWSET to import excel file in sql server.

SELECT * INTO Your_Table FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
                        'Excel 12.0;Database=C:\temp\MySpreadsheet.xlsx',
                        'SELECT * FROM [Data$]')

How do you make an element "flash" in jQuery

My way is .fadein, .fadeout .fadein, .fadeout ......

$("#someElement").fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);

_x000D_
_x000D_
function go1() { $("#demo1").fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100)}_x000D_
_x000D_
function go2() { $('#demo2').delay(100).fadeOut().fadeIn('slow') }
_x000D_
#demo1,_x000D_
#demo2 {_x000D_
  text-align: center;_x000D_
  font-family: Helvetica;_x000D_
  background: IndianRed;_x000D_
  height: 50px;_x000D_
  line-height: 50px;_x000D_
  width: 150px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<button onclick="go1()">Click Me</button>_x000D_
<div id='demo1'>My Element</div>_x000D_
<br>_x000D_
<button onclick="go2()">Click Me</button> (from comment)_x000D_
<div id='demo2'>My Element</div>
_x000D_
_x000D_
_x000D_

using scp in terminal

Simple :::

scp remoteusername@remoteIP:/path/of/file /Local/path/to/copy

scp -r remoteusername@remoteIP:/path/of/folder /Local/path/to/copy

assign multiple variables to the same value in Javascript

There is another option that does not introduce global gotchas when trying to initialize multiple variables to the same value. Whether or not it is preferable to the long way is a judgement call. It will likely be slower and may or may not be more readable. In your specific case, I think that the long way is probably more readable and maintainable as well as being faster.

The other way utilizes Destructuring assignment.

_x000D_
_x000D_
let [moveUp, moveDown,_x000D_
     moveLeft, moveRight,_x000D_
     mouseDown, touchDown] = Array(6).fill(false);_x000D_
_x000D_
console.log(JSON.stringify({_x000D_
    moveUp, moveDown,_x000D_
    moveLeft, moveRight,_x000D_
    mouseDown, touchDown_x000D_
}, null, '  '));_x000D_
_x000D_
// NOTE: If you want to do this with objects, you would be safer doing this_x000D_
let [obj1, obj2, obj3] = Array(3).fill(null).map(() => ({}));_x000D_
console.log(JSON.stringify({_x000D_
    obj1, obj2, obj3_x000D_
}, null, '  '));_x000D_
// So that each array element is a unique object_x000D_
_x000D_
// Or another cool trick would be to use an infinite generator_x000D_
let [a, b, c, d] = (function*() { while (true) yield {x: 0, y: 0} })();_x000D_
console.log(JSON.stringify({_x000D_
    a, b, c, d_x000D_
}, null, '  '));_x000D_
_x000D_
// Or generic fixed generator function_x000D_
function* nTimes(n, f) {_x000D_
    for(let i = 0; i < n; i++) {_x000D_
        yield f();_x000D_
    }_x000D_
}_x000D_
let [p1, p2, p3] = [...nTimes(3, () => ({ x: 0, y: 0 }))];_x000D_
console.log(JSON.stringify({_x000D_
    p1, p2, p3_x000D_
}, null, '  '));
_x000D_
_x000D_
_x000D_

This allows you to initialize a set of var, let, or const variables to the same value on a single line all with the same expected scope.

References:

Difference between View and ViewGroup in Android

Viewgroup inherits properties of views and does more with other views and viewgroup.

See the Android API: http://developer.android.com/reference/android/view/ViewGroup.html

Convert string to float?

Use Float.valueOf(String) to do the conversion.

The difference between valueOf() and parseFloat() is only the return. Use the former if you want a Float (object) and the latter if you want the float number.

How to check version of python modules?

I myself work in a heavily restricted server environment and unfortunately none of the solutions here are working for me. There may be no glove solution that fits all, but I figured out a swift workaround by reading the terminal output of pip freeze within my script and storing the modules labels and versions in a dictionary.

import os
os.system('pip freeze > tmpoutput')
with open('tmpoutput', 'r') as f:
    modules_version = f.read()
  
module_dict = {item.split("==")[0]:item.split("==")[-1] for item in modules_versions.split("\n")}

Retrieve your module's versions through passing the module label key, e.g.:

>>  module_dict["seaborn"]
'0.9.0'

How to programmatically move, copy and delete files and directories on SD?

Use standard Java I/O. Use Environment.getExternalStorageDirectory() to get to the root of external storage (which, on some devices, is an SD card).

How to encrypt String in Java

Here is a copy/paste solution. I also recommend reading and voting for @Konstantino's answer even though it doesn't provider any code. The initialization vector (IV) is like a salt - it doesn't have to be kept secret. I am new to GCM and apparently AAD is optional and only used in certain circumstances. Set the key in the environment variable SECRET_KEY_BASE. Use something like KeePass to generate a 32 character password. This solution is modeled after my Ruby solution.

    public static String encrypt(String s) {
        try {
            byte[] input = s.getBytes("UTF-8");
            String keyString = System.getProperty("SECRET_KEY_BASE", System.getenv("SECRET_KEY_BASE"));
            if (keyString == null || keyString.length() == 0) {
                Logger.error(Utils.class, "encrypt()", "$SECRET_KEY_BASE is not set.");
                return null;
            }
            byte[] keyBytes = keyString.getBytes("UTF-8");
            SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
            // generate IV
            SecureRandom secureRandom = SecureRandom.getInstanceStrong();
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            byte[] ivBytes = new byte[cipher.getBlockSize()];
            secureRandom.nextBytes(ivBytes);
            GCMParameterSpec gcmSpec = new GCMParameterSpec(96, ivBytes); // 96 bit tag length
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmSpec);
            // generate AAD
//          byte[] aadBytes = new byte[cipher.getBlockSize()];
//          secureRandom.nextBytes(aadBytes);
//          cipher.updateAAD(aadBytes);
            // encrypt
            byte[] encrypted = cipher.doFinal(input);
            byte[] returnBytes = new byte[ivBytes.length + encrypted.length];
//          byte[] returnBytes = new byte[ivBytes.length + aadBytes.length + encrypted.length];
            System.arraycopy(ivBytes, 0, returnBytes, 0, ivBytes.length);
//          System.arraycopy(aadBytes, 0, returnBytes, ivBytes.length, aadBytes.length);
            System.arraycopy(encrypted, 0, returnBytes, ivBytes.length, encrypted.length);
//          System.arraycopy(encrypted, 0, returnBytes, ivBytes.length+aadBytes.length, encrypted.length);
            String encryptedString = Base64.getEncoder().encodeToString(returnBytes);
            return encryptedString;
        } catch (UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | 
                InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
            Logger.error(Utils.class, "encrypt()", "Could not encrypt string: " + e.getMessage());
            return null;
        }
    }

    public static String decrypt(String s) {
        if (s == null || s.length() == 0) return "";
        try {
            byte[] encrypted = Base64.getDecoder().decode(s);
            String keyString = System.getProperty("SECRET_KEY_BASE", System.getenv("SECRET_KEY_BASE"));
            if (keyString == null || keyString.length() == 0) {
                Logger.error(Utils.class, "encrypt()", "$SECRET_KEY_BASE is not set.");
                return null;
            }
            byte[] keyBytes = keyString.getBytes("UTF-8");
            SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            byte[] ivBytes = new byte[cipher.getBlockSize()];
            System.arraycopy(encrypted, 0, ivBytes, 0, ivBytes.length);
            GCMParameterSpec gcmSpec = new GCMParameterSpec(96, ivBytes);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmSpec);
//          cipher.updateAAD(encrypted, ivBytes.length, cipher.getBlockSize());
            byte[] decrypted = cipher.doFinal(encrypted, cipher.getBlockSize(), encrypted.length - cipher.getBlockSize());
//          byte[] decrypted = cipher.doFinal(encrypted, cipher.getBlockSize()*2, encrypted.length - cipher.getBlockSize()*2);
            String decryptedString = new String(decrypted, "UTF-8");
            return decryptedString;
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | UnsupportedEncodingException | InvalidKeyException | 
                InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
            Logger.error(Utils.class, "decrypt()", "Could not decrypt string: " + e.getMessage());
            return null;
        }
    }

Here is an example:

    String s = "This is a test.";
    String enc = Utils.encrypt(s);
    System.out.println(enc);
    // fQHfYjbD+xAuN5XzH2ojk/EWNeKXUrKRSfx8LU+5dpuKkM/pueCMBjKCZw==
    String dec = Utils.decrypt(enc);
    System.out.println(dec);
    // This is a test.

Performing a Stress Test on Web Application?

This is an old question, but I think newer solutions are worthy of a mention. Checkout LoadImpact: http://www.loadimpact.com.

How to get the previous page URL using JavaScript?

You can use the following to get the previous URL.

var oldURL = document.referrer;
alert(oldURL);

How to install bcmath module?

ubuntu and php7.1

sudo apt install php7.1-bcmath

ubuntu and php without version specification

sudo apt install php-bcmath

How to create a file name with the current date & time in Python?

This one is much more human readable.

from datetime import datetime

datetime.now().strftime("%Y_%m_%d-%I_%M_%S_%p")
'2020_08_12-03_29_22_AM'

How to read .pem file to get private and public key

Read public key from pem (PK or Cert). Depends on Bouncycastle.

private static PublicKey getPublicKeyFromPEM(Reader reader) throws IOException {

    PublicKey key;

    try (PEMParser pem = new PEMParser(reader)) {
        JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter();
        Object pemContent = pem.readObject();
        if (pemContent instanceof PEMKeyPair) {
            PEMKeyPair pemKeyPair = (PEMKeyPair) pemContent;
            KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair);
            key = keyPair.getPublic();
        } else if (pemContent instanceof SubjectPublicKeyInfo) {
            SubjectPublicKeyInfo keyInfo = (SubjectPublicKeyInfo) pemContent;
            key = jcaPEMKeyConverter.getPublicKey(keyInfo);
        } else if (pemContent instanceof X509CertificateHolder) {
            X509CertificateHolder cert = (X509CertificateHolder) pemContent;
            key = jcaPEMKeyConverter.getPublicKey(cert.getSubjectPublicKeyInfo());
        } else {
            throw new IllegalArgumentException("Unsupported public key format '" +
                pemContent.getClass().getSimpleName() + '"');
        }
    }

    return key;
}

Read private key from PEM:

private static PrivateKey getPrivateKeyFromPEM(Reader reader) throws IOException {

    PrivateKey key;

    try (PEMParser pem = new PEMParser(reader)) {
        JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter();
        Object pemContent = pem.readObject();
        if (pemContent instanceof PEMKeyPair) {
            PEMKeyPair pemKeyPair = (PEMKeyPair) pemContent;
            KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair);
            key = keyPair.getPrivate();
        } else if (pemContent instanceof PrivateKeyInfo) {
            PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) pemContent;
            key = jcaPEMKeyConverter.getPrivateKey(privateKeyInfo);
        } else {
            throw new IllegalArgumentException("Unsupported private key format '" +
                pemContent.getClass().getSimpleName() + '"');
        }
    }

    return key;
}

GLYPHICONS - bootstrap icon font hex value

If you want to use glyph icons with bootstrap 2.3.2, Add the font files from bootstrap 3 to your project folder then copy this to your css file

 @font-face {
  font-family: 'Glyphicons Halflings';
  src: url('../fonts/glyphicons-halflings-regular.eot');
  src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

How to connect Bitbucket to Jenkins properly

I was just able to successfully trigger builds on commit using the Hooks option in Bitbucket to a Jenkins instance with the following steps (similar as link):

  1. Generate a custom UUID or string sequence, save for later
  2. Jenkins -> Configure Project -> Build Triggers -> "Trigger builds remotely (e.g., from scripts)"
  3. (Paste UUID/string Here) for "Authentication Token"
  4. Save
  5. Edit Bitbucket repository settings
  6. Hooks -> Edit: Endpoint: http://jenkins.something.co:9009/ Module Name: Project Name: Project Name Token: (Paste UUID/string Here)

The endpoint did not require inserting the basic HTTP auth in the URL despite using authentication, I did not use the Module Name field and the Project Name was entered case sensitive including a space in my test case. The build did not always trigger immediately but relatively fast. One other thing you may consider is disabling the "Prevent Cross Site Request Forgery exploits" option in "Configure Global Security" for testing as I've experienced all sorts of API difficulties from existing integrations when this option was enabled.

Getting rid of all the rounded corners in Twitter Bootstrap

I set all element's border-radius to "0" like this:

* {
  border-radius: 0 !important;
}

As I'm sure I don't want to overwrite this later I just use !important.

If you are not compiling your less files just do:

* {
  -webkit-border-radius: 0 !important;
     -moz-border-radius: 0 !important;
          border-radius: 0 !important;
}

In bootstrap 3 if you are compiling it you can now set radius in the variables.less file:

@border-radius-base:        0px;
@border-radius-large:       0px;
@border-radius-small:       0px;

In bootstrap 4 if you are compiling it you can disable radius alltogether in the _custom.scss file:

$enable-rounded:   false;

Setting Custom ActionBar Title from Fragment

if you are using android studio 1.4 stable template provided by google than simple you had to write following code in onNavigationItemSelected methode in which your related fragment calling if condition.

 setTitle("YOUR FRAGMENT TITLE");

how to pass parameters to query in SQL (Excel)

This post is old enough that this answer will probably be little use to the OP, but I spent forever trying to answer this same question, so I thought I would update it with my findings.

This answer assumes that you already have a working SQL query in place in your Excel document. There are plenty of tutorials to show you how to accomplish this on the web, and plenty that explain how to add a parameterized query to one, except that none seem to work for an existing, OLE DB query.

So, if you, like me, got handed a legacy Excel document with a working query, but the user wants to be able to filter the results based on one of the database fields, and if you, like me, are neither an Excel nor a SQL guru, this might be able to help you out.

Most web responses to this question seem to say that you should add a “?” in your query to get Excel to prompt you for a custom parameter, or place the prompt or the cell reference in [brackets] where the parameter should be. This may work for an ODBC query, but it does not seem to work for an OLE DB, returning “No value given for one or more required parameters” in the former instance, and “Invalid column name ‘xxxx’” or “Unknown object ‘xxxx’” in the latter two. Similarly, using the mythical “Parameters…” or “Edit Query…” buttons is also not an option as they seem to be permanently greyed out in this instance. (For reference, I am using Excel 2010, but with an Excel 97-2003 Workbook (*.xls))

What we can do, however, is add a parameter cell and a button with a simple routine to programmatically update our query text.

First, add a row above your external data table (or wherever) where you can put a parameter prompt next to an empty cell and a button (Developer->Insert->Button (Form Control) – You may need to enable the Developer tab, but you can find out how to do that elsewhere), like so:

[Picture of a cell of prompt (label) text, an empty cell, then a button.]

Next, select a cell in the External Data (blue) area, then open Data->Refresh All (dropdown)->Connection Properties… to look at your query. The code in the next section assumes that you already have a parameter in your query (Connection Properties->Definition->Command Text) in the form “WHERE (DB_TABLE_NAME.Field_Name = ‘Default Query Parameter')” (including the parentheses). Clearly “DB_TABLE_NAME.Field_Name” and “Default Query Parameter” will need to be different in your code, based on the database table name, database value field (column) name, and some default value to search for when the document is opened (if you have auto-refresh set). Make note of the “DB_TABLE_NAME.Field_Name” value as you will need it in the next section, along with the “Connection name” of your query, which can be found at the top of the dialog.

Close the Connection Properties, and hit Alt+F11 to open the VBA editor. If you are not on it already, right click on the name of the sheet containing your button in the “Project” window, and select “View Code”. Paste the following code into the code window (copying is recommended, as the single/double quotes are dicey and necessary).

Sub RefreshQuery()
 Dim queryPreText As String
 Dim queryPostText As String
 Dim valueToFilter As String
 Dim paramPosition As Integer
 valueToFilter = "DB_TABLE_NAME.Field_Name ="

 With ActiveWorkbook.Connections("Connection name").OLEDBConnection
     queryPreText = .CommandText
     paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1
     queryPreText = Left(queryPreText, paramPosition)
     queryPostText = .CommandText
     queryPostText = Right(queryPostText, Len(queryPostText) - paramPosition)
     queryPostText = Right(queryPostText, Len(queryPostText) - InStr(queryPostText, ")") + 1)
     .CommandText = queryPreText & " '" & Range("Cell reference").Value & "'" & queryPostText
 End With
 ActiveWorkbook.Connections("Connection name").Refresh
End Sub

Replace “DB_TABLE_NAME.Field_Name” and "Connection name" (in two locations) with your values (the double quotes and the space and equals sign need to be included).

Replace "Cell reference" with the cell where your parameter will go (the empty cell from the beginning) - mine was the second cell in the first row, so I put “B1” (again, the double quotes are necessary).

Save and close the VBA editor.

Enter your parameter in the appropriate cell.

Right click your button to assign the RefreshQuery sub as the macro, then click your button. The query should update and display the right data!

Notes: Using the entire filter parameter name ("DB_TABLE_NAME.Field_Name =") is only necessary if you have joins or other occurrences of equals signs in your query, otherwise just an equals sign would be sufficient, and the Len() calculation would be superfluous. If your parameter is contained in a field that is also being used to join tables, you will need to change the "paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1" line in the code to "paramPosition = InStr(Right(.CommandText, Len(.CommandText) - InStrRev(.CommandText, "WHERE")), valueToFilter) + Len(valueToFilter) - 1 + InStr(.CommandText, "WHERE")" so that it only looks for the valueToFilter after the "WHERE".

This answer was created with the aid of datapig’s “BaconBits” where I found the base code for the query update.

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

Using multidex support should be the last resort. By default gradle build will collect a ton of transitive dependencies for your APK. As recommended in Google Developers Docs, first attempt to remove unnecessary dependencies from your project.

Using command line navigate to Android Projects Root. You can get the compile dependency tree as follows.

gradlew app:dependencies --configuration debugCompileClasspath

You can get full list of dependency tree

gradlew app:dependencies

enter image description here

Then remove the unnecessary or transitive dependencies from your app build.gradle. As an example if your app uses dependency called 'com.google.api-client' you can exclude the libraries/modules you do not need.

implementation ('com.google.api-client:google-api-client-android:1.28.0'){
   exclude group: 'org.apache.httpcomponents'
   exclude group: 'com.google.guava'
   exclude group: 'com.fasterxml.jackson.core'
   }

Then in Android Studio Select Build > Analyze APK... Select the release/debug APK file to see the contents. This will give you the methods and references count as follows.

Analyze APK

Mocking member variables of a class using Mockito

If you want an alternative to ReflectionTestUtils from Spring in mockito, use

Whitebox.setInternalState(first, "second", sec);

Editing dictionary values in a foreach loop

Starting with .NET 4.5 You can do this with ConcurrentDictionary:

using System.Collections.Concurrent;

var colStates = new ConcurrentDictionary<string,int>();
colStates["foo"] = 1;
colStates["bar"] = 2;
colStates["baz"] = 3;

int OtherCount = 0;
int TotalCount = 100;

foreach(string key in colStates.Keys)
{
    double Percent = (double)colStates[key] / TotalCount;

    if (Percent < 0.05)
    {
        OtherCount += colStates[key];
        colStates[key] = 0;
    }
}

colStates.TryAdd("Other", OtherCount);

Note however that its performance is actually much worse that a simple foreach dictionary.Kes.ToArray():

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

public class ConcurrentVsRegularDictionary
{
    private readonly Random _rand;
    private const int Count = 1_000;

    public ConcurrentVsRegularDictionary()
    {
        _rand = new Random();
    }

    [Benchmark]
    public void ConcurrentDictionary()
    {
        var dict = new ConcurrentDictionary<int, int>();
        Populate(dict);

        foreach (var key in dict.Keys)
        {
            dict[key] = _rand.Next();
        }
    }

    [Benchmark]
    public void Dictionary()
    {
        var dict = new Dictionary<int, int>();
        Populate(dict);

        foreach (var key in dict.Keys.ToArray())
        {
            dict[key] = _rand.Next();
        }
    }

    private void Populate(IDictionary<int, int> dictionary)
    {
        for (int i = 0; i < Count; i++)
        {
            dictionary[i] = 0;
        }
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        BenchmarkRunner.Run<ConcurrentVsRegularDictionary>();
    }
}

Result:

              Method |      Mean |     Error |    StdDev |
--------------------- |----------:|----------:|----------:|
 ConcurrentDictionary | 182.24 us | 3.1507 us | 2.7930 us |
           Dictionary |  47.01 us | 0.4824 us | 0.4512 us |

How can I mock an ES6 module import using Jest?

The question is already answered, but you can resolve it like this:

File dependency.js

const doSomething = (x) => x
export default doSomething;

File myModule.js

import doSomething from "./dependency";

export default (x) => doSomething(x * 2);

File myModule.spec.js

jest.mock('../dependency');
import doSomething from "../dependency";
import myModule from "../myModule";

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    doSomething.mockImplementation((x) => x * 10)

    myModule(2);

    expect(doSomething).toHaveBeenCalledWith(4);
    console.log(myModule(2)) // 40
  });
});

Django - filtering on foreign key properties

student_user = User.objects.get(id=user_id)
available_subjects = Subject.objects.exclude(subject_grade__student__user=student_user) # My ans
enrolled_subjects = SubjectGrade.objects.filter(student__user=student_user)
context.update({'available_subjects': available_subjects, 'student_user': student_user, 
                'request':request, 'enrolled_subjects': enrolled_subjects})

In my application above, i assume that once a student is enrolled, a subject SubjectGrade instance will be created that contains the subject enrolled and the student himself/herself.

Subject and Student User model is a Foreign Key to the SubjectGrade Model.

In "available_subjects", i excluded all the subjects that are already enrolled by the current student_user by checking all subjectgrade instance that has "student" attribute as the current student_user

PS. Apologies in Advance if you can't still understand because of my explanation. This is the best explanation i Can Provide. Thank you so much

disable horizontal scroll on mobile web

This works for me across all mobile devices in both portrait and landscape modes.

<meta name="viewport" content="width=device-width, initial-scale = 0.86, maximum-scale=3.0, minimum-scale=0.86">

Difference between Static and final?

static means it belongs to the class not an instance, this means that there is only one copy of that variable/method shared between all instances of a particular Class.

public class MyClass {
    public static int myVariable = 0; 
}

//Now in some other code creating two instances of MyClass
//and altering the variable will affect all instances

MyClass instance1 = new MyClass();
MyClass instance2 = new MyClass();

MyClass.myVariable = 5;  //This change is reflected in both instances

final is entirely unrelated, it is a way of defining a once only initialization. You can either initialize when defining the variable or within the constructor, nowhere else.

note A note on final methods and final classes, this is a way of explicitly stating that the method or class can not be overridden / extended respectively.

Extra Reading So on the topic of static, we were talking about the other uses it may have, it is sometimes used in static blocks. When using static variables it is sometimes necessary to set these variables up before using the class, but unfortunately you do not get a constructor. This is where the static keyword comes in.

public class MyClass {

    public static List<String> cars = new ArrayList<String>();

    static {
        cars.add("Ferrari");
        cars.add("Scoda");
    }

}

public class TestClass {

    public static void main(String args[]) {
        System.out.println(MyClass.cars.get(0));  //This will print Ferrari
    }
}

You must not get this confused with instance initializer blocks which are called before the constructor per instance.

How to get ID of the last updated row in MySQL?

This is the same method as Salman A's answer, but here's the code you actually need to do it.

First, edit your table so that it will automatically keep track of whenever a row is modified. Remove the last line if you only want to know when a row was initially inserted.

ALTER TABLE mytable
ADD lastmodified TIMESTAMP 
    DEFAULT CURRENT_TIMESTAMP 
    ON UPDATE CURRENT_TIMESTAMP;

Then, to find out the last updated row, you can use this code.

SELECT id FROM mytable ORDER BY lastmodified DESC LIMIT 1;

This code is all lifted from MySQL vs PostgreSQL: Adding a 'Last Modified Time' Column to a Table and MySQL Manual: Sorting Rows. I just assembled it.

Pygame Drawing a Rectangle

Have you tried this:

PyGame Drawing Basics

Taken from the site:

pygame.draw.rect(screen, color, (x,y,width,height), thickness) draws a rectangle (x,y,width,height) is a Python tuple x,y are the coordinates of the upper left hand corner width, height are the width and height of the rectangle thickness is the thickness of the line. If it is zero, the rectangle is filled

How to list all properties of a PowerShell object

The most succinct way to do this is:

Get-WmiObject -Class win32_computersystem -Property *

Create the perfect JPA entity

The JPA 2.0 Specification states that:

  • The entity class must have a no-arg constructor. It may have other constructors as well. The no-arg constructor must be public or protected.
  • The entity class must a be top-level class. An enum or interface must not be designated as an entity.
  • The entity class must not be final. No methods or persistent instance variables of the entity class may be final.
  • If an entity instance is to be passed by value as a detached object (e.g., through a remote interface), the entity class must implement the Serializable interface.
  • Both abstract and concrete classes can be entities. Entities may extend non-entity classes as well as entity classes, and non-entity classes may extend entity classes.

The specification contains no requirements about the implementation of equals and hashCode methods for entities, only for primary key classes and map keys as far as I know.

How to convert a String to CharSequence?

CharSequence is an interface and String is its one of the implementations other than StringBuilder, StringBuffer and many other.

So, just as you use InterfaceName i = new ItsImplementation(), you can use CharSequence cs = new String("string") or simply CharSequence cs = "string";

How to overwrite existing files in batch?

you need to simply add /Y

xcopy /s c:\mmyinbox\test.doc C:\myoutbox /Y

and if you're using path with spaces, try this

xcopy /s "c:\mmyinbox\test.doc" "C:\myoutbox" /Y

Compare two date formats in javascript/jquery

This is already in :

Age from Date of Birth using JQuery

or alternatively u can use Date.parse() as in

var date1 = new Date("10/25/2011");
var date2 = new Date("09/03/2010");
var date3 = new Date(Date.parse(date1) - Date.parse(date2));

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

How can I make a div not larger than its contents?

You can try this code. Follow the code in the CSS section.

_x000D_
_x000D_
div {_x000D_
  display: inline-block;_x000D_
  padding: 2vw;_x000D_
  background-color: green;_x000D_
}_x000D_
_x000D_
table {_x000D_
  width: 70vw;_x000D_
  background-color: white;_x000D_
}
_x000D_
<div>_x000D_
    <table border="colapsed">_x000D_
      <tr>_x000D_
        <td>Apple</td>_x000D_
        <td>Banana</td>_x000D_
        <td>Strawberry</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Apple</td>_x000D_
        <td>Banana</td>_x000D_
        <td>Strawberry</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Apple</td>_x000D_
        <td>Banana</td>_x000D_
        <td>Strawberry</td>_x000D_
      </tr>_x000D_
_x000D_
    </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Java JTable setting Column Width

No need for the option, just make the preferred width of the last column the maximum and it will take all the extra space.

table.getColumnModel().getColumn(0).setPreferredWidth(27);
table.getColumnModel().getColumn(1).setPreferredWidth(120);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(90);
table.getColumnModel().getColumn(4).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(95);
table.getColumnModel().getColumn(9).setPreferredWidth(40);
table.getColumnModel().getColumn(10).setPreferredWidth(Integer.MAX_INT);

How could I create a function with a completion handler in Swift?

Simple Example:

func method(arg: Bool, completion: (Bool) -> ()) {
    print("First line of code executed")
    // do stuff here to determine what you want to "send back".
    // we are just sending the Boolean value that was sent in "back"
    completion(arg)
}

How to use it:

method(arg: true, completion: { (success) -> Void in
    print("Second line of code executed")
    if success { // this will be equal to whatever value is set in this method call
          print("true")
    } else {
         print("false")
    }
})

Is it possible to use Java 8 for Android development?

A subset of Java 8 is supported now on Android Studio. Just make the Source and Target Compatibility adjustments from the window below:

File --> Project Structure

Adjustment Window

More information is given in the below link.

https://developer.android.com/studio/write/java8-support.html

Can't access Eclipse marketplace

I know it's a bit old but I ran in the same problem today. I wanted to install eclipse on my vm with xubuntu. Because I've had problems with the latest eclipse version 2019-06 I tried with Oxygen. So I went to eclipse.org and downloaded oxygen. When running oxygen, the problem with merketplace not reachable occurs. So I downloaded the eclipse installer not immediatly the oxygen. After that I can use eclipse as expectet ( all versions)

Using ResourceManager

The quick and dirty way to check what string you need it to look at the generated .resources files.

Your .resources are generated in the resources projects obj/Debug directory. (if not right click on .resx file in solution explorer and hit 'Run Custom Tool' to generate the .resources files)

Navigate to this directory and have a look at the filenames. You should see a file ending in XYZ.resources. Copy that filename and remove the trailing .resources and that is the file you should be loading.

For example in my obj/Bin directory I have the file:

MyLocalisation.Properties.Resources.resources

If the resource files are in the same Class library/Application I would use the following C#

ResourceManager RM = new ResourceManager("MyLocalisation.Properties.Resources", Assembly.GetExecutingAssembly());

However, as it sounds like you are using the resources file from a separate Class library/Application you probably want

Assembly localisationAssembly = Assembly.Load("MyLocalisation");
ResourceManager RM =  new ResourceManager("MyLocalisation.Properties.Resources", localisationAssembly);

Create an application setup in visual studio 2013

Microsoft recommends to use the "InstallShield Limited Edition for Visual Studio" as replacement for the discontinued "Deployment and Setup Project" - but it is not so nice and nobody else recommends to use it. But for simple setups, and if it is not a problem to relay on commercial third party products, you can use it.

The alternative is to use Windows Installer XML (WiX), but you have to do many things manually that did the Setup-Project by itself.

How to know that a string starts/ends with a specific string in jQuery?

You can always extend String prototype like this:

//  Checks that string starts with the specific string
if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function (str) {
        return this.slice(0, str.length) == str;
    };
}

//  Checks that string ends with the specific string...
if (typeof String.prototype.endsWith != 'function') {
    String.prototype.endsWith = function (str) {
        return this.slice(-str.length) == str;
    };
}

And use it like this:

var str = 'Hello World';

if( str.startsWith('Hello') ) {
   // your string starts with 'Hello'
}

if( str.endsWith('World') ) {
   // your string ends with 'World'
}

#ifdef in C#

C# does have a preprocessor. It works just slightly differently than that of C++ and C.

Here is a MSDN links - the section on all preprocessor directives.

How to get the selected index of a RadioGroup in Android

You can either use OnCheckedChangeListener or can use getCheckedRadioButtonId()

"java.lang.OutOfMemoryError: PermGen space" in Maven build

This very annoying error so what I did: Under Windows:

Edit system environment variables - > Edit Variables -> New

then fill

MAVEN_OPTS
-Xms512m -Xmx2048m -XX:MaxPermSize=512m

enter image description here

Then restart the console and run the maven build again. No more Maven space/perm size problems.

LinkButton Send Value to Code Behind OnClick

Add a CommandName attribute, and optionally a CommandArgument attribute, to your LinkButton control. Then set the OnCommand attribute to the name of your Command event handler.

<asp:LinkButton ID="ENameLinkBtn" runat="server" CommandName="MyValueGoesHere" CommandArgument="OtherValueHere" 
          style="font-weight: 700; font-size: 8pt;" OnCommand="ENameLinkBtn_Command" ><%# Eval("EName") %></asp:LinkButton>

<asp:Label id="Label1" runat="server"/>

Then it will be available when in your handler:

protected void ENameLinkBtn_Command (object sender, CommandEventArgs e)
{
   Label1.Text = "You chose: " + e.CommandName + " Item " + e.CommandArgument;
}

More info on MSDN

assigning column names to a pandas series

If you have a pd.Series object x with index named 'Gene', you can use reset_index and supply the name argument:

df = x.reset_index(name='count')

Here's a demo:

x = pd.Series([2, 7, 1], index=['Ezh2', 'Hmgb', 'Irf1'])
x.index.name = 'Gene'

df = x.reset_index(name='count')

print(df)

   Gene  count
0  Ezh2      2
1  Hmgb      7
2  Irf1      1

How to convert "0" and "1" to false and true

How about:

return (returnValue == "1");

or as suggested below:

return (returnValue != "0");

The correct one will depend on what you are looking for as a success result.

Highlight all occurrence of a selected word?

  1. Add those lines in your ~/.vimrc file

" highlight the searched items set hlsearch " F8 search for word under the cursor recursively , :copen , to close -> :ccl nnoremap <F8> :grep! "\<<cword>\>" . -r<CR>:copen 33<CR>

  1. Reload the settings with :so%
  2. In normal model go over the word.

  3. Press * Press F8 to search recursively bellow your whole project over the word

Accidentally committed .idea directory files into git

Its better to perform this over Master branch

Edit .gitignore file. Add the below line in it.

.idea

Remove .idea folder from remote repo. using below command.

git rm -r --cached .idea

For more info. reference: Removing Files from a Git Repository Without Actually Deleting Them

Stage .gitignore file. Using below command

git add .gitignore

Commit

git commit -m 'Removed .idea folder'

Push to remote

git push origin master

Selecting pandas column by location

You could use label based using .loc or index based using .iloc method to do column-slicing including column ranges:

In [50]: import pandas as pd

In [51]: import numpy as np

In [52]: df = pd.DataFrame(np.random.rand(4,4), columns = list('abcd'))

In [53]: df
Out[53]: 
          a         b         c         d
0  0.806811  0.187630  0.978159  0.317261
1  0.738792  0.862661  0.580592  0.010177
2  0.224633  0.342579  0.214512  0.375147
3  0.875262  0.151867  0.071244  0.893735

In [54]: df.loc[:, ["a", "b", "d"]] ### Selective columns based slicing
Out[54]: 
          a         b         d
0  0.806811  0.187630  0.317261
1  0.738792  0.862661  0.010177
2  0.224633  0.342579  0.375147
3  0.875262  0.151867  0.893735

In [55]: df.loc[:, "a":"c"] ### Selective label based column ranges slicing
Out[55]: 
          a         b         c
0  0.806811  0.187630  0.978159
1  0.738792  0.862661  0.580592
2  0.224633  0.342579  0.214512
3  0.875262  0.151867  0.071244

In [56]: df.iloc[:, 0:3] ### Selective index based column ranges slicing
Out[56]: 
          a         b         c
0  0.806811  0.187630  0.978159
1  0.738792  0.862661  0.580592
2  0.224633  0.342579  0.214512
3  0.875262  0.151867  0.071244

How do I add a custom script to my package.json file that runs a javascript file?

I have created the following, and it's working on my system. Please try this:

package.json:

{
  "name": "test app",
  "version": "1.0.0",
  "scripts": {
    "start": "node script1.js"   
  }
}

script1.js:

console.log('testing')

From your command line run the following command:

npm start

Additional use case

My package.json file has generally the following scripts, which enable me to watch my files for typescript, sass compilations and running a server as well.

 "scripts": {
    "start": "concurrently \"sass --watch ./style/sass:./style/css\" \"npm run tsc:w\" \"npm run lite\" ",    
    "tsc": "tsc",
    "tsc:w": "tsc -w", 
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install" 
  }

How to paste text to end of every line? Sublime 2

Let's say you have these lines of code:

test line one
test line two
test line three
test line four

Using Search and Replace Ctrl+H with Regex let's find this: ^ and replace it with ", we'll have this:

"test line one
"test line two
"test line three
"test line four

Now let's search this: $ and replace it with ", now we'll have this:

"test line one"
"test line two"
"test line three"
"test line four"

SVN check out linux

There should be svn utility on you box, if installed:

$ svn checkout http://example.com/svn/somerepo somerepo

This will check out a working copy from a specified repository to a directory somerepo on our file system.

You may want to print commands, supported by this utility:

$ svn help

uname -a output in your question is identical to one, used by Parallels Virtuozzo Containers for Linux 4.0 kernel, which is based on Red Hat 5 kernel, thus your friends are rpm or the following command:

$ sudo yum install subversion

SVN: Is there a way to mark a file as "do not commit"?

I would instead write a helper bash script that runs svn commit on all the files you need to and none of the ones you don't. This way you have much more control.

For example, with one line, you can commit all files with extension .h and .cpp to which you made changes (and which wouldn't cause a conflict):

svn commit -m "" `svn status | grep "^M.*[h|cpp]$" | awk '{print $2}' | tr "\\n" " "`

Change / add extensions to the [h|cpp] part. Add a log message in between the quotes of -m "" if needed.

Automapper missing type map configuration or unsupported mapping - Error

In my case, I had created the map, but was missing the ReverseMap function. Adding it got rid of the error.

      private static void RegisterServices(ContainerBuilder bldr)
      {
         var config = new MapperConfiguration(cfg =>
         {
            cfg.AddProfile(new CampMappingProfile());
         });
         ...
       }


      public CampMappingProfile()
      {
         CreateMap<Talk, TalkModel>().ReverseMap();
         ...
      }

sql: check if entry in table A exists in table B

If you are set on using EXISTS you can use the below in SQL Server:

SELECT * FROM TableB as b
WHERE NOT EXISTS
(
   SELECT * FROM TableA as a
   WHERE b.id = a.id
)

Get the _id of inserted document in Mongo database in NodeJS

I actually did a console.log() for the second parameter in the callback function for insert. There is actually a lot of information returned apart from the inserted object itself. So the code below explains how you can access it's id.

collection.insert(objToInsert, function (err, result){
    if(err)console.log(err);
    else {
        console.log(result["ops"][0]["_id"]);
        // The above statement will output the id of the 
        // inserted object
       }
});

Iterate Multi-Dimensional Array with Nested Foreach Statement

Two ways:

  1. Define the array as a jagged array, and use nested foreachs.
  2. Define the array normally, and use foreach on the entire thing.

Example of #2:

int[,] arr = { { 1, 2 }, { 3, 4 } };
foreach(int a in arr)
    Console.Write(a);

Output will be 1234. ie. exactly the same as doing i from 0 to n, and j from 0 to n.

how to install multiple versions of IE on the same system?

I would use VMs. Create an XP (or whatever) VM using VMware Workstation or similar product, and snapshot it. That is your oldest version. Then perform the upgrades one at a time, and snapshot each time. Then you can switch to any snapshot you need later, or clone independent VMs based on all the snapshots so you can run them all at once. You probably want to test on different operating systems as well as different versions, so VMs generalize that solution as well rather than some one-off solution of hacking multiple IEs to coexist on a single instance of Windows.

NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack

OK, they all have got some similarities, they do the same things for you in different and similar ways, I divide them in 3 main groups as below:


1) Module bundlers

webpack and browserify as popular ones, work like task runners but with more flexibility, aslo it will bundle everything together as your setting, so you can point to the result as bundle.js for example in one single file including the CSS and Javascript, for more details of each, look at the details below:

webpack

webpack is a module bundler for modern JavaScript applications. When webpack processes your application, it recursively builds a dependency graph that includes every module your application needs, then packages all of those modules into a small number of bundles - often only one - to be loaded by the browser.

It is incredibly configurable, but to get started you only need to understand Four Core Concepts: entry, output, loaders, and plugins.

This document is intended to give a high-level overview of these concepts, while providing links to detailed concept specific use-cases.

more here

browserify

Browserify is a development tool that allows us to write node.js-style modules that compile for use in the browser. Just like node, we write our modules in separate files, exporting external methods and properties using the module.exports and exports variables. We can even require other modules using the require function, and if we omit the relative path it’ll resolve to the module in the node_modules directory.

more here


2) Task runners

gulp and grunt are task runners, basically what they do, creating tasks and run them whenever you want, for example you install a plugin to minify your CSS and then run it each time to do minifying, more details about each:

gulp

gulp.js is an open-source JavaScript toolkit by Fractal Innovations and the open source community at GitHub, used as a streaming build system in front-end web development. It is a task runner built on Node.js and Node Package Manager (npm), used for automation of time-consuming and repetitive tasks involved in web development like minification, concatenation, cache busting, unit testing, linting, optimization etc. gulp uses a code-over-configuration approach to define its tasks and relies on its small, single-purposed plugins to carry them out. gulp ecosystem has 1000+ such plugins made available to choose from.

more here

grunt

Grunt is a JavaScript task runner, a tool used to automatically perform frequently used tasks such as minification, compilation, unit testing, linting, etc. It uses a command-line interface to run custom tasks defined in a file (known as a Gruntfile). Grunt was created by Ben Alman and is written in Node.js. It is distributed via npm. Presently, there are more than five thousand plugins available in the Grunt ecosystem.

more here


3) Package managers

package managers, what they do is managing plugins you need in your application and install them for you through github etc using package.json, very handy to update you modules, install them and sharing your app across, more details for each:

npm

npm is a package manager for the JavaScript programming language. It is the default package manager for the JavaScript runtime environment Node.js. It consists of a command line client, also called npm, and an online database of public packages, called the npm registry. The registry is accessed via the client, and the available packages can be browsed and searched via the npm website.

more here

bower

Bower can manage components that contain HTML, CSS, JavaScript, fonts or even image files. Bower doesn’t concatenate or minify code or do anything else - it just installs the right versions of the packages you need and their dependencies. To get started, Bower works by fetching and installing packages from all over, taking care of hunting, finding, downloading, and saving the stuff you’re looking for. Bower keeps track of these packages in a manifest file, bower.json.

more here

and the most recent package manager that shouldn't be missed, it's young and fast in real work environment compare to npm which I was mostly using before, for reinstalling modules, it do double checks the node_modules folder to check the existence of the module, also seems installing the modules takes less time:

yarn

Yarn is a package manager for your code. It allows you to use and share code with other developers from around the world. Yarn does this quickly, securely, and reliably so you don’t ever have to worry.

Yarn allows you to use other developers’ solutions to different problems, making it easier for you to develop your software. If you have problems, you can report issues or contribute back, and when the problem is fixed, you can use Yarn to keep it all up to date.

Code is shared through something called a package (sometimes referred to as a module). A package contains all the code being shared as well as a package.json file which describes the package.

more here


finding the type of an element using jQuery

You can use .prop() with tagName as the name of the property that you want to get:

$("#elementId").prop('tagName'); 

Send raw ZPL to Zebra printer via USB

Found amazing simple solution - working for Chrome (Windows, not tested on Mac)

Zebra ZP 450

  1. Go here Zebra Generic Text
  2. Go precisely by the manual
  3. No COM1 or any other ports needed - USB is enough
  4. When done (named the printer ZTEXT), does not matter if it won't print a test page
  5. Turn of Spooling and enable direct printing in Printer Preferences - 1 note here 1 printer is ZP450 CPT and other ZP450 only - on the other one I do not even need to turn off spooling and it worked.
  6. Go to Chrome and printing ZPL from there with Chrome Print Dialog Box by selecting the ZTEXT printer (Generic / Text) Printer (Do not choose Windows Dialog Box) - we needed this for Chrome to be working

Jquery ajax call click event submit button

You did not add # before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.

See documentation: http://api.jquery.com/category/selectors/
its your friend.

Try this:

It seems that id: $("#Shareitem").val() is wrong if you want to pass the value of

<input type="hidden" name="id" value="" id="id">

you need to change this line:

id: $("#Shareitem").val()

by

id: $("#id").val()

All together:

 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
    $(document).ready(function(){
      $("#Shareitem").click(function(e){
          e.preventDefault();
        $.ajax({type: "POST",
                url: "/imball-reagens/public/shareitem",
                data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
                success:function(result){
          $("#sharelink").html(result);
        }});
      });
    });
    </script>

Creating a Custom Event

Yes you can do like this :

Creating advanced C# custom events

or

The Simplest C# Events Example Imaginable

public class Metronome
{
    public event TickHandler Tick;
    public EventArgs e = null;
    public delegate void TickHandler(Metronome m, EventArgs e);
    public void Start()
    {
        while (true)
        {
            System.Threading.Thread.Sleep(3000);
            if (Tick != null)
            {
                Tick(this, e);
            }
        }
    }
}
public class Listener
{
    public void Subscribe(Metronome m)
    {
        m.Tick += new Metronome.TickHandler(HeardIt);
    }

    private void HeardIt(Metronome m, EventArgs e)
    {
        System.Console.WriteLine("HEARD IT");
    }
}
class Test
{
    static void Main()
    {
        Metronome m = new Metronome();
        Listener l = new Listener();
        l.Subscribe(m);
        m.Start();
    }
}

Bash scripting missing ']'

add a space before the close bracket

How to write subquery inside the OUTER JOIN Statement

I think you don't have to use sub query in this scenario.You can directly left outer join the DEPRMNT table .

While using Left Outer Join ,don't use columns in the RHS table of the join in the where condition, you ll get wrong output

How to do fade-in and fade-out with JavaScript and CSS

Here is a simplified running example of Seattle Ninja's solution.

_x000D_
_x000D_
var slideSource = document.getElementById('slideSource');_x000D_
_x000D_
document.getElementById('handle').onclick = function () {_x000D_
  slideSource.classList.toggle('fade');_x000D_
}
_x000D_
#slideSource {_x000D_
  opacity: 1;_x000D_
  transition: opacity 1s; _x000D_
}_x000D_
_x000D_
#slideSource.fade {_x000D_
  opacity: 0;_x000D_
}
_x000D_
<button id="handle">Fade</button> _x000D_
<div id="slideSource">Whatever you want here - images or text</div>
_x000D_
_x000D_
_x000D_

How to make EditText not editable through XML in Android?

As you mentioned android:editable is deprecated. android:inputType="none" should be used instead but it does not work due to a bug (https://code.google.com/p/android/issues/detail?id=2854)

But you can achieve the same thing by using focusable.

Via XML:

<EditText ...
        android:focusable="false" 
</EditText>

From code:

((EditText) findViewById(R.id.LoginNameEditText)).setFocusable(false);

error: request for member '..' in '..' which is of non-class type

If you want to declare a new substance with no parameter (knowing that the object have default parameters) don't write

 type substance1();

but

 type substance;

The calling thread must be STA, because many UI components require this

If you call a new window UI statement in an existing thread, it throws an error. Instead of that create a new thread inside the main thread and write the window UI statement in the new child thread.

How do I download/extract font from chrome developers tools?

Open chrome

Right click => inspect => navigate to application tab

In Frames section, all the statically available assets(resources) such as css, JavaScript, fonts are listed.

Convert Java object to XML string

You can use the Marshaler's method for marshaling which takes a Writer as parameter:

marshal(Object,Writer)

and pass it an Implementation which can build a String object

Direct Known Subclasses: BufferedWriter, CharArrayWriter, FilterWriter, OutputStreamWriter, PipedWriter, PrintWriter, StringWriter

Call its toString method to get the actual String value.

So doing:

StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(customer, sw);
String xmlString = sw.toString();

How to attach a process in gdb

With a running instance of myExecutableName having a PID 15073:

hitting Tab twice after $ gdb myExecu in the command line, will automagically autocompletes to:

$ gdb myExecutableName 15073

and will attach gdb to this process. That's nice!

Get POST data in C#/ASP.NET

Try using:

string ap = c.Request["AP"];

That reads from the cookies, form, query string or server variables.

Alternatively:

string ap = c.Request.Form["AP"];

to just read from the form's data.

Add object to ArrayList at specified index

You can do it like this:

list.add(1, object1)
list.add(2, object3)
list.add(2, object2)

After you add object2 to position 2, it will move object3 to position 3.

If you want object3 to be at position3 all the time I'd suggest you use a HashMap with position as key and object as a value.

CodeIgniter Disallowed Key Characters

function _clean_input_keys($str)
{
if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str))
{
exit('Disallowed Key Characters.');
}

return $str;
}

Please add .$str to exit('Disallowed Key Characters.'); Like: exit('Disallowed Key Characters. '.$str);

to help you in your search for rogue errors.

jQuery - Check if DOM element already exists

This question is about whether an element exists and all answers check if it doesn't exist :) Minor difference but worth mentioning.

Based on jQuery documentation the recommended way to check for existence is

if ($( "#myDiv" ).length) {
    // element exists
}

If you prefer to check for missing element you could use either:

if (!$( "#myDiv" ).length) {
    // element doesn't exist
}

or

if (0 === $( "#myDiv" ).length) {
    // element doesn't exist
}

Note please that in the second option I've used === which is slightly faster than == and put the 0 on the left as a Yoda condition.

Anaconda Navigator won't launch (windows 10)

Update to the latest conda and latest navigator will resolve this issue.

Open the Anaconda Prompt and type

  • conda update conda

and

  • conda update anaconda-navigator

MySQL Select all columns from one table and some from another table

Just use the table name:

SELECT myTable.*, otherTable.foo, otherTable.bar...

That would select all columns from myTable and columns foo and bar from otherTable.

Move existing, uncommitted work to a new branch in Git

There is actually a really easy way to do this with GitHub Desktop now that I don't believe was a feature before.

All you need to do is switch to the new branch in GitHub Desktop, and it will prompt you to leave your changes on the current branch (which will be stashed), or to bring your changes with you to the new branch. Just choose the second option, to bring the changes to the new branch. You can then commit as usual.

GitHub Desktop

Horizontal scroll on overflow of table

The solution for those who cannot or do not want to wrap the table in a div (e.g. if the HTML is generated from Markdown) but still want to have scrollbars:

_x000D_
_x000D_
table {_x000D_
  display: block;_x000D_
  max-width: -moz-fit-content;_x000D_
  max-width: fit-content;_x000D_
  margin: 0 auto;_x000D_
  overflow-x: auto;_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>Especially on mobile, a table can easily become wider than the viewport.</td>_x000D_
    <td>Using the right CSS, you can get scrollbars on the table without wrapping it.</td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>A centered table.</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Explanation: display: block; makes it possible to have scrollbars. By default (and unlike tables), blocks span the full width of the parent element. This can be prevented with max-width: fit-content;, which allows you to still horizontally center tables with less content using margin: 0 auto;. white-space: nowrap; is optional (but useful for this demonstration).

HTML button opening link in new tab

If you're in pug:

html
    head
        title Pug
    body
        a(href="http://www.example.com" target="_blank") Example
        button(onclick="window.open('http://www.example.com')") Example

And if you're puggin' Semantic UI:

html
    head
        title Pug
        link(rel='stylesheet' href='https://cdn.jsdelivr.net/npm/[email protected]/dist/semantic.min.css')
    body
        .ui.center.aligned.container
            a(href="http://www.example.com" target="_blank") Example
        .ui.center.aligned.container
           .ui.large.grey.button(onclick="window.open('http://www.example.com')") Example

Set IDENTITY_INSERT ON is not working

In VB code, when trying to submit an INSERT query, you must submit a double query in the same 'executenonquery' like this:

sqlQuery = "SET IDENTITY_INSERT dbo.TheTable ON; INSERT INTO dbo.TheTable (Col1, COl2) VALUES (Val1, Val2); SET IDENTITY_INSERT dbo.TheTable OFF;"

I used a ; separator instead of a GO.

Works for me. Late but efficient!

Regular expression - starting and ending with a character string

^wp.*\.php$ Should do the trick.

The .* means "any character, repeated 0 or more times". The next . is escaped because it's a special character, and you want a literal period (".php"). Don't forget that if you're typing this in as a literal string in something like C#, Java, etc., you need to escape the backslash because it's a special character in many literal strings.

"webxml attribute is required" error in Maven

If you are migrating from XML-based to Java-based configuration and you have removed the need for web.xml by implementing WebApplicationInitializer, simply remove the requirement for the web.xml file to be present.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.6</version>
    <configuration>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        ... 
    </configuration>

Truncate a string straight JavaScript

Updated ES6 version

const truncateString = (string, maxLength = 50) => {
  if (!string) return null;
  if (string.length <= maxLength) return string;
  return `${string.substring(0, maxLength)}...`;
};

truncateString('what up', 4); // returns 'what...'

Enable VT-x in your BIOS security settings (refer to documentation for your computer)

Intel HAXM is required to run this AVD. VT-x is disabled in BIOS.

Enable VT-x in your BIOS security settings (refer to documentation for your computer).this error on android studio I dont no how to do Bios Security

How to check if a MySQL query using the legacy API was successful?

You can use mysql_errno() for this too.

$result = mysql_query($query);

if(mysql_errno()){
    echo "MySQL error ".mysql_errno().": "
         .mysql_error()."\n<br>When executing <br>\n$query\n<br>";
}

Removing elements from array Ruby

You may do:

a= [1,1,1,2,2,3]
delete_list = [1,3]
delete_list.each do |del|
    a.delete_at(a.index(del))
end

result : [1, 1, 2, 2]

Missing Microsoft RDLC Report Designer in Visual Studio

I've had the same problem as you and I installed Microsoft rdlc designer to solve my problem.

And if you already installed this but still can't found rdlc designer try open visual studio > tools > Extension and Updates > then enable Miscrosoft Rdlc designer extensions.

hadoop No FileSystem for scheme: file

For SBT use below mergeStrategy in build.sbt

mergeStrategy in assembly <<= (mergeStrategy in assembly) { (old) => {
    case PathList("META-INF", "services", "org.apache.hadoop.fs.FileSystem") => MergeStrategy.filterDistinctLines
    case s => old(s)
  }
}

Change PictureBox's image to image from my resources?

Ok...so first you need to import in your project the image

1)Select the picturebox in Form Design

2)Open PictureBox Tasks (it's the little arrow pinted to right on the edge on the picturebox)

3)Click on "Choose image..."

4)Select the second option "Project resource file:" (this option will create a folder called "Resources" which you can acces with Properties.Resources)

5)Click on import and select your image from your computer (now a copy of the image with the same name as the image will be sent in Resources folder created at step 4)

6)Click on ok

Now the image is in your project and you can use it with Properties command.Just type this code when you want to change the picture from picturebox:

pictureBox1.Image = Properties.Resources.myimage;

Note: myimage represent the name of the image...after typing the dot after Resources,in your options it will be your imported image file

How do you round a number to two decimal places in C#?

Try this:

twoDec = Math.Round(val, 2)

Combining two expressions (Expression<Func<T, bool>>)

Well, you can use Expression.AndAlso / OrElse etc to combine logical expressions, but the problem is the parameters; are you working with the same ParameterExpression in expr1 and expr2? If so, it is easier:

var body = Expression.AndAlso(expr1.Body, expr2.Body);
var lambda = Expression.Lambda<Func<T,bool>>(body, expr1.Parameters[0]);

This also works well to negate a single operation:

static Expression<Func<T, bool>> Not<T>(
    this Expression<Func<T, bool>> expr)
{
    return Expression.Lambda<Func<T, bool>>(
        Expression.Not(expr.Body), expr.Parameters[0]);
}

Otherwise, depending on the LINQ provider, you might be able to combine them with Invoke:

// OrElse is very similar...
static Expression<Func<T, bool>> AndAlso<T>(
    this Expression<Func<T, bool>> left,
    Expression<Func<T, bool>> right)
{
    var param = Expression.Parameter(typeof(T), "x");
    var body = Expression.AndAlso(
            Expression.Invoke(left, param),
            Expression.Invoke(right, param)
        );
    var lambda = Expression.Lambda<Func<T, bool>>(body, param);
    return lambda;
}

Somewhere, I have got some code that re-writes an expression-tree replacing nodes to remove the need for Invoke, but it is quite lengthy (and I can't remember where I left it...)


Generalized version that picks the simplest route:

static Expression<Func<T, bool>> AndAlso<T>(
    this Expression<Func<T, bool>> expr1,
    Expression<Func<T, bool>> expr2)
{
    // need to detect whether they use the same
    // parameter instance; if not, they need fixing
    ParameterExpression param = expr1.Parameters[0];
    if (ReferenceEquals(param, expr2.Parameters[0]))
    {
        // simple version
        return Expression.Lambda<Func<T, bool>>(
            Expression.AndAlso(expr1.Body, expr2.Body), param);
    }
    // otherwise, keep expr1 "as is" and invoke expr2
    return Expression.Lambda<Func<T, bool>>(
        Expression.AndAlso(
            expr1.Body,
            Expression.Invoke(expr2, param)), param);
}

Starting from .NET 4.0, there is the ExpressionVisitor class which allows you to build expressions that are EF safe.

    public static Expression<Func<T, bool>> AndAlso<T>(
        this Expression<Func<T, bool>> expr1,
        Expression<Func<T, bool>> expr2)
    {
        var parameter = Expression.Parameter(typeof (T));

        var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
        var left = leftVisitor.Visit(expr1.Body);

        var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter);
        var right = rightVisitor.Visit(expr2.Body);

        return Expression.Lambda<Func<T, bool>>(
            Expression.AndAlso(left, right), parameter);
    }



    private class ReplaceExpressionVisitor
        : ExpressionVisitor
    {
        private readonly Expression _oldValue;
        private readonly Expression _newValue;

        public ReplaceExpressionVisitor(Expression oldValue, Expression newValue)
        {
            _oldValue = oldValue;
            _newValue = newValue;
        }

        public override Expression Visit(Expression node)
        {
            if (node == _oldValue)
                return _newValue;
            return base.Visit(node);
        }
    }

What is the difference between atomic / volatile / synchronized?

volatile:

volatile is a keyword. volatile forces all threads to get latest value of the variable from main memory instead of cache. No locking is required to access volatile variables. All threads can access volatile variable value at same time.

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.

This means that changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.

When to use: One thread modifies the data and other threads have to read latest value of data. Other threads will take some action but they won't update data.

AtomicXXX:

AtomicXXX classes support lock-free thread-safe programming on single variables. These AtomicXXX classes (like AtomicInteger) resolves memory inconsistency errors / side effects of modification of volatile variables, which have been accessed in multiple threads.

When to use: Multiple threads can read and modify data.

synchronized:

synchronized is keyword used to guard a method or code block. By making method as synchronized has two effects:

  1. First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

  2. Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

When to use: Multiple threads can read and modify data. Your business logic not only update the data but also executes atomic operations

AtomicXXX is equivalent of volatile + synchronized even though the implementation is different. AmtomicXXX extends volatile variables + compareAndSet methods but does not use synchronization.

Related SE questions:

Difference between volatile and synchronized in Java

Volatile boolean vs AtomicBoolean

Good articles to read: ( Above content is taken from these documentation pages)

https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html

https://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html

ITextSharp HTML to PDF?

If you are converting html to pdf on the html server side you can use Rotativa :

Install-Package Rotativa

This is based on wkhtmltopdf but it has better css support than iTextSharp has and is very simple to integrate with MVC (which is mostly used) as you can simply return the view as pdf:

public ActionResult GetPdf()
{
    //...
    return new ViewAsPdf(model);// and you are done!
} 

Is it possible to insert HTML content in XML document?

Please see this.

Text inside a CDATA section will be ignored by the parser.

http://www.w3schools.com/xml/dom_cdatasection.asp

This is will help you to understand the basics about XML