Programs & Examples On #Scanning

Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

You should add the code into pom.xml like:

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

Vue template or render function not defined yet I am using neither?

As a Summary of all the posts

This error:

[Vue warn]: Failed to mount component: template or render function not defined.

You're getting because of a certain problem that's preventing your component from being mounted.

This can be caused by a lot of different issues, as you can see from the different posts here. Debug your component thoroughly, and be aware of everything that is maybe not done correctly and might prevent the mount.

I was getting the error when my component file was not encoded correctly...

converting json to string in python

json.dumps() is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.

For instance, if one of the values is None, the str() would produce an invalid JSON which cannot be loaded:

>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)

But the dumps() would convert None into null making a valid JSON string that can be loaded:

>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}

How can I install Python's pip3 on my Mac?

I solved the same problem with these commands:

curl -O https://bootstrap.pypa.io/get-pip.py
sudo python3 get-pip.py

How do I force Maven to use my local repository rather than going out to remote repos to retrieve artifacts?

To truly force maven to only use your local repo, you can run with mvn <goals> -o. The -o tells maven to let you work "offline", and it will stay off the network.

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

None of the other answers worked for me. The solution that worked for me was to download the missing artifact manually via cmd:

mvn dependency:get -DrepoUrl=http://repo.maven.apache.org/maven2/ -Dartifact=ro.isdc.wro4j:wro4j-maven-plugin:1.8.0

Run a command shell in jenkins

Error shows that script does not exists

The file does not exists. check your full path

C:\Windows\TEMP\hudson6299483223982766034.sh
The system cannot find the file specified

Moreover, to launch .sh scripts into windows, you need to have CYGWIN installed and well configured into your path

Confirm that script exists.

Into jenkins script, do the following to confirm that you do have the file

cd C:\Windows\TEMP\
ls -rtl
sh -xe hudson6299483223982766034.sh

Why am I getting a "401 Unauthorized" error in Maven?

It could be caused by wrong version, you can double check the parent's version and lib's version, to make sure they're correct and not duplicated, I've experienced same problem

How to split a python string on new line characters

a.txt

this is line 1
this is line 2

code:

Python 3.4.0 (default, Mar 20 2014, 22:43:40) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']

I'm on Linux, but I guess you just use \r\n on Windows and it would also work

JPG vs. JPEG image formats

No difference at all.

I personally prefer having 3 letters extensions, but you might prefer having the full name.
It's pure aestetics (personal taste), nothing else.
The format doesn't change.

You can rename the jpeg files into jpg (or vice versa) an nothing changes: they will open in your picture viewer.

By opening both a JPG and a JPEG file with an hex editor, you will notice that they share the very same heading information.

How to make java delay for a few seconds?

This is in a mouseEvent btw

If this is in a Swing GUI, then get rid of all calls to Thread.sleep(...) as doing so can put the entire GUI to sleep rendering it useless. Instead use a Swing Timer to produce any delays in the GUI while letting it still update its graphics.

You'll also want to avoid System.out.println(...) calls, except when debugging, and instead display user notifications in the GUI itself, perhaps in a status JLabel or as a message dialog.

OPTION (RECOMPILE) is Always Faster; Why?

To add to the excellent list (given by @CodeCowboyOrg) of situations where OPTION(RECOMPILE) can be very helpful,

  1. Table Variables. When you are using table variables, there will not be any pre-built statistics for the table variable, often leading to large differences between estimated and actual rows in the query plan. Using OPTION(RECOMPILE) on queries with table variables allows generation of a query plan that has a much better estimate of the row numbers involved. I had a particularly critical use of a table variable that was unusable, and which I was going to abandon, until I added OPTION(RECOMPILE). The run time went from hours to just a few minutes. That is probably unusual, but in any case, if you are using table variables and working on optimizing, it's well worth seeing whether OPTION(RECOMPILE) makes a difference.

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

You should add maven-resources-plugin in your pom.xml file. Deleting ~/.m2/repository does not work always.

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.4</version>
            </plugin>
        </plugins>

Now build your project again. It should be successful!

How to generate classes from wsdl using Maven and wsimport?

The key here is keep option of wsimport. And it is configured using element in About keep from the wsimport documentation :

-keep                     keep generated files

Errors in pom.xml with dependencies (Missing artifact...)

This is a very late answer,but this might help.I went to this link and searched for ojdbc8(I was trying to add jdbc oracle driver) When clicked on the result , a note was displayed like this:

enter image description here

I clicked the link in the note and the correct dependency was mentioned like below enter image description here

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

To solve this problem in IntelliJ...
1) Put your .fxml files into resources directory
2) In the Start method define the path to .fxml file in the following way:
Parent root = FXMLLoader.load(getClass().getResource("/sample.fxml"));
The / seemed to solve this problem for me :)

Barcode scanner for mobile phone for Website in form

Check out https://github.com/serratus/quaggaJS

"QuaggaJS is a barcode-scanner entirely written in JavaScript supporting real- time localization and decoding of various types of barcodes such as EAN, CODE 128, CODE 39, EAN 8, UPC-A, UPC-C, I2of5, 2of5, CODE 93 and CODABAR. The library is also capable of using getUserMedia to get direct access to the user's camera stream. Although the code relies on heavy image-processing even recent smartphones are capable of locating and decoding barcodes in real-time."

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

It is because your Maven not able to find settings file. If deleting .m2 not work, try below solution

Go to your JOB configuration

than to the Build section

Add build step :- Invoke top level maven target and fill Maven version and Goal

than click on Advance button and mention settings file path as mention in image enter image description here

Printf width specifier to maintain precision of floating-point value

To my knowledge, there is a well diffused algorithm allowing to output to the necessary number of significant digits such that when scanning the string back in, the original floating point value is acquired in dtoa.c written by Daniel Gay, which is available here on Netlib (see also the associated paper). This code is used e.g. in Python, MySQL, Scilab, and many others.

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

  • The execution of maven command required pom.xml file that contains information about the project and configuration details used by Maven to build the project. It contains default values for most projects.

  • Make sure that porject should contains pom.xml at the root level.

How to disable Python warnings?

warnings are output via stderr and the simple solution is to append '2> /dev/null' to the CLI. this makes a lot of sense to many users such as those with centos 6 that are stuck with python 2.6 dependencies (like yum) and various modules are being pushed to the edge of extinction in their coverage.

this is especially true for cryptography involving SNI et cetera. one can update 2.6 for HTTPS handling using the proc at: https://urllib3.readthedocs.io/en/latest/user-guide.html#ssl-py2

the warning is still in place, but everything you want is back-ported. the re-direct of stderr will leave you with clean terminal/shell output although the stdout content itself does not change.

responding to FriendFX. sentence one (1) responds directly to the problem with an universal solution. sentence two (2) takes into account the cited anchor re 'disable warnings' which is python 2.6 specific and notes that RHEL/centos 6 users cannot directly do without 2.6. although no specific warnings were cited, para two (2) answers the 2.6 question I most frequently get re the short-comings in the cryptography module and how one can "modernize" (i.e., upgrade, backport, fix) python's HTTPS/TLS performance. para three (3) merely explains the outcome of using the re-direct and upgrading the module/dependencies.

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

For Tomcat 8, I had to add the following line to tomcat/conf/logging.properties for the jars scanned by Tomcat to show up in the logs:

org.apache.jasper.servlet.TldScanner.level = FINE

Android + Pair devices via bluetooth programmatically

if you have the BluetoothDevice object you can create bond(pair) from api 19 onwards with bluetoothDevice.createBond() method.

Edit

for callback, if the request was accepted or denied you will have to create a BroadcastReceiver with BluetoothDevice.ACTION_BOND_STATE_CHANGED action

"Non-resolvable parent POM: Could not transfer artifact" when trying to refer to a parent pom from a child pom with ${parent.groupid}

As Nayan said the Path has to updated properly in my case the apache-maven was installed in C:\apache-maven and settings.xml was found inside C:\apache-maven\conf\settings.xml

if this doesn't work go to your local repos
in my case C:\Users\<<"name">>.m2\
and search for .lastUpdated and delete them
then build the maven

Non-resolvable parent POM for Could not find artifact and 'parent.relativePath' points at wrong local POM

Any way you mentioned /root/.m2/settings.xml.

But in my Case i missed the settings.xml to configure in the maven preferences. enter image description here so that maven will search for the relative_path pom.xml from the remote_repository which is configured in settings.xml

At least one JAR was scanned for TLDs yet contained no TLDs

(tomcat 8.0.28) Above method did not work for me. This is what worked:

  1. Add this line to the end of your {CATALINA-HOME}/conf/logging.properties:

    org.apache.jasper.level = FINEST
    
  2. Shut down the server (if started).

  3. Open console and run (in case of Windows):

    %CATALINA_HOME%\bin\catalina.bat run
    
  4. Enjoy logs, e.g. (again, for Windows):

    {CATALINA-HOME}/logs/catalina.2015-12-28.log
    

I gave up on integrating this with Eclipse launch configuration so be aware that this works only from console, launching the server from Eclipse won't produce additional log messages.

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

Add bean declaration in bean.xml file or in any other configuration file . It will resolve the error

<bean  class="com.demo.dao.RailwayDao"></bean>
<bean  class="com.demo.service.RailwayService"></bean>
<bean  class="com.demo.model.RailwayReservation"></bean>

Spring: @Component versus @Bean

When you use the @Component tag, it's the same as having a POJO (Plain Old Java Object) with a vanilla bean declaration method (annotated with @Bean). For example, the following method 1 and 2 will give the same result.

Method 1

@Component
public class SomeClass {

    private int number;

    public SomeClass(Integer theNumber){
        this.number = theNumber.intValue();
    }

    public int getNumber(){
        return this.number;
    }
}

with a bean for 'theNumber':

@Bean
Integer theNumber(){
    return new Integer(3456);
}

Method 2

//Note: no @Component tag
public class SomeClass {

    private int number;

    public SomeClass(Integer theNumber){
        this.number = theNumber.intValue();
    }

    public int getNumber(){
        return this.number;
    }
}

with the beans for both:

@Bean
Integer theNumber(){
    return new Integer(3456);
}

@Bean
SomeClass someClass(Integer theNumber){
    return new SomeClass(theNumber);
}

Method 2 allows you to keep bean declarations together, it's a bit more flexible etc. You may even want to add another non-vanilla SomeClass bean like the following:

@Bean
SomeClass strawberryClass(){
    return new SomeClass(new Integer(1));
}

Tomcat 7 "SEVERE: A child container failed during start"

"there is no problem with tomcat".

I have suffered 4-5 days to resolve the issue (same issue mentioned above). here i was using tomcat 8.5. Finally, the issue got resolved, the issue was with the "Corrupted jar files". You have to delete all your .m2 repository (for me C:\Users\Bandham.m2\repository). den run "mvn clean install" command from your project folder.

happy coding.

Give one UP if it is solved your problem.

Error creating bean with name

I think it comes from this line in your XML file:

<context:component-scan base-package="org.assessme.com.controller." />

Replace it by:

<context:component-scan base-package="org.assessme.com." />

It is because your Autowired service is not scanned by Spring since it is not in the right package.

c# Best Method to create a log file

We did a lot of research into logging, and decided that NLog was the best one to use.

See http://nlog-project.org/

Also see log4net vs. Nlog and http://www.dotnetlogging.com/comparison/

Oracle JDBC ojdbc6 Jar as a Maven Dependency

The correct answer was supplied by Raghuram in the comments section to my original question.

For whatever reason, pointing "mvn install" to a full path of the physical ojdbc6.jar file didn't work for me. (Or I consistently repeatedly flubbed it up when running the command, but no errors were issued.)

cd-ing into the directory where I keep ojdb6.jar and running the command from there worked the first time.

If Raghuram would like to answer this question, I'll accept his answer instead. Thanks everyone!

Connect Android to WiFi Enterprise network EAP(PEAP)

Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.

The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.

There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.

Its name is Wifi Config Advanced Editor.

  • First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.

  • Save it.

  • Go to the WCE and edit the parameters of the network you have created in the previous step.

  • There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
    As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.

  • When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.

  • Do not Edit the network again with the Android wifi interface.

I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.

Byte array to image conversion

public Image byteArrayToImage(byte[] bytesArr)
{
    using (MemoryStream memstr = new MemoryStream(bytesArr))
    {
        Image img = Image.FromStream(memstr);
        return img;
    }
}

How can I convert a series of images to a PDF from the command line on linux?

Using imagemagick, you can try:

convert page.png page.pdf

Or for multiple images:

convert page*.png mydoc.pdf

Neither BindingResult nor plain target object for bean name available as request attribute

I had problem like this, but with several "actions". My solution looks like this:

    <form method="POST" th:object="${searchRequest}" action="searchRequest" >
          <input type="text" th:field="*{name}"/>
          <input type="submit" value="find" th:value="find" />
    </form>
        ...
    <form method="POST" th:object="${commodity}" >
        <input type="text" th:field="*{description}"/>
        <input type="submit" value="add" />
    </form>

And controller

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @RequestMapping(value = "add", method = GET)
    public String showGoodsForm(Model model){
           model.addAttribute(new Commodity());
           model.addAttribute("searchRequest", new SearchRequest());
           return "goodsForm";
    }
    @RequestMapping(value = "add", method = POST)
    public ModelAndView processAddCommodities(
            @Valid Commodity commodity,
            Errors errors) {
        if (errors.hasErrors()) {
            ModelAndView model = new ModelAndView("goodsForm");
            model.addObject("searchRequest", new SearchRequest());
            return model;
        }
        ModelAndView model = new ModelAndView("redirect:/goods/" + commodity.getName());
        model.addObject(new Commodity());
        model.addObject("searchRequest", new SearchRequest());
        return model;
    }
    @RequestMapping(value="searchRequest", method=POST)
    public String processFindCommodity(SearchRequest commodity, Model model) {
    ...
        return "catalog";
    }

I'm sure - here is not "best practice", but it is works without "Neither BindingResult nor plain target object for bean name available as request attribute".

@Scope("prototype") bean scope not creating new bean

By default, Spring beans are singletons. The problem arises when we try to wire beans of different scopes. For example, a prototype bean into a singleton. This is known as the scoped bean injection problem.

Another way to solve the problem is method injection with the @Lookup annotation.

Here is a nice article on this issue of injecting prototype beans into a singleton instance with multiple solutions.

https://www.baeldung.com/spring-inject-prototype-bean-into-singleton

Maven: Non-resolvable parent POM

I solved that problem on me after a very long try, I created another file named "parent_pom.xml" in child module file directory at local and pasted contents of parent_pom.xml,which is located at remote, to newly created "parent_pom.xml". It worked for me and error message has gone.

How do I find which application is using up my port?

On the command prompt, do:

netstat -nb

Are "while(true)" loops so bad?

To me, the problem is readability.

A while statement with a true condition tells you nothing about the loop. It makes the job of understanding it much more difficult.

What would be easier to understand out of these two snippets?

do {
  // Imagine a nice chunk of code here
} while(true);

do {
  // Imagine a nice chunk of code here
} while(price < priceAllowedForDiscount);

Android: converting String to int

Use regular expression:

int i=Integer.parseInt("hello123".replaceAll("[\\D]",""));
int j=Integer.parseInt("123hello".replaceAll("[\\D]",""));
int k=Integer.parseInt("1h2el3lo".replaceAll("[\\D]",""));

output:

i=123;
j=123;
k=123;

android:layout_height 50% of the screen size

This kind of worked for me. Though FAB doesn't float independently, but now it isn't getting pushed down.

Observe the weights given inside the LinearLayout

<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:id="@+id/andsanddkasd">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/sharedResourcesRecyclerView"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="4"
                />

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fab"
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:layout_gravity="bottom|right"
                android:src="@android:drawable/ic_input_add"
                android:layout_weight="1"/>

        </LinearLayout>

Hope this helps :)

How to enable DataGridView sorting when user clicks on the column header?

  1. Create a class which contains all properties you need, and populate them in the constructor

    class Student
    {
        int _StudentId;
        public int StudentId {get;}
        string _Name;
        public string Name {get;}
        ...
    
        public Student(int studentId, string name ...)
        { _StudentId = studentId; _Name = name; ... }
    }
    
  2. Create an IComparer < Student > class, to be able to sort

    class StudentSorter : IComparer<Student>
    {
        public enum SField {StudentId, Name ... }
        SField _sField; SortOrder _sortOrder;
    
        public StudentSorder(SField field, SortOrder order)
        { _sField = field; _sortOrder = order;}
    
        public int Compare(Student x, Student y)
        {
            if (_SortOrder == SortOrder.Descending)
            {
                Student tmp = x;
                x = y;
                y = tmp;
            }
    
            if (x == null || y == null)
                return 0;
    
            int result = 0;
            switch (_sField)
            {
                case SField.StudentId:
                    result = x.StudentId.CompareTo(y.StudentId);
                    break;
                case SField.Name:
                    result = x.Name.CompareTo(y.Name);
                    break;
                    ...
            }
    
            return result;
        }
    }
    
  3. Within the form containing the datagrid add

    ListDictionary sortOrderLD = new ListDictionary(); //if less than 10 columns
    private SortOrder SetOrderDirection(string column)
    {
        if (sortOrderLD.Contains(column))
        {
            sortOrderLD[column] = (SortOrder)sortOrderLD[column] == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
        }
        else
        {
            sortOrderLD.Add(column, SortOrder.Ascending);
        }
    
        return (SortOrder)sortOrderLD[column];
    }
    
  4. Within datagridview_ColumnHeaderMouseClick event handler do something like this

    private void dgv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        StudentSorter sorter = null;
        string column = dGV.Columns[e.ColumnIndex].DataPropertyName; //Use column name if you set it
        if (column == "StudentId")
        {
            sorter = new StudentSorter(StudentSorter.SField.StudentId, SetOrderDirection(column));
        }
        else if (column == "Name")
        {
            sorter = new StudentSorter(StudentSorter.SField.Name, SetOrderDirection(column));
        }
    
        ...
    
        List<Student> lstFD = datagridview.DataSource as List<Student>;
        lstFD.Sort(sorter);
        datagridview.DataSource = lstFD;
        datagridview.Refresh();
    }
    

Hope this helps

Python Replace \\ with \

r'a\\nb'.replace('\\\\', '\\')

or

'a\nb'.replace('\n', '\\n')

Integrating the ZXing library directly into my Android application

I just wrote a method, which decodes generated bar-codes, Bitmap to String.

It does exactly what is being requested, just without the CaptureActivity...

Therefore, one can skip the android-integration library in the build.gradle :

dependencies {
    // https://mvnrepository.com/artifact/com.google.zxing
    compile('com.google.zxing:core:3.3.0')
    compile('com.google.zxing:android-core:3.3.0')
}

The method as following (which actually decodes generated bar-codes, within a jUnit test):

import android.graphics.Bitmap;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.Result;

protected String decode(Bitmap bitmap) {

    MultiFormatReader reader = new MultiFormatReader();
    String barcode = null;

    int[] intArray = new int[bitmap.getWidth() * bitmap.getHeight()];
    bitmap.getPixels(intArray, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
    LuminanceSource source = new RGBLuminanceSource(bitmap.getWidth(), bitmap.getHeight(), intArray);
    BinaryBitmap binary = new BinaryBitmap(new HybridBinarizer(source));

    try {

        Result result = reader.decode(binary);
        // BarcodeFormat format = result.getBarcodeFormat(); 
        // ResultPoint[] points = result.getResultPoints();
        // byte[] bytes = result.getRawBytes(); 
        barcode = result.getText();

    } catch (NotFoundException e) {
        e.printStackTrace();
    }
    return barcode;
}

Maven Could not resolve dependencies, artifacts could not be resolved

Have come across such issue. The root cause is the .m2 folder. You gotta make sure that whatever you're trying to access is present there in your .m2 folder (this is your local repo). If the stuff is there then you're good. This is usually present inside of users folder on your system (be it mac/linux or even windows)

Controlling Maven final name of jar artifact

@Maxim
try this...

pom.xml

 <groupId>org.opensource</groupId>
 <artifactId>base</artifactId>
 <version>1.0.0.SNAPSHOT</version>

  ..............
<properties>
    <my.version>4.0.8.8</my.version>
</properties>

<build>
    <finalName>my-base-project</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-install-plugin</artifactId>
            <version>2.3.1</version>
            <executions>
                <execution>
                    <goals>
                        <goal>install-file</goal>
                    </goals>
                    <phase>install</phase>
                    <configuration>
                        <file>${project.build.finalName}.${project.packaging}</file>
                        <generatePom>false</generatePom>
                        <pomFile>pom.xml</pomFile>
                        <version>${my.version}</version>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</plugins>
</build>

Commnad mvn clean install

Output

[INFO] --- maven-jar-plugin:2.3.1:jar (default-jar) @ base ---
[INFO] Building jar: D:\dev\project\base\target\my-base-project.jar
[INFO]
[INFO] --- maven-install-plugin:2.3.1:install (default-install) @ base ---
[INFO] Installing D:\dev\project\base\target\my-base-project.jar to H:\dev\.m2\repository\org\opensource\base\1.0.0.SNAPSHOT\base-1.0.0.SNAPSHOT.jar
[INFO] Installing D:\dev\project\base\pom.xml to H:\dev\.m2\repository\org\opensource\base\1.0.0.SNAPSHOT\base-1.0.0.SNAPSHOT.pom
[INFO]
[INFO] --- maven-install-plugin:2.3.1:install-file (default) @ base ---
[INFO] Installing D:\dev\project\base\my-base-project.jar to H:\dev\.m2\repository\org\opensource\base\4.0.8.8\base-4.0.8.8.jar
[INFO] Installing D:\dev\project\base\pom.xml to H:\dev\.m2\repository\org\opensource\base\4.0.8.8\base-4.0.8.8.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------


Reference

Maven 3 warnings about build.plugins.plugin.version

Add a <version> element after the <plugin> <artifactId> in your pom.xml file. Find the following text:

<plugin>
  <artifactId>maven-compiler-plugin</artifactId>

Add the version tag to it:

<plugin>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>2.3.2</version>

The warning should be resolved.

Regarding this:

'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing

Many people have mentioned why the issue is happening, but fail to suggest a fix. All I needed to do was to go into my POM file for my project, and add the <version> tag as shown above.

To discover the version number, one way is to look in Maven's output after it finishes running. Where you are missing version numbers, Maven will display its default version:

[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ entities ---

Take that version number (as in the 2.3.2 above) and add it to your POM, as shown.

How do MySQL indexes work?

Adding some visual representation to the list of answers. enter image description here

MySQL uses an extra layer of indirection: secondary index records point to primary index records, and the primary index itself holds the on-disk row locations. If a row offset changes, only the primary index needs to be updated.

Caveat: Disk data structure looks flat in the diagram but actually is a B+ tree.

Source: link

python: SyntaxError: EOL while scanning string literal

You can try this:

s = r'long\annoying\path'

MySQL: Convert INT to DATETIME

select from_unixtime(column,'%Y-%m-%d') from myTable; 

How do I get Maven to use the correct repositories?

I think what you have missed here is this:

https://maven.apache.org/settings.html#Servers

The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.

This is the prefered way of using custom repos. So probably what is happening is that the url of this repo is in settings.xml of the build server.

Once you get hold of the url and credentials, you can put them in your machine here: ~/.m2/settings.xml like this:

<settings ...> 

        .
        .
        .
        <servers>
            <server>
              <id>internal-repository-group</id>
              <username>YOUR-USERNAME-HERE</username>
              <password>YOUR-PASSWORD-HERE</password>
            </server>
        </servers>
</settings>

EDIT:

You then need to refer this repository into project POM. The id internal-repository-group can be used in every project. You can setup multiple repos and credentials setting using different IDs in settings xml.

The advantage of this approach is that project can be shared without worrying about the credentials and don't have to mention the credentials in every project.

Following is a sample pom of a project using "internal-repository-group"

<repositories>
    <repository>
        <id>internal-repository-group</id>
        <name>repo-name</name>
        <url>http://project.com/yourrepourl/</url>
        <layout>default</layout>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>never</updatePolicy>
        </releases>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>never</updatePolicy>
        </snapshots>
    </repository>
</repositories>

Using ZXing to create an Android barcode scanning app

You can use this quick start guide http://shyyko.wordpress.com/2013/07/30/zxing-with-android-quick-start/ with simple example project to build android app without IntentIntegrator.

How to build a query string for a URL in C#?

Here's my late entry. I didn't like any of the others for various reasons, so I wrote my own.

This version features:

  • Use of StringBuilder only. No ToArray() calls or other extension methods. It doesn't look as pretty as some of the other responses, but I consider this a core function so efficiency is more important than having "fluent", "one-liner" code which hide inefficiencies.

  • Handles multiple values per key. (Didn't need it myself but just to silence Mauricio ;)

    public string ToQueryString(NameValueCollection nvc)
    {
        StringBuilder sb = new StringBuilder("?");
    
        bool first = true;
    
        foreach (string key in nvc.AllKeys)
        {
            foreach (string value in nvc.GetValues(key))
            {
                if (!first)
                {
                    sb.Append("&");
                }
    
                sb.AppendFormat("{0}={1}", Uri.EscapeDataString(key), Uri.EscapeDataString(value));
    
                first = false;
            }
        }
    
        return sb.ToString();
    }
    

Example Usage

        var queryParams = new NameValueCollection()
        {
            { "x", "1" },
            { "y", "2" },
            { "foo", "bar" },
            { "foo", "baz" },
            { "special chars", "? = &" },
        };

        string url = "http://example.com/stuff" + ToQueryString(queryParams);

        Console.WriteLine(url);

Output

http://example.com/stuff?x=1&y=2&foo=bar&foo=baz&special%20chars=%3F%20%3D%20%26

Firefox "ssl_error_no_cypher_overlap" error

I had the same issue while renewing the certificate for our server at www.tpsynergy.com . After importing the new server certificate and restarting the tomcat, the error we were getting was ERR_SSL_VERSION_OR_CIPHER_MISMATCH. After lot of research, I used this link https://www.sslshopper.com/certificate-key-matcher.html to compare the csr (certificate signing request to the actual certificate). They both did not match. So I created a new csr and obtained a new certificate and installed the same. It worked.

So the full steps for the process are

  1. From the same server where the certificate will be installed, create CSR

keytool -keysize 2048 -genkey -alias tomcat -keyalg RSA -keystore tpsynergy.keystore (change the domain name as needed)

While creating this, it will ask for first name and last name. Do not give your name, but use the domain name. For example I gave it as www.tpsynergy.com

2.keytool -certreq -keyalg RSA -alias tomcat -file csr.csr -keystore tpsynergy.keystore

This will create a csr.csr file in the same folder. copy the contents of this to the godaddy site and create the new certificate.

  1. The downloaded certificate zip file will have three files gd_bundle-g2-g1.crt gdig2.crt youractualcert.crt

  2. You will need to download the root cert gdroot-g2.crt from godaddy repository.

  3. Copy all these files to the same directory from where you created the CSR file and where the keystore file is located.

  4. Now run the below commands one by one to import the certs into the keystore

    keytool -import -trustcacerts -alias root -file gd_bundle-g2-g1.crt -keystore tpsynergy.keystore

    keytool -import -trustcacerts -alias root2 -file gdroot-g2.crt -keystore tpsynergy.keystore

    keytool -import -trustcacerts -alias intermediate -file gdig2.crt -keystore tpsynergy.keystore

    keytool -import -trustcacerts -alias tomcat -file yourdomainfile.crt -keystore tpsynergy.keystore

  5. Ensure that server.xml file in conf folder has this entry

  6. Restart the tomcat

How do I sort arrays using vbscript?

When having large ("wide") arrays, instead of moving each element of a long row of data around, use a one-dimensional array with indexes of the array.

initialize ptr_arr with 0,1,2,3,..uBound(arr) then access data with

arr(field_index,ptr_arr(row_index))

instead of

arr(field_index,row_index)

and just swap the elements of ptr_arr instead of swapping the rows.

If you are processing the array row by row, eg displaying it as a , you can take the lookout out of the inner loop:

max_col=uBound(arr,1)
response.write "<table>"
for n = 0 to uBound(arr,2)
  response.write "<tr>"
  row=ptr_arr(n)
  for i=0 to max_col
    response.write "<td>"&arr(i,row)&"</td>"
  next
  response.write "</tr>
next
response.write "</table>" 

Scanning Java annotations at runtime

Is it too late to answer. I would say, its better to go by Libraries like ClassPathScanningCandidateComponentProvider or like Scannotations

But even after somebody wants to try some hands on it with classLoader, I have written some on my own to print the annotations from classes in a package:

public class ElementScanner {

public void scanElements(){
    try {
    //Get the package name from configuration file
    String packageName = readConfig();

    //Load the classLoader which loads this class.
    ClassLoader classLoader = getClass().getClassLoader();

    //Change the package structure to directory structure
    String packagePath  = packageName.replace('.', '/');
    URL urls = classLoader.getResource(packagePath);

    //Get all the class files in the specified URL Path.
    File folder = new File(urls.getPath());
    File[] classes = folder.listFiles();

    int size = classes.length;
    List<Class<?>> classList = new ArrayList<Class<?>>();

    for(int i=0;i<size;i++){
        int index = classes[i].getName().indexOf(".");
        String className = classes[i].getName().substring(0, index);
        String classNamePath = packageName+"."+className;
        Class<?> repoClass;
        repoClass = Class.forName(classNamePath);
        Annotation[] annotations = repoClass.getAnnotations();
        for(int j =0;j<annotations.length;j++){
            System.out.println("Annotation in class "+repoClass.getName()+ " is "+annotations[j].annotationType().getName());
        }
        classList.add(repoClass);
    }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

/**
 * Unmarshall the configuration file
 * @return
 */
public String readConfig(){
    try{
        URL url = getClass().getClassLoader().getResource("WEB-INF/config.xml");
        JAXBContext jContext = JAXBContext.newInstance(RepositoryConfig.class);
         Unmarshaller um =  jContext.createUnmarshaller();
         RepositoryConfig rc = (RepositoryConfig) um.unmarshal(new File(url.getFile()));
         return rc.getRepository().getPackageName();
        }catch(Exception e){
            e.printStackTrace();
        }
    return null;

}
}

And in config File, you put the package name and unmarshall it to a class .

Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

Use a library instead

We don't have to reinvent the wheel. Just use a library to save the time and headache.

js-base64

https://github.com/dankogai/js-base64 is good and I confirm it supports unicode very well.

Base64.encode('dankogai');  // ZGFua29nYWk=
Base64.encode('???');    // 5bCP6aO85by+
Base64.encodeURI('???'); // 5bCP6aO85by-

Base64.decode('ZGFua29nYWk=');  // dankogai
Base64.decode('5bCP6aO85by+');  // ???
// note .decodeURI() is unnecessary since it accepts both flavors
Base64.decode('5bCP6aO85by-');  // ???

How to enable CORS in apache tomcat

Just to add a bit of extra info over the right solution. Be aware that you'll need this class org.apache.catalina.filters.CorsFilter. So in order to have it, if your tomcat is not 7.0.41 or higher, download 'tomcat-catalina.7.0.41.jar' or higher ( you can do it from http://mvnrepository.com/artifact/org.apache.tomcat/tomcat-catalina ) and put it in the 'lib' folder inside Tomcat installation folders. I actually used 7.0.42 Hope it helps!

ASP.NET MVC - passing parameters to the controller

public ActionResult ViewNextItem(int? id) makes the id integer a nullable type, no need for string<->int conversions.

Converting serial port data to TCP/IP in a Linux environment

I think your question isn't quite clear. There are several answers here on how to catch the data coming into a Linux's serial port, but perhaps your problem is the other way around?

If you need to catch the data coming out of a Linux's serial port and send it to a server, there are several little hardware gizmos that can do this, starting with the simple serial print server such as this Lantronix gizmo.

No, I'm not affiliated with Lantronix in any way.

PHP function to get the subdomain of a URL

this is my solution, it works with the most common domains, you can fit the array of extensions as you need:

$SubDomain = explode('.', explode('|ext|', str_replace(array('.com', '.net', '.org'), '|ext|',$_SERVER['HTTP_HOST']))[0]);

How to obtain Telegram chat_id for a specific user?

I created a bot to get User or GroupChat id, just send the /my_id to telegram bot @get_id_bot.

It does not only work for user chat ID, but also for group chat ID.

To get group chat ID, first you have to add the bot to the group, then send /my_id in the group.

Here's the link to the bot.

Are there any free Xml Diff/Merge tools available?

I wrote and released a Windows application that specifically solves the problem of comparing and merging XML files.

Project: Merge can perform two and three way comparisons and merges of any XML file (where two of the files are considered to be independent revisions of a common base file). You can instruct it to identify elements within the input files by attribute values, or the content of child elements, among other things.

It is fully controllable via the command line and can also generate text reports containing the differences between the files.

Project: Merge merging three XML files

How can I get LINQ to return the object which has the max value for a given property?

try this:

var maxid = from i in items
            group i by i.clientid int g
            select new { id = g.Max(i=>i.ID }

How can I get screen resolution in java?

This call will give you the information you want.

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

Gradle, Android and the ANDROID_HOME SDK location

Your local.properties file might be missing. If so add a file named 'local.properties' inside /local.properties and provide the sdk location as following.

sdk.dir=C:\Users\\AppData\Local\Android\Sdk

What does the DOCKER_HOST variable do?

Ok, I think I got it.

The client is the docker command installed into OS X.

The host is the Boot2Docker VM.

The daemon is a background service running inside Boot2Docker.

This variable tells the client how to connect to the daemon.

When starting Boot2Docker, the terminal window that pops up already has DOCKER_HOST set, so that's why docker commands work. However, to run Docker commands in other terminal windows, you need to set this variable in those windows.

Failing to set it gives a message like this:

$ docker run hello-world
2014/08/11 11:41:42 Post http:///var/run/docker.sock/v1.13/containers/create: 
dial unix /var/run/docker.sock: no such file or directory

One way to fix that would be to simply do this:

$ export DOCKER_HOST=tcp://192.168.59.103:2375

But, as pointed out by others, it's better to do this:

$ $(boot2docker shellinit)
$ docker run hello-world
Hello from Docker. [...]

To spell out this possibly non-intuitive Bash command, running boot2docker shellinit returns a set of Bash commands that set environment variables:

export DOCKER_HOST=tcp://192.168.59.103:2376
export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
export DOCKER_TLS_VERIFY=1

Hence running $(boot2docker shellinit) generates those commands, and then runs them.

SQL Server Insert Example

To insert a single row of data:

INSERT INTO USERS
VALUES (1, 'Mike', 'Jones');

To do an insert on specific columns (as opposed to all of them) you must specify the columns you want to update.

INSERT INTO USERS (FIRST_NAME, LAST_NAME)
VALUES ('Stephen', 'Jiang');

To insert multiple rows of data in SQL Server 2008 or later:

INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe'),
(3, 'Linda', 'Mitchell'),
(4, 'Jillian', 'Carson'),
(5, 'Garrett', 'Vargas');

To insert multiple rows of data in earlier versions of SQL Server, use "UNION ALL" like so:

INSERT INTO USERS (FIRST_NAME, LAST_NAME)
SELECT 'James', 'Bond' UNION ALL
SELECT 'Miss', 'Moneypenny' UNION ALL
SELECT 'Raoul', 'Silva'

Note, the "INTO" keyword is optional in INSERT queries. Source and more advanced querying can be found here.

How to pass boolean parameter value in pipeline to downstream jobs?

like Jesse Jesse Glick and abguy said you can enumerate string into Boolean type:

Boolean.valueOf(string_variable)

or the opposite Boolean into string:

String.valueOf(boolean_variable)

in my case I had to to downstream Boolean parameter to another job. So for this you will need the use the class BooleanParameterValue :

build job: 'downstream_job_name', parameters:
[
[$class: 'BooleanParameterValue', name: 'parameter_name', value: false],
], wait: true

Python - How to cut a string in Python?

>>str = "http://www.domain.com/?s=some&two=20"
>>str.split("&")
>>["http://www.domain.com/?s=some", "two=20"]

How to add jQuery in JS file

var jQueryScript = document.createElement('script');  
jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
document.head.appendChild(jQueryScript);

How can I create persistent cookies in ASP.NET?

FWIW be very careful with storing something like a userid in a cookie unencrypted. Doing this makes your site very prone to cookie poisoning where users can easily impersonate another user. If you are considering something like this I would highly recommend using the forms authentication cookie directly.

bool persist = true;

var cookie = FormsAuthentication.GetAuthCookie(loginUser.ContactId, persist);

cookie.Expires = DateTime.Now.AddMonths(3);

var ticket = FormsAuthentication.Decrypt(cookie.Value);

var userData = "store any string values you want inside the ticket
                 extra than user id that will be encrypted"

var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name,
     ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData);

cookie.Value = FormsAuthentication.Encrypt(newTicket);

Response.Cookies.Add(cookie);

Then you can read this at any time from an ASP.NET page by doing

string userId = null;
if (this.Context.User.Identity.IsAuthenticated) 
{
    userId = this.Context.User.Identity.Name;
}

Windows Forms - Enter keypress activates submit button?

As previously stated, set your form's AcceptButton property to one of its buttons AND set the DialogResult property for that button to DialogResult.OK, in order for the caller to know if the dialog was accepted or dismissed.

iFrame src change event detection?

Here is the method which is used in Commerce SagePay and in Commerce Paypoint Drupal modules which basically compares document.location.href with the old value by first loading its own iframe, then external one.

So basically the idea is to load the blank page as a placeholder with its own JS code and hidden form. Then parent JS code will submit that hidden form where its #action points to the external iframe. Once the redirect/submit happens, the JS code which still running on that page can track your document.location.href value changes.

Here is example JS used in iframe:

;(function($) {
  Drupal.behaviors.commercePayPointIFrame = {
    attach: function (context, settings) {
      if (top.location != location) {
        $('html').hide();
        top.location.href = document.location.href;
      }
    }
  }
})(jQuery);

And here is JS used in parent page:

;(function($) {
  /**
   * Automatically submit the hidden form that points to the iframe.
   */
  Drupal.behaviors.commercePayPoint = {
    attach: function (context, settings) {
      $('div.payment-redirect-form form', context).submit();
      $('div.payment-redirect-form #edit-submit', context).hide();
      $('div.payment-redirect-form .checkout-help', context).hide();
    }
  }
})(jQuery);

Then in temporary blank landing page you need to include the form which will redirect to the external page.

How to replace space with comma using sed?

Inside vim, you want to type when in normal (command) mode:

:%s/ /,/g

On the terminal prompt, you can use sed to perform this on a file:

sed -i 's/\ /,/g' input_file

Note: the -i option to sed means "in-place edit", as in that it will modify the input file.

How to make a HTTP PUT request?


protected void UpdateButton_Click(object sender, EventArgs e)
        {
            var values = string.Format("Name={0}&Family={1}&Id={2}", NameToUpdateTextBox.Text, FamilyToUpdateTextBox.Text, IdToUpdateTextBox.Text);
            var bytes = Encoding.ASCII.GetBytes(values);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("http://localhost:51436/api/employees"));
            request.Method = "PUT";
            request.ContentType = "application/x-www-form-urlencoded";
            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }
            var response =  (HttpWebResponse) request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
                UpdateResponseLabel.Text = "Update completed";
            else
                UpdateResponseLabel.Text = "Error in update";
        }

how to specify new environment location for conda create

You can create it like this

conda create --prefix C:/tensorflow2 python=3.7

and you don't have to move to that folder to activate it.

# To activate this environment, use:
# > activate C:\tensorflow2

As you see I do it like this.

D:\Development_Avector\PycharmProjects\TensorFlow>activate C:\tensorflow2

(C:\tensorflow2) D:\Development_Avector\PycharmProjects\TensorFlow>

(C:\tensorflow2) D:\Development_Avector\PycharmProjects\TensorFlow>conda --version
conda 4.5.13

possible EventEmitter memory leak detected

The accepted answer provides the semantics on how to increase the limit, but as @voltrevo pointed out that warning is there for a reason and your code probably has a bug.

Consider the following buggy code:

//Assume Logger is a module that emits errors
var Logger = require('./Logger.js');

for (var i = 0; i < 11; i++) {
    //BUG: This will cause the warning
    //As the event listener is added in a loop
    Logger.on('error', function (err) {
        console.log('error writing log: ' + err)
    });

    Logger.writeLog('Hello');
}

Now observe the correct way of adding the listener:

//Good: event listener is not in a loop
Logger.on('error', function (err) {
    console.log('error writing log: ' + err)
});

for (var i = 0; i < 11; i++) {
    Logger.writeLog('Hello');
}

Search for similar issues in your code before changing the maxListeners (which is explained in other answers)

Creating and throwing new exception

To call a specific exception such as FileNotFoundException use this format

if (-not (Test-Path $file)) 
{
    throw [System.IO.FileNotFoundException] "$file not found."
}

To throw a general exception use the throw command followed by a string.

throw "Error trying to do a task"

When used inside a catch, you can provide additional information about what triggered the error

WCF Service, the type provided as the service attribute values…could not be found

In my case I did a "Convert to application" to the wrong folder on iis. My application was set in a subfolder of where it should have been.

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

All combinations of a list of lists

from itertools import product 
list_vals = [['Brand Acronym:CBIQ', 'Brand Acronym :KMEFIC'],['Brand Country:DXB','Brand Country:BH']]
list(product(*list_vals))

Output:

[('Brand Acronym:CBIQ', 'Brand Country :DXB'),
('Brand Acronym:CBIQ', 'Brand Country:BH'),
('Brand Acronym :KMEFIC', 'Brand Country :DXB'),
('Brand Acronym :KMEFIC', 'Brand Country:BH')]

Execute function after Ajax call is complete

Add .done() to your function

var id;
var vname;
function ajaxCall(){
for(var q = 1; q<=10; q++){
 $.ajax({                                            
         url: 'api.php',                        
         data: 'id1='+q+'',                                                         
         dataType: 'json',
         async:false,                    
         success: function(data)          
         {   
            id = data[0];              
            vname = data[1];
         }
      }).done(function(){
           printWithAjax(); 
      });



 }//end of the for statement
}//end of ajax call function

Equals(=) vs. LIKE

To address the original question regarding performance, it comes down to index utilization. When a simple table scan occurs, "LIKE" and "=" are identical. When indexes are involved, it depends on how the LIKE clause is formed. More specifically, what is the location of the wildcard(s)?


Consider the following:

CREATE TABLE test(
    txt_col  varchar(10) NOT NULL
)
go

insert test (txt_col)
select CONVERT(varchar(10), row_number() over (order by (select 1))) r
  from master..spt_values a, master..spt_values b
go

CREATE INDEX IX_test_data 
    ON test (txt_col);
go 

--Turn on Show Execution Plan
set statistics io on

--A LIKE Clause with a wildcard at the beginning
DBCC DROPCLEANBUFFERS
SELECT txt_Col from test where txt_col like '%10000'
--Results in
--Table 'test'. Scan count 3, logical reads 15404, physical reads 2, read-ahead reads 15416, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
--Index SCAN is 85% of Query Cost

--A LIKE Clause with a wildcard in the middle
DBCC DROPCLEANBUFFERS
SELECT txt_Col from test where txt_col like '1%99'
--Results in
--Table 'test'. Scan count 1, logical reads 3023, physical reads 3, read-ahead reads 3018, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
--Index Seek is 100% of Query Cost for test data, but it may result in a Table Scan depending on table size/structure

--A LIKE Clause with no wildcards
DBCC DROPCLEANBUFFERS
SELECT txt_Col from test where txt_col like '10000'
--Results in
--Table 'test'. Scan count 1, logical reads 3, physical reads 2, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
--Index Seek is 100% of Query Cost
GO

--an "=" clause = does Index Seek same as above
DBCC DROPCLEANBUFFERS
SELECT txt_Col from test where txt_col = '10000'
--Results in
--Table 'test'. Scan count 1, logical reads 3, physical reads 2, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
--Index Seek is 100% of Query Cost
GO


DROP TABLE test

There may be also negligible difference in the creation of the query plan when using "=" vs "LIKE".

How to run an .ipynb Jupyter Notebook from terminal?

You can export all your code from .ipynb and save it as a .py script. Then you can run the script in your terminal.

code export sample

Hope it helps.

Disable Input fields in reactive form

I solved it by wrapping my input object with its label in a field set: The fieldset should have the disabled property binded to the boolean

 <fieldset [disabled]="isAnonymous">
    <label class="control-label" for="firstName">FirstName</label>
    <input class="form-control" id="firstName" type="text" formControlName="firstName" />
 </fieldset>

How to make bootstrap 3 fluid layout without horizontal scrollbar

Apply to the body seems to get rid of the horizontal scrollbar

overflow-x: hidden;

Select Rows with id having even number

SELECT * FROM ( SELECT *, Row_Number() 
OVER(ORDER BY country_gid) AS sdfg  FROM eka_mst_tcountry ) t 
WHERE t.country_gid % 2 = 0 

Search for exact match of string in excel row using VBA Macro

This is not another code as you have already helped yourself; but for you to take a look at the performance when using Excel functions in VBA.

PS: **On a latter note, if you wish to do pattern matching then you may consider ScriptingObject **Regex.

Aborting a shell script if any command returns a non-zero value

If you have cleanup you need to do on exit, you can also use 'trap' with the pseudo-signal ERR. This works the same way as trapping INT or any other signal; bash throws ERR if any command exits with a nonzero value:

# Create the trap with   
#    trap COMMAND SIGNAME [SIGNAME2 SIGNAME3...]
trap "rm -f /tmp/$MYTMPFILE; exit 1" ERR INT TERM
command1
command2
command3
# Partially turn off the trap.
trap - ERR
# Now a control-C will still cause cleanup, but
# a nonzero exit code won't:
ps aux | grep blahblahblah

Or, especially if you're using "set -e", you could trap EXIT; your trap will then be executed when the script exits for any reason, including a normal end, interrupts, an exit caused by the -e option, etc.

'mat-form-field' is not a known element - Angular 5 & Material2

When using the 'mat-form-field' MatInputModule needs to be imported also

import { 
    MatToolbarModule, 
    MatButtonModule,
    MatSidenavModule,
    MatIconModule,
    MatListModule ,
    MatStepperModule,
    MatInputModule
} from '@angular/material';

Swift: Convert enum value to String?

Not sure in which Swift version this feature was added, but right now (Swift 2.1) you only need this code:

enum Audience : String {
    case public
    case friends
    case private
}

let audience = Audience.public.rawValue // "public"

When strings are used for raw values, the implicit value for each case is the text of that case’s name.

[...]

enum CompassPoint : String {
    case north, south, east, west
}

In the example above, CompassPoint.south has an implicit raw value of "south", and so on.

You access the raw value of an enumeration case with its rawValue property:

let sunsetDirection = CompassPoint.west.rawValue
// sunsetDirection is "west"

Source.

Difference between "process.stdout.write" and "console.log" in node.js?

I've just noticed something while researching this after getting help with https.request for post method. Thought I share some input to help understand.

process.stdout.write doesn't add a new line while console.log does, like others had mentioned. But there's also this which is easier to explain with examples.

var req = https.request(options, (res) => {
    res.on('data', (d) => {
        process.stdout.write(d);
        console.log(d)
    });
});

process.stdout.write(d); will print the data properly without a new line. However console.log(d) will print a new line but the data won't show correctly, giving this <Buffer 12 34 56... for example.

To make console.log(d) show the information correctly, I would have to do this.

var req = https.request(options, (res) => {
    var dataQueue = "";    
    res.on("data", function (d) {
        dataQueue += d;
    });
    res.on("end", function () {
        console.log(dataQueue);
    });
});

So basically:

  • process.stdout.write continuously prints the information as the data being retrieved and doesn't add a new line.

  • console.log prints the information what was obtained at the point of retrieval and adds a new line.

That's the best way I can explain it.

Mock HttpContext.Current in Test Init Method

I know this is an older subject, however Mocking a MVC application for unit tests is something we do on very regular basis.

I just wanted to add my experiences Mocking a MVC 3 application using Moq 4 after upgrading to Visual Studio 2013. None of the unit tests were working in debug mode and the HttpContext was showing "could not evaluate expression" when trying to peek at the variables.

Turns out visual studio 2013 has issues evaluating some objects. To get debugging mocked web applications working again, I had to check the "Use Managed Compatibility Mode" in Tools=>Options=>Debugging=>General settings.

I generally do something like this:

public static class FakeHttpContext
{
    public static void SetFakeContext(this Controller controller)
    {

        var httpContext = MakeFakeContext();
        ControllerContext context =
        new ControllerContext(
        new RequestContext(httpContext,
        new RouteData()), controller);
        controller.ControllerContext = context;
    }


    private static HttpContextBase MakeFakeContext()
    {
        var context = new Mock<HttpContextBase>();
        var request = new Mock<HttpRequestBase>();
        var response = new Mock<HttpResponseBase>();
        var session = new Mock<HttpSessionStateBase>();
        var server = new Mock<HttpServerUtilityBase>();
        var user = new Mock<IPrincipal>();
        var identity = new Mock<IIdentity>();

        context.Setup(c=> c.Request).Returns(request.Object);
        context.Setup(c=> c.Response).Returns(response.Object);
        context.Setup(c=> c.Session).Returns(session.Object);
        context.Setup(c=> c.Server).Returns(server.Object);
        context.Setup(c=> c.User).Returns(user.Object);
        user.Setup(c=> c.Identity).Returns(identity.Object);
        identity.Setup(i => i.IsAuthenticated).Returns(true);
        identity.Setup(i => i.Name).Returns("admin");

        return context.Object;
    }


}

And initiating the context like this

FakeHttpContext.SetFakeContext(moController);

And calling the Method in the controller straight forward

long lReportStatusID = -1;
var result = moController.CancelReport(lReportStatusID);

Find all storage devices attached to a Linux machine

Modern linux systems will normally only have entries in /dev for devices that exist, so going through hda* and sda* as you suggest would work fairly well.

Otherwise, there may be something in /proc you can use. From a quick look in there, I'd have said /proc/partitions looks like it could do what you need.

How do I set proxy for chrome in python webdriver?

This worked for me like a charm:

proxy = "localhost:8080"
desired_capabilities = webdriver.DesiredCapabilities.CHROME.copy()
desired_capabilities['proxy'] = {
    "httpProxy": proxy,
    "ftpProxy": proxy,
    "sslProxy": proxy,
    "noProxy": None,
    "proxyType": "MANUAL",
    "class": "org.openqa.selenium.Proxy",
    "autodetect": False
}

Read Numeric Data from a Text File in C++

Repeat >> reads in loop.

#include <iostream>
#include <fstream>
int main(int argc, char * argv[])
{
    std::fstream myfile("D:\\data.txt", std::ios_base::in);

    float a;
    while (myfile >> a)
    {
        printf("%f ", a);
    }

    getchar();

    return 0;
}

Result:

45.779999 67.900002 87.000000 34.889999 346.000000 0.980000

If you know exactly, how many elements there are in a file, you can chain >> operator:

int main(int argc, char * argv[])
{
    std::fstream myfile("D:\\data.txt", std::ios_base::in);

    float a, b, c, d, e, f;

    myfile >> a >> b >> c >> d >> e >> f;

    printf("%f\t%f\t%f\t%f\t%f\t%f\n", a, b, c, d, e, f);

    getchar();

    return 0;
}

Edit: In response to your comments in main question.

You have two options.

  • You can run previous code in a loop (or two loops) and throw away a defined number of values - for example, if you need the value at point (97, 60), you have to skip 5996 (= 60 * 100 + 96) values and use the last one. This will work if you're interested only in specified value.
  • You can load the data into an array - as Jerry Coffin sugested. He already gave you quite nice class, which will solve the problem. Alternatively, you can use simple array to store the data.

Edit: How to skip values in file

To choose the 1234th value, use the following code:

int skipped = 1233;
for (int i = 0; i < skipped; i++)
{
    float tmp;
    myfile >> tmp;
}
myfile >> value;

Form Validation With Bootstrap (jQuery)

enter image description here

Here is a very simple and lightweight plugin for validation with Boostrap, you can use it if you like: https://github.com/wpic/bootstrap.validator.js

How to solve munmap_chunk(): invalid pointer error in C++

The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[] with an index read from stream. Try vector::at() instead of vector::operator[]. This won't solve your problem, but will show which assignment to the vector causes error.

How to remove all duplicate items from a list

This should be faster and will preserve the original order:

seen = {}
new_list = [seen.setdefault(x, x) for x in my_list if x not in seen]

If you don't care about order, you can just:

new_list = list(set(my_list))

How to sort an array based on the length of each element?

Based on Salman's answer, I've written a small function to encapsulate it:

function sortArrayByLength(arr, ascYN) {
        arr.sort(function (a, b) {           // sort array by length of text
            if (ascYN) return a.length - b.length;              // ASC -> a - b
            else return b.length - a.length;                    // DESC -> b - a
        });
    }

then just call it with

sortArrayByLength( myArray, true );

Note that unfortunately, functions can/should not be added to the Array prototype, as explained on this page.

Also, it modified the array passed as a parameter and doesn't return anything. This would force the duplication of the array and wouldn't be great for large arrays. If someone has a better idea, please do comment!

How to asynchronously call a method in Java

You may wish to also consider the class java.util.concurrent.FutureTask.

If you are using Java 5 or later, FutureTask is a turnkey implementation of "A cancellable asynchronous computation."

There are even richer asynchronous execution scheduling behaviors available in the java.util.concurrent package (for example, ScheduledExecutorService), but FutureTask may have all the functionality you require.

I would even go so far as to say that it is no longer advisable to use the first code pattern you gave as an example ever since FutureTask became available. (Assuming you are on Java 5 or later.)

How do I perform an IF...THEN in an SQL SELECT?

SELECT  
(CASE 
     WHEN (Obsolete = 'N' OR InStock = 'Y') THEN 'YES'
                                            ELSE 'NO' 
 END) as Salable
, * 
FROM Product

.gitignore is ignored by Git

I've created .gitignore using echo "..." > .gitignore in PowerShell in Windows, because it does not let me to create it in Windows Explorer.

The problem in my case was the encoding of the created file, and the problem was solved after I changed it to ANSI.

What is the iOS 6 user agent string?

Some more:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25

R - argument is of length zero in if statement

I spent an entire day bashing my head against this, the solution turned out to be simple..

R isn't zero-index.

Every programming language that I've used before has it's data start at 0, R starts at 1. The result is an off-by-one error but in the opposite direction of the usual. going out of bounds on a data structure returns null and comparing null in an if statement gives the argument is of length zero error. The confusion started because the dataset doesn't contain any null, and starting at position [0] like any other pgramming language turned out to be out of bounds.

Perhaps starting at 1 makes more sense to people with no programming experience (the target market for R?) but for a programmer is a real head scratcher if you're unaware of this.

Excel 2007: How to display mm:ss format not as a DateTime (e.g. 73:07)?

One convenient trick to entering elapsed times into Excel is to have two zeros and a colon before the number of minutes, details follow. For copy and paste operations into Excel without have to worry about formatting at all one can use the format 00:XX:XX where XX are two digits totaling < 60. In that case, Excel will echo 0:XX:XX in the cell contents displayed and store the data as 12:XX:XX AM. If one pastes data in a 00:XXX:XX format into Excel, or 00:XX:XX where either XX > 59 this will be converted into a fraction of a day.

For example, 00:121:12 becomes 0.0841666666666667, which if multiplied by the number of seconds in a day, 86,400, becomes 7272 s. Next, 00:21:12 would by default show 0:21:12 stored as 12:21:12 AM. Finally, 00:21:60 becomes 0.0152777777777778, also a fraction of a day.

This suggestion is made merely to avoid having to worry about specific formatting in Excel, and letting the program worry about it. Note, for Excel data internally formatted as 12:XX:XX AM one can only use certain Excel commands, for example, one can take an average. However, subtraction will only work when the result is a positive number. Such that converting times into seconds, fractions of a day, or other real number is suggested for access to more complete arithmetic operation coverage.

For example, if one has a column of mixed time formats, or times that are negative and will not display, if one changes the number formatting to General, all the times will be converted to fractions of a day.

How to convert characters to HTML entities using plain JavaScript

Demo on JSFiddle

here's a tiny stand alone method that:

  • attempts to consolidate the answers on this page, without using a library
  • works in older browsers
  • supports surrogate pairs (like emojis)
  • applies character overrides (what's that? not sure exactly)

i don't know too much about unicode, but it seems to be working well.

// escape a string for display in html
// see also: 
// polyfill for String.prototype.codePointAt
//   https://raw.githubusercontent.com/mathiasbynens/String.prototype.codePointAt/master/codepointat.js
// how to convert characters to html entities
//     http://stackoverflow.com/a/1354491/347508
// html overrides from 
//   https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides / http://stackoverflow.com/questions/1354064/how-to-convert-characters-to-html-entities-using-plain-javascript/23831239#comment36668052_1354098

var _escape_overrides = { 0x00:'\uFFFD',0x80:'\u20AC',0x82:'\u201A',0x83:'\u0192',0x84:'\u201E',0x85:'\u2026',0x86:'\u2020',0x87:'\u2021',0x88:'\u02C6',0x89:'\u2030',0x8A:'\u0160',0x8B:'\u2039',0x8C:'\u0152',0x8E:'\u017D',0x91:'\u2018',0x92:'\u2019',0x93:'\u201C',0x94:'\u201D',0x95:'\u2022',0x96:'\u2013',0x97:'\u2014',0x98:'\u02DC',0x99:'\u2122',0x9A:'\u0161',0x9B:'\u203A',0x9C:'\u0153',0x9E:'\u017E',0x9F:'\u0178' }; 

function escapeHtml(str){
    return str.replace(/([\u0000-\uD799]|[\uD800-\uDBFF][\uDC00-\uFFFF])/g, function(c) {
        var c1 = c.charCodeAt(0);
        // ascii character, use override or escape
        if( c1 <= 0xFF ) return (c1=_escape_overrides[c1])?c1:escape(c).replace(/%(..)/g,"&#x$1;");
        // utf8/16 character
        else if( c.length == 1 ) return "&#" + c1 + ";"; 
        // surrogate pair
        else if( c.length == 2 && c1 >= 0xD800 && c1 <= 0xDBFF ) return "&#" + ((c1-0xD800)*0x400 + c.charCodeAt(1) - 0xDC00 + 0x10000) + ";"
        // no clue .. 
        else return "";
    });
}

ORA-01843 not a valid month- Comparing Dates

If you are using command line tools, then you can also set it in the shell.

On linux, with a sh type shell, you can do for example:

export NLS_TIMESTAMP_FORMAT='DD/MON/RR HH24:MI:SSXFF'

Then you can use the command line tools and it will use the specified format:

/path/to/dbhome_1/bin/sqlldr user/pass@host:port/service control=table.ctl direct=true

What is the difference between the kernel space and the user space?

The really simplified answer is that the kernel runs in kernel space, and normal programs run in user space. User space is basically a form of sand-boxing -- it restricts user programs so they can't mess with memory (and other resources) owned by other programs or by the OS kernel. This limits (but usually doesn't entirely eliminate) their ability to do bad things like crashing the machine.

The kernel is the core of the operating system. It normally has full access to all memory and machine hardware (and everything else on the machine). To keep the machine as stable as possible, you normally want only the most trusted, well-tested code to run in kernel mode/kernel space.

The stack is just another part of memory, so naturally it's segregated right along with the rest of memory.

Reading an Excel file in PHP

Try this...

I have used following code to read "xls and xlsx"

    <?php
    include 'excel_reader.php';       // include the class
    $excel = new PhpExcelReader;      // creates object instance of the class
    $excel->read('excel_file.xls');   // reads and stores the excel file data

    // Test to see the excel data stored in $sheets property
    echo '<pre>';
    var_export($excel->sheets);

    echo '</pre>';

    or 

 echo '<pre>';
    print_r($excel->sheets);

    echo '</pre>';

Reference:http://coursesweb.net/php-mysql/read-excel-file-data-php_pc

avrdude: stk500v2_ReceiveMessage(): timeout

My aurdino mega 2560 returned same error. It seems the problem exists in unofficial clones. The issue solved by pressing reset button just before uploading starts, as advertised in following video.

https://www.youtube.com/watch?v=tAzjO4v7oF4&list=LLDn5ewJDzz53IiwWmZTgQnQ&index=1

How to remove unused imports from Eclipse

Remove all unused import in eclipse:

Right click on the desired package then Source->Organize Imports. Or You can direct use the shortcut by pressing Ctrl+Shift+O

Work perfectly.

Open multiple Projects/Folders in Visual Studio Code

you can create a workspace and put folders in that : File > save workspace as and drag and drop your folders in saved workspace

Convert a JSON Object to Buffer and Buffer to JSON Object back

You need to stringify the json, not calling toString

var buf = Buffer.from(JSON.stringify(obj));

And for converting string to json obj :

var temp = JSON.parse(buf.toString());

Angular 2 - Setting selected value on dropdown list

Actually if You use ReactiveForms i found this way much easier to acomplish:

If the form is defined like this:

public formName = new FormGroup({

    fieldName: new FormControl("test") //where "test is field default value"

});

Then thats the way You can change its value:

this.formName.controls.fieldName.setValue("test 2"); //setting field value to "test 2"

How to maintain aspect ratio using HTML IMG tag

<img src="Runtime Path to photo"
     style="border: 1px solid #000; max-width:64px; max-height:64px;">

React Error: Target Container is not a DOM Element

webpack solution

If you got this error while working in React with webpack and HMR.

You need to create template index.html and save it in src folder:

<html>
    <body>
       <div id="root"></root>
    </body>
</html>

Now when we have template with id="root" we need to tell webpack to generate index.html which will mirror our index.html file.

To do that:

plugins: [
    new HtmlWebpackPlugin({
        title: "Application name",
        template: './src/index.html'
    })
],

template property will tell webpack how to build index.html file.

How to remove leading whitespace from each line in a file

Here you go:

user@host:~$ sed 's/^[\t ]*//g' < file-in.txt

Or:

user@host:~$ sed 's/^[\t ]*//g' < file-in.txt > file-out.txt

Named placeholders in string formatting

For very simple cases you can simply use a hardcoded String replace, no need for a library there:

    String url = "There's an incorrect value '%(value)' in column # %(column)";
    url = url.replace("%(value)", x); // 1
    url = url.replace("%(column)", y); // 2

WARNING: I just wanted to show the simplest code possible. Of course DO NOT use this for serious production code where security matters, as stated in the comments: escaping, error handling and security are an issue here. But in the worst case you now know why using a 'good' lib is required :-)

Any way to generate ant build.xml file automatically from Eclipse?

  • Select File > Export from main menu (or right click on the project name and select Export > Export…).
  • In the Export dialog, select General > Ant Buildfiles as follows: enter image description here

  • Click Next. In the Generate Ant Buildfilesscreen:

    • Check the project in list.
    • Uncheck the option "Create target to compile project using Eclipse compiler" - because we want to create a build file which is independent of Eclipse.
    • Leave the Name for Ant buildfile as default: build.xml

enter image description here

  • Click Finish, Eclipse will generate the build.xml file under project’s directory as follows:
    enter image description here
  • Double click on the build.xml file to open its content in Ant editor: enter image description here

source

How do I vertically align something inside a span tag?

this works for me (Keltex said the same)

.foo {
height: 50px;
...
}
.foo span{
vertical-align: middle; 
}

<span class="foo"> <span>middle!</span></span>

How do you fix a bad merge, and replay your good commits onto a fixed merge?

Just to add that to Charles Bailey's solution, I just used a git rebase -i to remove unwanted files from an earlier commit and it worked like a charm. The steps:

# Pick your commit with 'e'
$ git rebase -i

# Perform as many removes as necessary
$ git rm project/code/file.txt

# amend the commit
$ git commit --amend

# continue with rebase
$ git rebase --continue

Arduino COM port doesn't work

Did you install the drivers? See the Arduino installation instructions under #4. I don't know that machine but I doubt it doesn't have any COM ports.

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

Determine installed PowerShell version

I tried this on version 7.1.0 and it worked:

$PSVersionTable | Select-Object PSVersion

Output

PSVersion
---------
7.1.0

It doesn't work on version 5.1 though, so rather go for this on versions below 7:

$PSVersionTable.PSVersion

Output

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      18362  1171

Parse large JSON file in Nodejs

I had similar requirement, i need to read a large json file in node js and process data in chunks and call a api and save in mongodb. inputFile.json is like:

{
 "customers":[
       { /*customer data*/},
       { /*customer data*/},
       { /*customer data*/}....
      ]
}

Now i used JsonStream and EventStream to achieve this synchronously.

var JSONStream = require("JSONStream");
var es = require("event-stream");

fileStream = fs.createReadStream(filePath, { encoding: "utf8" });
fileStream.pipe(JSONStream.parse("customers.*")).pipe(
  es.through(function(data) {
    console.log("printing one customer object read from file ::");
    console.log(data);
    this.pause();
    processOneCustomer(data, this);
    return data;
  }),
  function end() {
    console.log("stream reading ended");
    this.emit("end");
  }
);

function processOneCustomer(data, es) {
  DataModel.save(function(err, dataModel) {
    es.resume();
  });
}

What to do with branch after merge

If you DELETE the branch after merging it, just be aware that all hyperlinks, URLs, and references of your DELETED branch will be BROKEN.

How can I sharpen an image in OpenCV?

Try with this:

cv::bilateralFilter(img, 9, 75, 75);

You might find more information here.

How can I format my grep output to show line numbers at the end of the line, and also the hit count?

or in perl (for completeness...):

perl -npe 'chomp; /null/ and print "$_ - Line number : $.\n" and $i++;$_="";END{print "Total null count : $i\n"}'

Handling exceptions from Java ExecutorService tasks

This works

  • It is derived from SingleThreadExecutor, but you can adapt it easily
  • Java 8 lamdas code, but easy to fix

It will create a Executor with a single thread, that can get a lot of tasks; and will wait for the current one to end execution to begin with the next

In case of uncaugth error or exception the uncaughtExceptionHandler will catch it

public final class SingleThreadExecutorWithExceptions {

    public static ExecutorService newSingleThreadExecutorWithExceptions(final Thread.UncaughtExceptionHandler uncaughtExceptionHandler) {

        ThreadFactory factory = (Runnable runnable)  -> {
            final Thread newThread = new Thread(runnable, "SingleThreadExecutorWithExceptions");
            newThread.setUncaughtExceptionHandler( (final Thread caugthThread,final Throwable throwable) -> {
                uncaughtExceptionHandler.uncaughtException(caugthThread, throwable);
            });
            return newThread;
        };
        return new FinalizableDelegatedExecutorService
                (new ThreadPoolExecutor(1, 1,
                        0L, TimeUnit.MILLISECONDS,
                        new LinkedBlockingQueue(),
                        factory){


                    protected void afterExecute(Runnable runnable, Throwable throwable) {
                        super.afterExecute(runnable, throwable);
                        if (throwable == null && runnable instanceof Future) {
                            try {
                                Future future = (Future) runnable;
                                if (future.isDone()) {
                                    future.get();
                                }
                            } catch (CancellationException ce) {
                                throwable = ce;
                            } catch (ExecutionException ee) {
                                throwable = ee.getCause();
                            } catch (InterruptedException ie) {
                                Thread.currentThread().interrupt(); // ignore/reset
                            }
                        }
                        if (throwable != null) {
                            uncaughtExceptionHandler.uncaughtException(Thread.currentThread(),throwable);
                        }
                    }
                });
    }



    private static class FinalizableDelegatedExecutorService
            extends DelegatedExecutorService {
        FinalizableDelegatedExecutorService(ExecutorService executor) {
            super(executor);
        }
        protected void finalize() {
            super.shutdown();
        }
    }

    /**
     * A wrapper class that exposes only the ExecutorService methods
     * of an ExecutorService implementation.
     */
    private static class DelegatedExecutorService extends AbstractExecutorService {
        private final ExecutorService e;
        DelegatedExecutorService(ExecutorService executor) { e = executor; }
        public void execute(Runnable command) { e.execute(command); }
        public void shutdown() { e.shutdown(); }
        public List shutdownNow() { return e.shutdownNow(); }
        public boolean isShutdown() { return e.isShutdown(); }
        public boolean isTerminated() { return e.isTerminated(); }
        public boolean awaitTermination(long timeout, TimeUnit unit)
                throws InterruptedException {
            return e.awaitTermination(timeout, unit);
        }
        public Future submit(Runnable task) {
            return e.submit(task);
        }
        public  Future submit(Callable task) {
            return e.submit(task);
        }
        public  Future submit(Runnable task, T result) {
            return e.submit(task, result);
        }
        public  List> invokeAll(Collection> tasks)
                throws InterruptedException {
            return e.invokeAll(tasks);
        }
        public  List> invokeAll(Collection> tasks,
                                             long timeout, TimeUnit unit)
                throws InterruptedException {
            return e.invokeAll(tasks, timeout, unit);
        }
        public  T invokeAny(Collection> tasks)
                throws InterruptedException, ExecutionException {
            return e.invokeAny(tasks);
        }
        public  T invokeAny(Collection> tasks,
                               long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return e.invokeAny(tasks, timeout, unit);
        }
    }



    private SingleThreadExecutorWithExceptions() {}
}

Two color borders

Not possible, but you should check to see if border-style values like inset, outset or some other, accomplished the effect you want.. (i doubt it though..)

CSS3 has the border-image properties, but i do not know about support from browsers yet (more info at http://www.css3.info/preview/border-image/)..

Live search through table rows

Here is something you can do with Ajax, PHP and JQuery. Hope this helps or gives you a start. Check the mysql query in php. It matches the pattern starting from first.

See live demo and source code here.

http://purpledesign.in/blog/to-create-a-live-search-like-google/

Create a search box, may be an input field like this.

<input type="text" id="search" autocomplete="off">

Now we need listen to whatever the user types on the text area. For this we will use the jquery live() and the keyup event. On every keyup we have a jquery function “search” that will run a php script.

Suppose we have the html like this. We have an input field and a list to display the results.

 <div class="icon"></div>
 <input type="text" id="search" autocomplete="off">
 <ul id="results"></ul>

We have a Jquery script that will listen to the keyup event on the input field and if it is not empty it will invoke the search() function. The search() function will run the php script and display the result on the same page using AJAX.

Here is the JQuery.

$(document).ready(function() {  

    // Icon Click Focus
    $('div.icon').click(function(){
        $('input#search').focus();
    });

    //Listen for the event
    $("input#search").live("keyup", function(e) {
    // Set Timeout
    clearTimeout($.data(this, 'timer'));

    // Set Search String
    var search_string = $(this).val();

    // Do Search
    if (search_string == '') {
        $("ul#results").fadeOut();
        $('h4#results-text').fadeOut();
    }else{
        $("ul#results").fadeIn();
        $('h4#results-text').fadeIn();
        $(this).data('timer', setTimeout(search, 100));
    };
});


// Live Search
// On Search Submit and Get Results
function search() {
    var query_value = $('input#search').val();
    $('b#search-string').html(query_value);
    if(query_value !== ''){
        $.ajax({
            type: "POST",
            url: "search_st.php",
            data: { query: query_value },
            cache: false,
            success: function(html){
                $("ul#results").html(html);

            }
        });
    }return false;    
}

}); In the php, shoot a query to the mysql database. The php will return the results that will be put into the html using AJAX. Here the result is put into a html list.

Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type’ and ‘desc’.

//search.php
// Credentials
$dbhost = "localhost";
$dbname = "live";
$dbuser = "root";
$dbpass = "";

//  Connection
global $tutorial_db;

$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");

//  Check Connection
if ($tutorial_db->connect_errno) {
    printf("Connect failed: %s\n", $tutorial_db->connect_error);
    exit();

$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';

$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);

// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
    // Build Query
    $query = "SELECT *
        FROM animals
        WHERE type REGEXP '^".$search_string."'
        UNION ALL SELECT *
        FROM birf
        WHERE type REGEXP '^".$search_string."'"
        ;

$result = $tutorial_db->query($query);
    while($results = $result->fetch_array()) {
        $result_array[] = $results;
    }

    // Check If We Have Results
    if (isset($result_array)) {
        foreach ($result_array as $result) {

            // Format Output Strings And Hightlight Matches
            $display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']);
            $display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']);
        $display_url = 'https://www.google.com/search?q='.urlencode($result['type']).'&ie=utf-8&oe=utf-8';

            // Insert Name
            $output = str_replace('nameString', $display_name, $html);

            // Insert Description
            $output = str_replace('functionString', $display_function, $output);

            // Insert URL
            $output = str_replace('urlString', $display_url, $output);



            // Output
            echo($output);
        }
    }else{

        // Format No Results Output
        $output = str_replace('urlString', 'javascript:void(0);', $html);
        $output = str_replace('nameString', '<b>No Results Found.</b>', $output);
        $output = str_replace('functionString', 'Sorry :(', $output);

        // Output
        echo($output);
    }
}

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

Also to add the language to the session, I would define some constants for each language, then make sure you have the session library autoloaded in config/autoload.php, or you load it whenever you need it. Add the users desired language to the session:

$this->session->set_userdata('language', ENGLISH);

Then you can grab it anytime like this:

$language = $this->session->userdata('language');

asp.net: How can I remove an item from a dropdownlist?

I would add an identifying Id or class to the dropbox and remove using Javascript.

The article here should help.

D

How to escape a JSON string containing newline characters using JavaScript?

It's better to use JSON.parse(yourUnescapedJson);

How to specify non-default shared-library path in GCC Linux? Getting "error while loading shared libraries" when running

There are two ways to achieve that:

  • Use -rpath linker option:

gcc XXX.c -o xxx.out -L$HOME/.usr/lib -lXX -Wl,-rpath=/home/user/.usr/lib

  • Use LD_LIBRARY_PATH environment variable - put this line in your ~/.bashrc file:

    export LD_LIBRARY_PATH=/home/user/.usr/lib

This will work even for a pre-generated binaries, so you can for example download some packages from the debian.org, unpack the binaries and shared libraries into your home directory, and launch them without recompiling.

For a quick test, you can also do (in bash at least):

LD_LIBRARY_PATH=/home/user/.usr/lib ./xxx.out

which has the advantage of not changing your library path for everything else.

Embed an External Page Without an Iframe?

What about something like this?

<?php
$URL = "http://example.com";
$base = '<base href="'.$URL.'">';
$host = preg_replace('/^[^\/]+\/\//', '', $URL);
$tarray = explode('/', $host);
$host = array_shift($tarray);
$URI = '/' . implode('/', $tarray);
$content = '';
$fp = @fsockopen($host, 80, $errno, $errstr, 30);
if(!$fp) { echo "Unable to open socked: $errstr ($errno)\n"; exit; } 
fwrite($fp,"GET $URI HTTP/1.0\r\n");
fwrite($fp,"Host: $host\r\n");
if( isset($_SERVER["HTTP_USER_AGENT"]) ) { fwrite($fp,'User-Agent: '.$_SERVER

["HTTP_USER_AGENT"]."\r\n"); }
fwrite($fp,"Connection: Close\r\n");
fwrite($fp,"\r\n");
while (!feof($fp)) { $content .= fgets($fp, 128); }
fclose($fp);
if( strpos($content,"\r\n") > 0 ) { $eolchar = "\r\n"; }
else { $eolchar = "\n"; }
$eolpos = strpos($content,"$eolchar$eolchar");
$content = substr($content,($eolpos + strlen("$eolchar$eolchar")));
if( preg_match('/<head\s*>/i',$content) ) { echo( preg_replace('/<head\s*>/i','<head>'.

$base,$content,1) ); }
else { echo( preg_replace('/<([a-z])([^>]+)>/i',"<\\1\\2>".$base,$content,1) ); }
?>

XML element with attribute and content using JAXB

Here is working solution:

Output:

public class XmlTest {

    private static final Logger log = LoggerFactory.getLogger(XmlTest.class);

    @Test
    public void createDefaultBook() throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
        Marshaller marshaller = jaxbContext.createMarshaller();

        StringWriter writer = new StringWriter();
        marshaller.marshal(new Book(), writer);

        log.debug("Book xml:\n {}", writer.toString());
    }


    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlRootElement(name = "book")
    public static class Book {

        @XmlElementRef(name = "price")
        private Price price = new Price();


    }

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlRootElement(name = "price")
    public static class Price {
        @XmlAttribute(name = "drawable")
        private Boolean drawable = true; //you may want to set default value here

        @XmlValue
        private int priceValue = 1234;

        public Boolean getDrawable() {
            return drawable;
        }

        public void setDrawable(Boolean drawable) {
            this.drawable = drawable;
        }

        public int getPriceValue() {
            return priceValue;
        }

        public void setPriceValue(int priceValue) {
            this.priceValue = priceValue;
        }
    }
}

Output:

22:00:18.471 [main] DEBUG com.grebski.stack.XmlTest - Book xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book>
    <price drawable="true">1234</price>
</book>

Wildcards in jQuery selectors

Try the jQuery starts-with

selector, '^=', eg

[id^="jander"]

I have to ask though, why don't you want to do this using classes?

What is the difference between a symbolic link and a hard link?

I just found an easy way to understand hard links in a common scenario, software install.

One day I downloaded a software to folder Downloads for install. After I did sudo make install, some executables were cped to local bin folder. Here, cp creates hard link. I was happy with the software but soon realized that Downloads isn't a good place in the long run. So I mved the software folder to source directory. Well, I can still run the software as before without worrying about any target link things, like in Windows. This means hard link finds inode directly and other files around.

Decode HTML entities in Python string?

This probably isnt relevant here. But to eliminate these html entites from an entire document, you can do something like this: (Assume document = page and please forgive the sloppy code, but if you have ideas as to how to make it better, Im all ears - Im new to this).

import re
import HTMLParser

regexp = "&.+?;" 
list_of_html = re.findall(regexp, page) #finds all html entites in page
for e in list_of_html:
    h = HTMLParser.HTMLParser()
    unescaped = h.unescape(e) #finds the unescaped value of the html entity
    page = page.replace(e, unescaped) #replaces html entity with unescaped value

Generating random number between 1 and 10 in Bash Shell Script

Simplest solution would be to use tool which allows you to directly specify ranges, like shuf

shuf -i1-10 -n1

If you want to use $RANDOM, it would be more precise to throw out the last 8 numbers in 0...32767, and just treat it as 0...32759, since taking 0...32767 mod 10 you get the following distribution

0-8 each: 3277 
8-9 each: 3276

So, slightly slower but more precise would be

while :; do ran=$RANDOM; ((ran < 32760)) && echo $(((ran%10)+1)) && break; done 

jQuery won't parse my JSON from AJAX query

I had a similar problem to this where Firefox 3.5 worked fine and parsed my JSON data but Firefox 3.0.6 returned a parseerror. Turned out it was a blank space at the start of the JSON that caused Firefox 3.0.6 to throw an error. Removing the blank space fixed it

How to make an autocomplete TextBox in ASP.NET?

Try this: .aspx page

<td>  
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"OnTextChanged="TextBox1_TextChanged"></asp:TextBox>  
<asp:AutoCompleteExtender ServiceMethod="GetCompletionList" MinimumPrefixLength="1"  
   CompletionInterval="10" EnableCaching="false" CompletionSetCount="1" TargetControlID="TextBox1"  
   ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">  
      </asp:AutoCompleteExtender>  

Now To auto populate from database :

public static List<string> GetCompletionList(string prefixText, int count)  
    {  
        return AutoFillProducts(prefixText);  

    }  

    private static List<string> AutoFillProducts(string prefixText)  
    {  
        using (SqlConnection con = new SqlConnection())  
        {  
            con.ConnectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;  
            using (SqlCommand com = new SqlCommand())  
            {  
                com.CommandText = "select ProductName from ProdcutMaster where " + "ProductName like @Search + '%'";  
                com.Parameters.AddWithValue("@Search", prefixText);  
                com.Connection = con;  
                con.Open();  
                List<string> countryNames = new List<string>();  
                using (SqlDataReader sdr = com.ExecuteReader())  
                {  
                    while (sdr.Read())  
                    {  
                        countryNames.Add(sdr["ProductName"].ToString());  
                    }  
                }  
                con.Close();  
                return countryNames;  
            }  
        }  
    }  

Now:create a stored Procedure that fetches the Product details depending on the selected product from the Auto Complete Text Box.

Create Procedure GetProductDet  
(  
@ProductName varchar(50)    
)  
as  
begin  
Select BrandName,warranty,Price from ProdcutMaster where ProductName=@ProductName  
End   

Create a function name to get product details ::

private void GetProductMasterDet(string ProductName)  
    {  
        connection();  
        com = new SqlCommand("GetProductDet", con);  
        com.CommandType = CommandType.StoredProcedure;  
        com.Parameters.AddWithValue("@ProductName", ProductName);  
        SqlDataAdapter da = new SqlDataAdapter(com);  
        DataSet ds=new DataSet();  
        da.Fill(ds);  
        DataTable dt = ds.Tables[0];  
        con.Close();  
        //Binding TextBox From dataTable  
        txtbrandName.Text =dt.Rows[0]["BrandName"].ToString();  
        txtwarranty.Text = dt.Rows[0]["warranty"].ToString();  
        txtPrice.Text = dt.Rows[0]["Price"].ToString();   
    }

Auto post back should be true

<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>

Now, Just call this function

protected void TextBox1_TextChanged(object sender, EventArgs e)  
  {  
      //calling method and Passing Values  
      GetProductMasterDet(TextBox1.Text);  
  } 

Vertical Tabs with JQuery?

super simple function that will allow you to create your own tab / accordion structure here: http://jsfiddle.net/nabeezy/v36DF/

bindSets = function (tabClass, tabClassActive, contentClass, contentClassHidden) {
        //Dependent on jQuery
        //PARAMETERS
        //tabClass: 'the class name of the DOM elements that will be clicked',
        //tabClassActive: 'the class name that will be applied to the active tabClass element when clicked (must write your own css)',
        //contentClass: 'the class name of the DOM elements that will be modified when the corresponding tab is clicked',
        //contentClassHidden: 'the class name that will be applied to all contentClass elements except the active one (must write your own css)',
        //MUST call bindSets() after dom has rendered

        var tabs = $('.' + tabClass);
        var tabContent = $('.' + contentClass);
        if(tabs.length !== tabContent.length){console.log('JS bindSets: sets contain a different number of elements')};
        tabs.each(function (index) {
            this.matchedElement = tabContent[index];
            $(this).click(function () {
                tabs.each(function () {
                    this.classList.remove(tabClassActive);
                });
                tabContent.each(function () {
                    this.classList.add(contentClassHidden);
                });
                this.classList.add(tabClassActive);
                this.matchedElement.classList.remove(contentClassHidden);
            });
        })
        tabContent.each(function () {
            this.classList.add(contentClassHidden);
        });

        //tabs[0].click();
    }
bindSets('tabs','active','content','hidden');

Angular.js: How does $eval work and why is it different from vanilla eval?

From the test,

it('should allow passing locals to the expression', inject(function($rootScope) {
  expect($rootScope.$eval('a+1', {a: 2})).toBe(3);

  $rootScope.$eval(function(scope, locals) {
    scope.c = locals.b + 4;
  }, {b: 3});
  expect($rootScope.c).toBe(7);
}));

We also can pass locals for evaluation expression.

How to add Tomcat Server in eclipse

  1. Go to Server tab enter image description here

  2. Click on No servers are available. Click this link to create a new server.

  3. Select Tomcat V8.0 from server type list: enter image description here

  4. Provide path of server: enter image description here

  5. Click Finish.

  6. You will see server added: enter image description here

  7. Right click->Start

Now you can run your web applications on server.

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

Here is a possible solution:

From your first script, call your second script with the following line:

wscript.exe invis.vbs run.bat %*

Actually, you are calling a vbs script with:

  • the [path]\name of your script
  • all the other arguments needed by your script (%*)

Then, invis.vbs will call your script with the Windows Script Host Run() method, which takes:

  • intWindowStyle : 0 means "invisible windows"
  • bWaitOnReturn : false means your first script does not need to wait for your second script to finish

Here is invis.vbs:

set args = WScript.Arguments
num = args.Count

if num = 0 then
    WScript.Echo "Usage: [CScript | WScript] invis.vbs aScript.bat <some script arguments>"
    WScript.Quit 1
end if

sargs = ""
if num > 1 then
    sargs = " "
    for k = 1 to num - 1
        anArg = args.Item(k)
        sargs = sargs & anArg & " "
    next
end if

Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.Run """" & WScript.Arguments(0) & """" & sargs, 0, False

git ahead/behind info between master and branch?

First of all to see how many revisions you are behind locally, you should do a git fetch to make sure you have the latest info from your remote.

The default output of git status tells you how many revisions you are ahead or behind, but usually I find this too verbose:

$ git status
# On branch master
# Your branch and 'origin/master' have diverged,
# and have 2 and 1 different commit each, respectively.
#
nothing to commit (working directory clean)

I prefer git status -sb:

$ git status -sb
## master...origin/master [ahead 2, behind 1]

In fact I alias this to simply git s, and this is the main command I use for checking status.

To see the diff in the "ahead revisions" of master, I can exclude the "behind revisions" from origin/master:

git diff master..origin/master^

To see the diff in the "behind revisions" of origin/master, I can exclude the "ahead revisions" from master:

git diff origin/master..master^^

If there are 5 revisions ahead or behind it might be easier to write like this:

git diff master..origin/master~5
git diff origin/master..master~5

UPDATE

To see the ahead/behind revisions, the branch must be configured to track another branch. For me this is the default behavior when I clone a remote repository, and after I push a branch with git push -u remotename branchname. My version is 1.8.4.3, but it's been working like this as long as I remember.

As of version 1.8, you can set the tracking branch like this:

git branch --track test-branch

As of version 1.7, the syntax was different:

git branch --set-upstream test-branch

How to add 10 minutes to my (String) time?

Java 7 Time API

    DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm");

    LocalTime lt = LocalTime.parse("14:10");
    System.out.println(df.format(lt.plusMinutes(10)));

Good beginners tutorial to socket.io?

A 'fun' way to learn socket.io is to play BrowserQuest by mozilla and look at its source code :-)

http://browserquest.mozilla.org/

https://github.com/mozilla/BrowserQuest

How to make a DIV always float on the screen in top right corner?

Use position:fixed, as previously stated, IE6 doesn't recognize position:fixed, but with some css magic you can get IE6 to behave:

html, body {
    height: 100%;
    overflow:auto;
}
body #fixedElement {
    position:fixed !important;
    position: absolute; /*ie6 */
    bottom: 0;
}

The !important flag makes it so you don't have to use a conditional comment for IE. This will have #fixedElement use position:fixed in all browsers but IE, and in IE, position:absolute will take effect with bottom:0. This will simulate position:fixed for IE6

Best way to store date/time in mongodb

The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.

> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }

The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.

If you need to, you can easily convert Date objects to and from Unix timestamps1), using the getTime() method and Date(milliseconds) constructor, respectively.

1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.

Angular2 *ngIf check object array length in template

You can use

<div class="col-sm-12" *ngIf="event.attendees?.length">

Without event.attendees?.length > 0 or even event.attendees?length != 0

Because ?.length already return boolean value.

If in array will be something it will display it else not.

Best way to import Observable from rxjs

Rxjs v 6.*

It got simplified with newer version of rxjs .

1) Operators

import {map} from 'rxjs/operators';

2) Others

import {Observable,of, from } from 'rxjs';

Instead of chaining we need to pipe . For example

Old syntax :

source.map().switchMap().subscribe()

New Syntax:

source.pipe(map(), switchMap()).subscribe()

Note: Some operators have a name change due to name collisions with JavaScript reserved words! These include:

do -> tap,

catch -> catchError

switch -> switchAll

finally -> finalize


Rxjs v 5.*

I am writing this answer partly to help myself as I keep checking docs everytime I need to import an operator . Let me know if something can be done better way.

1) import { Rx } from 'rxjs/Rx';

This imports the entire library. Then you don't need to worry about loading each operator . But you need to append Rx. I hope tree-shaking will optimize and pick only needed funcionts( need to verify ) As mentioned in comments , tree-shaking can not help. So this is not optimized way.

public cache = new Rx.BehaviorSubject('');

Or you can import individual operators .

This will Optimize your app to use only those files :

2) import { _______ } from 'rxjs/_________';

This syntax usually used for main Object like Rx itself or Observable etc.,

Keywords which can be imported with this syntax

 Observable, Observer, BehaviorSubject, Subject, ReplaySubject

3) import 'rxjs/add/observable/__________';

Update for Angular 5

With Angular 5, which uses rxjs 5.5.2+

import { empty } from 'rxjs/observable/empty';
import { concat} from 'rxjs/observable/concat';

These are usually accompanied with Observable directly. For example

Observable.from()
Observable.of()

Other such keywords which can be imported using this syntax:

concat, defer, empty, forkJoin, from, fromPromise, if, interval, merge, of, 
range, throw, timer, using, zip

4) import 'rxjs/add/operator/_________';

Update for Angular 5

With Angular 5, which uses rxjs 5.5.2+

import { filter } from 'rxjs/operators/filter';
import { map } from 'rxjs/operators/map';

These usually come in the stream after the Observable is created. Like flatMap in this code snippet:

Observable.of([1,2,3,4])
          .flatMap(arr => Observable.from(arr));

Other such keywords using this syntax:

audit, buffer, catch, combineAll, combineLatest, concat, count, debounce, delay, 
distinct, do, every, expand, filter, finally, find , first, groupBy,
ignoreElements, isEmpty, last, let, map, max, merge, mergeMap, min, pluck, 
publish, race, reduce, repeat, scan, skip, startWith, switch, switchMap, take, 
takeUntil, throttle, timeout, toArray, toPromise, withLatestFrom, zip

FlatMap: flatMap is alias to mergeMap so we need to import mergeMap to use flatMap.


Note for /add imports :

We only need to import once in whole project. So its advised to do it at a single place. If they are included in multiple files, and one of them is deleted, the build will fail for wrong reasons.

R dates "origin" must be supplied

Another option is the lubridate package:

library(lubridate)

x <- 15103
as_date(x, origin = lubridate::origin)
"2011-05-09"

y <- 1442866615
as_datetime(y, origin = lubridate::origin)
"2015-09-21 20:16:55 UTC"

From the docs:

Origin is the date-time for 1970-01-01 UTC in POSIXct format. This date-time is the origin for the numbering system used by POSIXct, POSIXlt, chron, and Date classes.

autocomplete ='off' is not working when the input type is password and make the input field above it to enable autocomplete

I know this is an old question, but browsers have been changing over time. Although some of the answers to this question mentioned here like: creating a temporary text box above the password field and hiding it may have worked in the past, currently the easiest way to prevent the browser from popping up the password manager is to have at least three separate additional hidden password inputs, each with different dummy values, like so:

<form method="post" autocomplete="off" action="">
    <ul class="field-set">
    <li>
        <label>Username:</label>
        <input type="text" name="acct" id="username" maxlength="100" size="20">
    </li>
    <li>
        <label>Password:</label>
        <input type="password" name="pswd" id="password" maxlength="16" size="20" >
        <input type="password" style="display: none;" value="dummyinput1"/>
        <input type="password" style="display: none;" value="dummyinput2"/>
        <input type="password" style="display: none;" value="dummyinput3"/>
    </li>
    <li>
        <input type="submit" class="button" value="Login" id="Login" name="Login">
    </li>
    </ul>
</form>

hide div tag on mobile view only?

Well, I think that there are simple solutions than mentioned here on this page! first of all, let's make an example:

You have 1 DIV and want to hide thas DIV on Desktop and show on Mobile (or vice versa). So, let's presume that the DIV position placed in the Head section and named as header_div.

The global code in your CSS file will be: (for the same DIV):

.header_div {
    display: none;
}

@media all and (max-width: 768px){
.header_div {
    display: block;
}
}

So simple and no need to make 2 div's one for desktop and the other for mobile.

Hope this helps.

Thank you.

Get max and min value from array in JavaScript

arr = [9,4,2,93,6,2,4,61,1];
ArrMax = Math.max.apply(Math, arr);

Keyboard shortcuts are not active in Visual Studio with Resharper installed

Without resetting Visual Studio settings :

I found simply

  • ReSharper > Options > Keyboards
  • Apply Scheme button
  • Save button

Brought back my lost ReSharper keyboard commands without messing with my VS settings.

(Visual Studio Community 2017 + ReSharper Ultimate)

How can I test a change made to Jenkinsfile locally?

TL;DR

Long Version
Jenkins Pipeline testing becomes more and more of a pain. Unlike the classic declarative job configuration approach where the user was limited to what the UI exposed the new Jenkins Pipeline is a full fledged programming language for the build process where you mix the declarative part with your own code. As good developers we want to have some unit tests for this kind of code as well.

There are three steps you should follow when developing Jenkins Pipelines. The step 1. should cover 80% of the uses cases.

  1. Do as much as possible in build scripts (eg. Maven, Gradle, Gulp etc.). Then in your pipeline scripts just calls the build tasks in the right order. The build pipeline just orchestrates and executes the build tasks but does not have any major logic that needs a special testing.
  2. If the previous rule can't be fully applied then move over to Pipeline Shared libraries where you can develop and test custom logic on its own and integrate them into the pipeline.
  3. If all of the above fails you, you can try one of those libraries that came up recently (March-2017). Jenkins Pipeline Unit testing framework or pipelineUnit (examples). Since 2018 there is also Jenkinsfile Runner, a package to execution Jenkins pipelines from a command line tool.

Examples

The pipelineUnit GitHub repo contains some Spock examples on how to use Jenkins Pipeline Unit testing framework

How to verify a method is called two times with mockito verify()

Using the appropriate VerificationMode:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");

can we use xpath with BeautifulSoup?

Maybe you can try the following without XPath

from simplified_scrapy.simplified_doc import SimplifiedDoc 
html = '''
<html>
<body>
<div>
    <h1>Example Domain</h1>
    <p>This domain is for use in illustrative examples in documents. You may use this
    domain in literature without prior coordination or asking for permission.</p>
    <p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>
'''
# What XPath can do, so can it
doc = SimplifiedDoc(html)
# The result is the same as doc.getElementByTag('body').getElementByTag('div').getElementByTag('h1').text
print (doc.body.div.h1.text)
print (doc.div.h1.text)
print (doc.h1.text) # Shorter paths will be faster
print (doc.div.getChildren())
print (doc.div.getChildren('p'))

How can I decrypt MySQL passwords

Hashing is a one-way process but using a password-list you can regenerate the hashes and compare to the stored hash to 'crack' the password.

This site https://crackstation.net/ attempts to do this for you - run through passwords lists and tell you the cleartext password based on your hash.

Setting a div's height in HTML with CSS

_x000D_
_x000D_
.rightfloat {_x000D_
  color: red;_x000D_
  background-color: #BBBBBB;_x000D_
  float: right;_x000D_
  width: 200px;_x000D_
}_x000D_
_x000D_
.left {_x000D_
  font-size: 20pt;_x000D_
}_x000D_
_x000D_
.separator {_x000D_
  clear: both;_x000D_
  width: 100%;_x000D_
  border-top: 1px solid black;_x000D_
}
_x000D_
<div class="separator">_x000D_
  <div class="rightfloat">_x000D_
    Some really short content._x000D_
  </div>_x000D_
  <div class="left"> _x000D_
    Some really really really really really really_x000D_
    really really really really big content_x000D_
  </div>_x000D_
</div>_x000D_
<div class="separator">_x000D_
  <div class="rightfloat">_x000D_
    Some more short content._x000D_
  </div>_x000D_
  <div class="left"> _x000D_
    Some really really really really really really_x000D_
    really really really really big content_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is a Python dictionary an example of a hash table?

There must be more to a Python dictionary than a table lookup on hash(). By brute experimentation I found this hash collision:

>>> hash(1.1)
2040142438
>>> hash(4504.1)
2040142438

Yet it doesn't break the dictionary:

>>> d = { 1.1: 'a', 4504.1: 'b' }
>>> d[1.1]
'a'
>>> d[4504.1]
'b'

Sanity check:

>>> for k,v in d.items(): print(hash(k))
2040142438
2040142438

Possibly there's another lookup level beyond hash() that avoids collisions between dictionary keys. Or maybe dict() uses a different hash.

(By the way, this in Python 2.7.10. Same story in Python 3.4.3 and 3.5.0 with a collision at hash(1.1) == hash(214748749.8).)

:before and background-image... should it work?

Background images on :before and :after elements should work. If you post an example I could probably tell you why it does not work in your case.

Here is an example: http://jsfiddle.net/namas/3/

You can specify the dimensions of the element in % by using background-size: 100% 100% (width / height), for example.

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

I had the error when I was trying to make a custom result for a stored procedure and assumed it had to be an entity.

The solution was that I just made a complex type in the Model browser and assigned that as a result to the "Edit function imports".

I will add it here since it looks like this question is where google takes you when you get this error.

Creating an array of objects in Java

You are correct. Aside from that if we want to create array of specific size filled with elements provided by some "factory", since Java 8 (which introduces stream API) we can use this one-liner:

A[] a = Stream.generate(() -> new A()).limit(4).toArray(A[]::new);
  • Stream.generate(() -> new A()) is like factory for separate A elements created in a way described by lambda, () -> new A() which is implementation of Supplier<A> - it describe how each new A instances should be created.
  • limit(4) sets amount of elements which stream will generate
  • toArray(A[]::new) (can also be rewritten as toArray(size -> new A[size])) - it lets us decide/describe type of array which should be returned.

For some primitive types you can use DoubleStream, IntStream, LongStream which additionally provide generators like range rangeClosed and few others.

jQuery get an element by its data-id

Yes, you can find out element by data attribute.

element = $('a[data-item-id="stand-out"]');

How to change href of <a> tag on button click through javascript

I know its bit old post. Still, it might help some one.

Instead of tag,if possible you can this as well.

 <script type="text/javascript">
        function IsItWorking() {
          // Do your stuff here ...
            alert("YES, It Works...!!!");
        }
    </script>   

    `<asp:HyperLinkID="Link1"NavigateUrl="javascript:IsItWorking();"`            `runat="server">IsItWorking?</asp:HyperLink>`

Any comments on this?

Forgot Oracle username and password, how to retrieve?

  1. Open Command Prompt/Terminal and type:

    sqlplus / as SYSDBA

  2. SQL prompt will turn up. Now type:

    ALTER USER existing_account_name IDENTIFIED BY new_password ACCOUNT UNLOCK;

  3. Voila! You've unlocked your account.

Disable a textbox using CSS

Just try this.

<asp:TextBox ID="tb" onkeypress="javascript:return false;" width="50px" runat="server"></asp:TextBox>

This won't allow any characters to be entered inside the TextBox.

Removing an element from an Array (Java)

Sure, create another array :)

Losing scope when using ng-include

This is because of ng-include which creates a new child scope, so $scope.lineText isn’t changed. I think that this refers to the current scope, so this.lineText should be set.

Assign output of a program to a variable using a MS batch file

Some macros to set the output of a command to a variable/

For directly in the command prompt

c:\>doskey assign=for /f "tokens=1,2 delims=," %a in ("$*") do @for /f "tokens=* delims=" %# in ('"%a"') do @set "%b=%#"

c:\>assign WHOAMI /LOGONID,my-id

c:\>echo %my-id%

Macro with arguments

As this macro accepts arguments as a function i think it is the neatest macro to be used in a batch file:

@echo off

::::: ---- defining the assign macro ---- ::::::::
setlocal DisableDelayedExpansion
(set LF=^
%=EMPTY=%
)
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"

::set argv=Empty
set assign=for /L %%n in (1 1 2) do ( %\n%
   if %%n==2 (%\n%
      setlocal enableDelayedExpansion%\n%
      for /F "tokens=1,2 delims=," %%A in ("!argv!") do (%\n%
         for /f "tokens=* delims=" %%# in ('%%~A') do endlocal^&set "%%~B=%%#" %\n%
      ) %\n%
   ) %\n%
) ^& set argv=,

::::: -------- ::::::::


:::EXAMPLE
%assign% "WHOAMI /LOGONID",result
echo %result%

FOR /F macro

not so easy to read as the previous macro.

::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
;;set "--=') do @set ""                        &::
;;set "}}==%%#""                               &::
::::::::::::::::::::::::::::::::::::::::::::::::::

:: --examples

::assigning ver output to %win-ver% variable
%{{% ver %--%win-ver%}}%
echo 3: %win-ver%


::assigning hostname output to %my-host% variable
%{{% hostname %--%my-host%}}%
echo 4: %my-host%

Macro using a temp file

Easier to read , it is not so slow if you have a SSD drive but still it creates a temp file.

@echo off

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1" &::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

chcp %[[%code-page%]]%
echo ~~%code-page%~~

whoami %[[%its-me%]]%
echo ##%its-me%##

Java Object Null Check for method

If you are using Java 7 You can use Objects.requireNotNull(object[, optionalMessage]); - to check if the parameter is null. To check if each element is not null just use

if(null != books[i]){/*do stuff*/}

Example:

public static double calculateInventoryTotal(Book[] books){
    Objects.requireNotNull(books, "Books must not be null");

    double total = 0;

    for (int i = 0; i < books.length; i++){
        if(null != book[i]){
            total += books[i].getPrice();
        }
    }

    return total;
}

Rails: Check output of path helper from console

you can also

include Rails.application.routes.url_helpers

from inside a console sessions to access the helpers:

url_for controller: :users, only_path: true
users_path
# => '/users'

or

Rails.application.routes.url_helpers.users_path

How do I convert dmesg timestamp to custom date format?

Understanding dmesg timestamp is pretty simple: it is time in seconds since the kernel started. So, having time of startup (uptime), you can add up the seconds and show them in whatever format you like.

Or better, you could use the -T command line option of dmesg and parse the human readable format.

From the man page:

-T, --ctime
    Print human readable timestamps. The timestamp could be inaccurate!

    The time source used for the logs is not updated after system SUSPEND/RESUME.

How to convert from []byte to int in Go Programming

var bs []byte
value, _ := strconv.ParseInt(string(bs), 10, 64)

Is it safe to use Project Lombok?

Wanted to use lombok's @ToString but soon faced random compile errors on project rebuild in Intellij IDEA. Had to hit compile several times before incremental compilation could complete with success.

Tried both lombok 1.12.2 and 0.9.3 with Intellij IDEA 12.1.6 and 13.0 without any lombok plugin under jdk 1.6.0_39 and 1.6.0_45.

Had to manually copy generated methods from delomboked source and put lombok on hold until better times.

Update

The problem happens only with parallel compile enabled.

Filed an issue: https://github.com/rzwitserloot/lombok/issues/648

Update

mplushnikov commented on 30 Jan 2016:

Newer version of Intellij doesn't have such issues anymore. I think it can be closed here.

Update

I would highly recommend to switch from Java+Lombok to Kotlin if possible. As it has resolved from the ground up all Java issues that Lombok tries to work around.

how to get current datetime in SQL?

try this

SELECT CURTIME(); return 23:12:58

SELECT CURDATE(); return 2020-11-12

SELECT NOW(); return 2020-11-12 23:19:26

SELECT DAY(now()); return 12

SELECT DAYNAME(now()); return Thursday

Hope this would be helpful for you.

Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists

The solution that worked for me was closing sublime text because the running git process was initiated by the editor.

Environment Variable with Maven

The -D properties will not be reliable propagated from the surefire-pluging to your test (I do not know why it works with eclipse). When using maven on the command line use the argLine property to wrap your property. This will pass them to your test

mvn -DargLine="-DWSNSHELL_HOME=conf" test

Use System.getProperty to read the value in your code. Have a look to this post about the difference of System.getenv and Sytem.getProperty.

How to send POST request?

Your data dictionary conteines names of form input fields, you just keep on right their values to find results. form view Header configures browser to retrieve type of data you declare. With requests library it's easy to send POST:

import requests

url = "https://bugs.python.org"
data = {'@number': 12524, '@type': 'issue', '@action': 'show'}
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept":"text/plain"}
response = requests.post(url, data=data, headers=headers)

print(response.text)

More about Request object: https://requests.readthedocs.io/en/master/api/

Python equivalent of a given wget command

easy as py:

class Downloder():
    def download_manager(self, url, destination='Files/DownloderApp/', try_number="10", time_out="60"):
        #threading.Thread(target=self._wget_dl, args=(url, destination, try_number, time_out, log_file)).start()
        if self._wget_dl(url, destination, try_number, time_out, log_file) == 0:
            return True
        else:
            return False


    def _wget_dl(self,url, destination, try_number, time_out):
        import subprocess
        command=["wget", "-c", "-P", destination, "-t", try_number, "-T", time_out , url]
        try:
            download_state=subprocess.call(command)
        except Exception as e:
            print(e)
        #if download_state==0 => successfull download
        return download_state

jQuery datepicker, onSelect won't work

The function datepicker is case sensitive and all lowercase. The following however works fine for me:

$(document).ready(function() {
  $('.date-pick').datepicker( {
    onSelect: function(date) {
        alert(date);
    },
    selectWeek: true,
    inline: true,
    startDate: '01/01/2000',
    firstDay: 1
  });
});

Checking for empty or null List<string>

For anyone who doesn't have the guarantee that the list will not be null, you can use the null-conditional operator to safely check for null and empty lists in a single conditional statement:

if (list?.Any() != true)
{
    // Handle null or empty list
}

__init__() missing 1 required positional argument

You're receiving this error because you did not pass a data variable to the DHT constructor.

aIKid and Alexander's answers are nice but it wont work because you still have to initialize self.data in the class constructor like this:

class DHT:
   def __init__(self, data=None):
      if data is None:
         data = {}
      else:
         self.data = data
      self.data['one'] = '1'
      self.data['two'] = '2'
      self.data['three'] = '3'
   def showData(self):
      print(self.data)

And then calling the method showData like this:

DHT().showData()

Or like this:

DHT({'six':6,'seven':'7'}).showData()

or like this:

# Build the class first
dht = DHT({'six':6,'seven':'7'})
# The call whatever method you want (In our case only 1 method available)
dht.showData()

How to wait until an element exists?

Here's a function that acts as a thin wrapper around MutationObserver. The only requirement is that the browser support MutationObserver; there is no dependency on JQuery. Run the snippet below to see a working example.

_x000D_
_x000D_
function waitForMutation(parentNode, isMatchFunc, handlerFunc, observeSubtree, disconnectAfterMatch) {_x000D_
  var defaultIfUndefined = function(val, defaultVal) {_x000D_
    return (typeof val === "undefined") ? defaultVal : val;_x000D_
  };_x000D_
_x000D_
  observeSubtree = defaultIfUndefined(observeSubtree, false);_x000D_
  disconnectAfterMatch = defaultIfUndefined(disconnectAfterMatch, false);_x000D_
_x000D_
  var observer = new MutationObserver(function(mutations) {_x000D_
    mutations.forEach(function(mutation) {_x000D_
      if (mutation.addedNodes) {_x000D_
        for (var i = 0; i < mutation.addedNodes.length; i++) {_x000D_
          var node = mutation.addedNodes[i];_x000D_
          if (isMatchFunc(node)) {_x000D_
            handlerFunc(node);_x000D_
            if (disconnectAfterMatch) observer.disconnect();_x000D_
          };_x000D_
        }_x000D_
      }_x000D_
    });_x000D_
  });_x000D_
_x000D_
  observer.observe(parentNode, {_x000D_
    childList: true,_x000D_
    attributes: false,_x000D_
    characterData: false,_x000D_
    subtree: observeSubtree_x000D_
  });_x000D_
}_x000D_
_x000D_
// Example_x000D_
waitForMutation(_x000D_
  // parentNode: Root node to observe. If the mutation you're looking for_x000D_
  // might not occur directly below parentNode, pass 'true' to the_x000D_
  // observeSubtree parameter._x000D_
  document.getElementById("outerContent"),_x000D_
  // isMatchFunc: Function to identify a match. If it returns true,_x000D_
  // handlerFunc will run._x000D_
  // MutationObserver only fires once per mutation, not once for every node_x000D_
  // inside the mutation. If the element we're looking for is a child of_x000D_
  // the newly-added element, we need to use something like_x000D_
  // node.querySelector() to find it._x000D_
  function(node) {_x000D_
    return node.querySelector(".foo") !== null;_x000D_
  },_x000D_
  // handlerFunc: Handler._x000D_
  function(node) {_x000D_
    var elem = document.createElement("div");_x000D_
    elem.appendChild(document.createTextNode("Added node (" + node.innerText + ")"));_x000D_
    document.getElementById("log").appendChild(elem);_x000D_
  },_x000D_
  // observeSubtree_x000D_
  true,_x000D_
  // disconnectAfterMatch: If this is true the hanlerFunc will only run on_x000D_
  // the first time that isMatchFunc returns true. If it's false, the handler_x000D_
  // will continue to fire on matches._x000D_
  false);_x000D_
_x000D_
// Set up UI. Using JQuery here for convenience._x000D_
_x000D_
$outerContent = $("#outerContent");_x000D_
$innerContent = $("#innerContent");_x000D_
_x000D_
$("#addOuter").on("click", function() {_x000D_
  var newNode = $("<div><span class='foo'>Outer</span></div>");_x000D_
  $outerContent.append(newNode);_x000D_
});_x000D_
$("#addInner").on("click", function() {_x000D_
  var newNode = $("<div><span class='foo'>Inner</span></div>");_x000D_
  $innerContent.append(newNode);_x000D_
});
_x000D_
.content {_x000D_
  padding: 1em;_x000D_
  border: solid 1px black;_x000D_
  overflow-y: auto;_x000D_
}_x000D_
#innerContent {_x000D_
  height: 100px;_x000D_
}_x000D_
#outerContent {_x000D_
  height: 200px;_x000D_
}_x000D_
#log {_x000D_
  font-family: Courier;_x000D_
  font-size: 10pt;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h2>Create some mutations</h2>_x000D_
<div id="main">_x000D_
  <button id="addOuter">Add outer node</button>_x000D_
  <button id="addInner">Add inner node</button>_x000D_
  <div class="content" id="outerContent">_x000D_
    <div class="content" id="innerContent"></div>_x000D_
  </div>_x000D_
</div>_x000D_
<h2>Log</h2>_x000D_
<div id="log"></div>
_x000D_
_x000D_
_x000D_

JSON Java 8 LocalDateTime format in Spring Boot

simply use:

@JsonFormat(pattern="10/04/2019")

or you can use pattern as you like for e.g: ('-' in place of '/')

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

Reset git proxy to default configuration

git config --global --unset http.proxy

How to refer environment variable in POM.xml?

Check out the Maven Properties Guide...

As Seshagiri pointed out in the comments, ${env.VARIABLE_NAME} will do what you want.

I will add a word of warning and say that a pom.xml should completely describe your project so please use environment variables judiciously. If you make your builds dependent on your environment, they are harder to reproduce

How to reset the state of a Redux store?

Simply have your logout link clear session and refresh the page. No additional code needed for your store. Any time you want to completely reset the state a page refresh is a simple and easily repeatable way to handle it.

PPT to PNG with transparent background

It can't be done, either manually or progamatically. This is because the color behind every slide master is white. If you set your background to 100% transparent, it will print as white.

The best you could do is design your slide with all the stuff you want, group everything you want to appear in the transparent image and then right-click/save as picture/.PNG (or you could do that with a macro as well). In this way you would retain transparency.

Here's an example of how to export all slides' shapes to seperate PNG files. Note:

  1. This does not get any background shapes on the Slide Master.
  2. Resulting PNGs will not be the same size as each other, depending on where the shapes are located on each slide.
  3. This uses a depreciated function, namely Shape.Export. This means that while the function is still available up to PowerPoint 2010, it may be removed from PowerPoint VBA later.

    Sub PrintShapesToPng()
        Dim ap As Presentation: Set ap = ActivePresentation
        Dim sl As slide
        Dim shGroup As ShapeRange
        For Each sl In ap.Slides
            ActiveWindow.View.GotoSlide (sl.SlideIndex)
            sl.Shapes.SelectAll
            Set shGroup = ActiveWindow.Selection.ShapeRange
            shGroup.Export ap.Path & "\Slide" & sl.SlideIndex & ".png", _
                                ppShapeFormatPNG, , , ppRelativeToSlide
        Next
    End Sub
    

How to grant remote access permissions to mysql server for user?

This worked for me. But there was a strange problem that even I tryed first those it didnt affect. I updated phpmyadmin page and got it somehow working.

If you need access to local-xampp-mysql. You can go to xampp-shell -> opening command prompt.

Then mysql -uroot -p --port=3306 or mysql -uroot -p (if there is password set). After that you can grant those acces from mysql shell page (also can work from localhost/phpmyadmin).

Just adding these if somebody find this topic and having beginner problems.

Using NULL in C++?

In C++ NULL expands to 0 or 0L. See this quote from Stroustrup's FAQ:

Should I use NULL or 0?

In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.

If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.

How different is Scrum practice from Agile Practice?

Agile is not a methodology, embracing the agile manifesto means adopting a particular philosophy about software development. Within that philosophical perspective, there are many processes and practices. Scrum is a set of practices that follow agile principles. Many people grab onto the practices and processes without embracing (or even understanding) the underlying philosophy and they often end up with gorillarinas.

MVC If statement in View

Every time you use html syntax you have to start the next razor statement with a @. So it should be @if ....

Using env variable in Spring Boot's application.properties

You don't need to use java variables. To include system env variables add the following to your application.properties file:

spring.datasource.url = ${OPENSHIFT_MYSQL_DB_HOST}:${OPENSHIFT_MYSQL_DB_PORT}/"nameofDB"
spring.datasource.username = ${OPENSHIFT_MYSQL_DB_USERNAME}
spring.datasource.password = ${OPENSHIFT_MYSQL_DB_PASSWORD}

But the way suggested by @Stefan Isele is more preferable, because in this case you have to declare just one env variable: spring.profiles.active. Spring will read the appropriate property file automatically by application-{profile-name}.properties template.

how do I create an array in jquery?

Here is an example that I used.

<script>
  $(document).ready(function(){
      var array =  $.makeArray(document.getElementsByTagName(“p”));
      array.reverse(); 
      $(array).appendTo(document.body);
  });
</script>

Unix command to find lines common in two files

perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/'  file1 file2

How can I debug a .BAT script?

rem out the @ECHO OFF and call your batch file redirectin ALL output to a log file..

c:> yourbatch.bat (optional parameters) > yourlogfile.txt 2>&1

found at http://www.robvanderwoude.com/battech_debugging.php

IT WORKS!! don't forget the 2>&1...

WIZ

How To Upload Files on GitHub

You need to create a git repo locally, add your project files to that repo, commit them to the local repo, and then sync that repo to your repo on github. You can find good instructions on how to do the latter bit on github, and the former should be easy to do with the software you've downloaded.

How to use a different version of python during NPM install?

set python to python2.7 before running npm install

Linux:

export PYTHON=python2.7

Windows:

set PYTHON=python2.7

Android RecyclerView addition & removal of items

  String str = arrayList.get(position);
  arrayList.remove(str);
  MyAdapter.this.notifyDataSetChanged();

Get current value when change select option - Angular2

There is a way to get the value from different options. check this plunker

component.html

<select class="form-control" #t (change)="callType(t.value)">
  <option *ngFor="#type of types" [value]="type">{{type}}</option>
</select>

component.ts

this.types = [ 'type1', 'type2', 'type3' ];

callType(value) {
  console.log(value);
  this.order.type = value;
}

Convert integer to binary in C#

Convert.ToInt32(string, base) does not do base conversion into your base. It assumes that the string contains a valid number in the indicated base, and converts to base 10.

So you're getting an error because "8" is not a valid digit in base 2.

String str = "1111";
String Ans = Convert.ToInt32(str, 2).ToString();

Will show 15 (1111 base 2 = 15 base 10)

String str = "f000";
String Ans = Convert.ToInt32(str, 16).ToString();

Will show 61440.

In Java, how do I parse XML as a String instead of a file?

Convert the string to an InputStream and pass it to DocumentBuilder

final InputStream stream = new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8));
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
builder.parse(stream);

EDIT
In response to bendin's comment regarding encoding, see shsteimer's answer to this question.

How do I get an element to scroll into view, using jQuery?

Simplest solution I have seen

var offset = $("#target-element").offset();
$('html, body').animate({
    scrollTop: offset.top,
    scrollLeft: offset.left
}, 1000);

Tutorial Here

In Go's http package, how do I get the query string on a POST request?

Below is an example:

value := r.FormValue("field")

for more info. about http package, you could visit its documentation here. FormValue basically returns POST or PUT values, or GET values, in that order, the first one that it finds.

Convert UIImage to NSData and convert back to UIImage in Swift?

Image to Data:-

    if let img = UIImage(named: "xxx.png") {
        let pngdata = img.pngData()
    }

   if let img = UIImage(named: "xxx.jpeg") {
        let jpegdata = img.jpegData(compressionQuality: 1)
    }

Data to Image:-

 let image = UIImage(data: pngData)

How to get date and time from server

You should set the timezone to the one of the timezones you want. let set the Indian timezone

// set default timezone
date_default_timezone_set('Asia/Kolkata');

$info = getdate();
$date = $info['mday'];
$month = $info['mon'];
$year = $info['year'];
$hour = $info['hours'];
$min = $info['minutes'];
$sec = $info['seconds'];

$current_date = "$date/$month/$year == $hour:$min:$sec";

How to Inspect Element using Safari Browser

Press CMD + , than click in show develop menu in menu bar. After that click Option + CMD + i to open and close the inspector

enter image description here

Optional Parameters in Web Api Attribute Routing

For an incoming request like /v1/location/1234, as you can imagine it would be difficult for Web API to automatically figure out if the value of the segment corresponding to '1234' is related to appid and not to deviceid.

I think you should change your route template to be like [Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")] and then parse the deiveOrAppid to figure out the type of id.

Also you need to make the segments in the route template itself optional otherwise the segments are considered as required. Note the ? character in this case. For example: [Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")]

SELECT CASE WHEN THEN (SELECT)

You Could try the other format for the case statement

CASE WHEN Product.type_id = 10
THEN
(
  Select Statement
)
ELSE
(
  Other select statement

)  
END
FROM Product 
WHERE Product.product_id = $pid

See http://msdn.microsoft.com/en-us/library/ms181765.aspx for more information.

How to loop through elements of forms with JavaScript?

$(function() {
    $('form button').click(function() {
        var allowSubmit = true;
        $.each($('form input:text'), function(index, formField) {
            if($(formField).val().trim().length == 0) {
                alert('field is empty!');
                allowSubmit = false;
            }
        });
        return allowSubmit;
    });
});

DEMO

Linq select object from list depending on objects attribute

I assume you are getting an exception because of Single. Your list may have more than one answer marked as correct, that is why Single will throw an exception use First, or FirstOrDefault();

Answer answer = Answers.FirstOrDefault(a => a.Correct);

Also if you want to get list of all items marked as correct you may try:

List<Answer> correctedAnswers =  Answers.Where(a => a.Correct).ToList();

If your desired result is Single, then the mistake you are doing in your query is comparing an item with the bool value. Your comparison

a == a.Correct

is wrong in the statement. Your single query should be:

Answer answer = Answers.Single(a => a.Correct == true);

Or shortly as:

Answer answer = Answers.Single(a => a.Correct);

Download JSON object as a file from browser

The download property of links is new and not is supported in Internet Explorer (see the compatibility table here). For a cross-browser solution to this problem I would take a look at FileSaver.js

How do I use Wget to download all images into a single folder, from a URL?

I wrote a shellscript that solves this problem for multiple websites: https://github.com/eduardschaeli/wget-image-scraper

(Scrapes images from a list of urls with wget)

How to convert String into Hashmap in java

@Test
public void testToStringToMap() {
    Map<String,String> expected = new HashMap<>();
    expected.put("first_name", "naresh");
    expected.put("last_name", "kumar");
    expected.put("gender", "male");
    String mapString = expected.toString();
    Map<String, String> actual = Arrays.stream(mapString.replace("{", "").replace("}", "").split(","))
            .map(arrayData-> arrayData.split("="))
            .collect(Collectors.toMap(d-> ((String)d[0]).trim(), d-> (String)d[1]));

    expected.entrySet().stream().forEach(e->assertTrue(actual.get(e.getKey()).equals(e.getValue())));
}

How to assign colors to categorical variables in ggplot2 that have stable mapping?

The easiest solution is to convert your categorical variable to a factor prior to the subsetting. Bottomline is that you need a factor variable with exact the same levels in all your subsets.

library(ggplot2)
dataset <- data.frame(category = rep(LETTERS[1:5], 100), 
    x = rnorm(500, mean = rep(1:5, 100)), y = rnorm(500, mean = rep(1:5, 100)))
dataset$fCategory <- factor(dataset$category)
subdata <- subset(dataset, category %in% c("A", "D", "E"))

With a character variable

ggplot(dataset, aes(x = x, y = y, colour = category)) + geom_point()
ggplot(subdata, aes(x = x, y = y, colour = category)) + geom_point()

With a factor variable

ggplot(dataset, aes(x = x, y = y, colour = fCategory)) + geom_point()
ggplot(subdata, aes(x = x, y = y, colour = fCategory)) + geom_point()

Python unexpected EOF while parsing

What you can try is writing your code as normal for python using the normal input command. However the trick is to add at the beginning of you program the command input=raw_input.

Now all you have to do is disable (or enable) depending on if you're running in Python/IDLE or Terminal. You do this by simply adding '#' when needed.

Switched off for use in Python/IDLE

    #input=raw_input 

And of course switched on for use in terminal.

    input=raw_input 

I'm not sure if it will always work, but its a possible solution for simple programs or scripts.

Pass value to iframe from a window

Have a look at the link below, which suggests it is possible to alter the contents of an iFrame within your page with Javascript, although you are most likely to run into a few cross browser issues. If you can do this you can use the javascript in your page to add hidden dom elements to the iFrame containing your values, which the iFrame can read. Accessing the document inside an iFrame

Renaming columns in Pandas

My method is generic wherein you can add additional delimiters by comma separating delimiters= variable and future-proof it.

Working Code:

import pandas as pd
import re


df = pd.DataFrame({'$a':[1,2], '$b': [3,4],'$c':[5,6], '$d': [7,8], '$e': [9,10]})

delimiters = '$'
matchPattern = '|'.join(map(re.escape, delimiters))
df.columns = [re.split(matchPattern, i)[1] for i in df.columns ]

Output:

>>> df
   $a  $b  $c  $d  $e
0   1   3   5   7   9
1   2   4   6   8  10

>>> df
   a  b  c  d   e
0  1  3  5  7   9
1  2  4  6  8  10

Python string class like StringBuilder in C#?

Relying on compiler optimizations is fragile. The benchmarks linked in the accepted answer and numbers given by Antoine-tran are not to be trusted. Andrew Hare makes the mistake of including a call to repr in his methods. That slows all the methods equally but obscures the real penalty in constructing the string.

Use join. It's very fast and more robust.

$ ipython3
Python 3.5.1 (default, Mar  2 2016, 03:38:02) 
IPython 4.1.2 -- An enhanced Interactive Python.

In [1]: values = [str(num) for num in range(int(1e3))]

In [2]: %%timeit
   ...: ''.join(values)
   ...: 
100000 loops, best of 3: 7.37 µs per loop

In [3]: %%timeit
   ...: result = ''
   ...: for value in values:
   ...:     result += value
   ...: 
10000 loops, best of 3: 82.8 µs per loop

In [4]: import io

In [5]: %%timeit
   ...: writer = io.StringIO()
   ...: for value in values:
   ...:     writer.write(value)
   ...: writer.getvalue()
   ...: 
10000 loops, best of 3: 81.8 µs per loop

Are lists thread-safe?

To clarify a point in Thomas' excellent answer, it should be mentioned that append() is thread safe.

This is because there is no concern that data being read will be in the same place once we go to write to it. The append() operation does not read data, it only writes data to the list.

Unsupported major.minor version 52.0

You need to upgrade your Java version to Java 8.

Download latest Java archive

Download latest Java SE Development Kit 8 release from its official download page or use following commands to download from the shell.

For 64 bit

 # cd /opt/

 # wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u51-b16/jdk-8u51-linux-x64.tar.gz"

 # tar xzf jdk-8u51-linux-x64.tar.gz

For 32 bit

 # cd /opt/

 # wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u51-b16/jdk-8u51-linux-i586.tar.gz"

  # tar xzf jdk-8u51-linux-i586.tar.gz

Note: If the above wget command doesn’t not work for you, watch this example video to download the Java source archive using the terminal.

Install Java with alternatives

After extracting the archive file, use the alternatives command to install it. The alternatives command is available in the chkconfig package.

 # cd /opt/jdk1.8.0_51/

 # alternatives --install /usr/bin/java java /opt/jdk1.8.0_51/bin/java 2

 # alternatives --config java

At this point Java 8 has been successfully installed on your system. We also recommend to setup javac and jar commands path using alternatives:

 # alternatives --install /usr/bin/jar jar /opt/jdk1.8.0_51/bin/jar 2

 # alternatives --install /usr/bin/javac javac /opt/jdk1.8.0_51/bin/javac 2

 # alternatives --set jar /opt/jdk1.8.0_51/bin/jar

 # alternatives --set javac /opt/jdk1.8.0_51/bin/javac

Check installed Java version

Check the installed version of Java using the following command.

root@tecadmin ~# java -version

java version "1.8.0_51"
Java(TM) SE Runtime Environment (build 1.8.0_51-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.51-b03, mixed mode)

Configuring Environment Variables

Most of Java-based applications use environment variables to work. Set the Java environment variables using the following commands:

Setup JAVA_HOME Variable

# export JAVA_HOME=/opt/jdk1.8.0_51
Setup JRE_HOME Variable

# export JRE_HOME=$JAVA_HOME/jre
Setup PATH Variable

# export PATH=$JAVA_HOME/bin:$JRE_HOME/bin:$PATH

Note that the change to the PATH variable put the new Java bin folders first so that they override any existing java/bins in the path. It is a bit sloppy to leave two java/bin folders in your path so you should be advised to clean those up as a separate task.

Also, put all above environment variables in the /etc/environment file for auto loading on system boot.

Concatenating Files And Insert New Line In Between Files

If it were me doing it I'd use sed:

sed -e '$s/$/\n/' -s *.txt > finalfile.txt

In this sed pattern $ has two meanings, firstly it matches the last line number only (as a range of lines to apply a pattern on) and secondly it matches the end of the line in the substitution pattern.

If your version of sed doesn't have -s (process input files separately) you can do it all as a loop though:

for f in *.txt ; do sed -e '$s/$/\n/' $f ; done > finalfile.txt

Minimum and maximum date

From the spec, §15.9.1.1:

A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. A time value may also be NaN, indicating that the Date object does not represent a specific instant of time.

Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values can represent all integers from –9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC.

The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly –100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.

The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0.

The third paragraph being the most relevant. Based on that paragraph, we can get the precise earliest date per spec from new Date(-8640000000000000), which is Tuesday, April 20th, 271,821 BCE (BCE = Before Common Era, e.g., the year -271,821).

Android: Center an image

Technically both answers above are correct, but since you are setting your ImageView to fill_parent instead of wrap_content, the image within is not centered, but the ImageView itself is.

Give your ImageView the attributes:

android:scaleType="centerInside"
android:gravity="center"

The scaleType is really only necessary in this case if the image exceeds the size of the ImageView. You may also want different scaleTypes. In conclusion, android:gravity is what you're looking for in this case, but if your ImageView is set to wrap_content, you should set the ImageView's gravity (android:layout_gravity) to be centered within the parent.

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

Have a look at wxArt2d it is a complete framework for 2d editing and plotting. See the screenshots for more examples.

Some interesting features:

  • Reading and writing SVG and CVG
  • Several views of the same document
  • Changes are updated when idle
  • Optimized drawing of 2d objects

How to create a new variable in a data.frame based on a condition?

One obvious and straightforward possibility is to use "if-else conditions". In that example

x <- c(1, 2, 4)
y <- c(1, 4, 5)
w <- ifelse(x <= 1, "good", ifelse((x >= 3) & (x <= 5), "bad", "fair"))
data.frame(x, y, w)

** For the additional question in the edit** Is that what you expect ?

> d1 <- c("e", "c", "a")
> d2 <- c("e", "a", "b")
> 
> w <- ifelse((d1 == "e") & (d2 == "e"), 1, 
+    ifelse((d1=="a") & (d2 == "b"), 2,
+    ifelse((d1 == "e"), 3, 99)))
>     
> data.frame(d1, d2, w)
  d1 d2  w
1  e  e  1
2  c  a 99
3  a  b  2

If you do not feel comfortable with the ifelse function, you can also work with the if and else statements for such applications.

What is the alternative for ~ (user's home directory) on Windows command prompt?

You can %HOMEDRIVE%%HOMEPATH% for the drive + \docs settings\username or \users\username.

Get bottom and right position of an element

You can use the .position() for this

var link = $(element);
var position = link.position(); //cache the position
var right = $(window).width() - position.left - link.width();
var bottom = $(window).height() - position.top - link.height();

How to change the bootstrap primary color?

This is a very easy solution.

<h4 class="card-header bg-dark text-white text-center">Renew your Membership</h4>

replace the class bg-dark, with bg-custom.

In CSS

.bg-custom {
  background-color: red;
}

How do you do the "therefore" (?) symbol on a Mac or in Textmate?

If you want to do this often, you can create a keybindings file in your Library to map it to a key combination.

In ~/Library create a directory named KeyBindings. Create a file named DefaultKeyBinding.dict inside the directory. You can add key bindings in this format:

{
    "x" = (insertText:, "\U23CF");
    "y" = (insertText:, "hi"); /* warning: this will change 'y' to 'hi'! */
}

The LHS is the key combination you'll hit to enter the character. You can use the following characters to indicate command keys:

@ - Command

~ - Option

^ - Control

You'll need to look up the unicode for your character (in this case, ? is \U2234). So to type this character whenever you typed Control-M, you'd use

"^m" = (insertText:, "\U2234");

You can find more information here: http://www.hcs.harvard.edu/~jrus/site/cocoa-text.html

dplyr change many data types

It's a one-liner with mutate_at:

dat %>% mutate_at("l1", factor) %>% mutate_at("l2", as.numeric)

calculate the mean for each column of a matrix in R

class(mtcars)
my.mean <- unlist(lapply(mtcars, mean)); my.mean



   mpg        cyl       disp         hp       drat         wt       qsec         vs 
 20.090625   6.187500 230.721875 146.687500   3.596563   3.217250  17.848750   0.437500 
        am       gear       carb 
  0.406250   3.687500   2.812500 

How do I remove the horizontal scrollbar in a div?

Hide Scrollbars

step 1:

go to any browser for example Google Chrome
click on keyboard ctrl+Shift+i inspect use open tools Developer

step 2:

Focused mouse on the div and change style div use try this:
 overflow: hidden; /* Hide scrollbars */

now go to add file .css in project and include file

What are the complexity guarantees of the standard containers?

I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).

Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.

Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.

How to restart a single container with docker-compose

Restart Service with docker-compose file

docker-compose -f [COMPOSE_FILE_NAME].yml restart [SERVICE_NAME]

Use Case #1: If the COMPOSE_FILE_NAME is docker-compose.yml and service is worker

docker-compose restart worker

Use Case #2: If the file name is sample.yml and service is worker

docker-compose -f sample.yml restart worker

By default docker-compose looks for the docker-compose.yml if we run the docker-compose command, else we have flag to give specific file name with -f [FILE_NAME].yml

How to match any non white space character except a particular one?

This worked for me using sed [Edit: comment below points out sed doesn't support \s]

[^ ]

while

[^\s] 

didn't

# Delete everything except space and 'g'
echo "ghai ghai" | sed "s/[^\sg]//g"
gg

echo "ghai ghai" | sed "s/[^ g]//g"
g g

Two-dimensional array in Swift

In Swift 4

var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
// [[0, 0], [0, 0], [0, 0]]

Convert RGBA PNG to RGB with PIL

Here's a solution in pure PIL.

def blend_value(under, over, a):
    return (over*a + under*(255-a)) / 255

def blend_rgba(under, over):
    return tuple([blend_value(under[i], over[i], over[3]) for i in (0,1,2)] + [255])

white = (255, 255, 255, 255)

im = Image.open(object.logo.path)
p = im.load()
for y in range(im.size[1]):
    for x in range(im.size[0]):
        p[x,y] = blend_rgba(white, p[x,y])
im.save('/tmp/output.png')

Catch KeyError in Python

I dont think python has a catch :)

try:
    connection = manager.connect("I2Cx")
except Exception, e:
    print e

How to locate the git config file in Mac

The global Git configuration file is stored at $HOME/.gitconfig on all platforms.

However, you can simply open a terminal and execute git config, which will write the appropriate changes to this file. You shouldn't need to manually tweak .gitconfig, unless you particularly want to.

Add click event on div tag using javascript

Try this:

 var div = document.getElementsByClassName('drill_cursor')[0];

 div.addEventListener('click', function (event) {
     alert('Hi!');
 });

Pandas every nth row

There is an even simpler solution to the accepted answer that involves directly invoking df.__getitem__.

df = pd.DataFrame('x', index=range(5), columns=list('abc'))
df

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

For example, to get every 2 rows, you can do

df[::2]

   a  b  c
0  x  x  x
2  x  x  x
4  x  x  x

There's also GroupBy.first/GroupBy.head, you group on the index:

df.index // 2
# Int64Index([0, 0, 1, 1, 2], dtype='int64')

df.groupby(df.index // 2).first()
# Alternatively,
# df.groupby(df.index // 2).head(1)

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x

The index is floor-divved by the stride (2, in this case). If the index is non-numeric, instead do

# df.groupby(np.arange(len(df)) // 2).first()
df.groupby(pd.RangeIndex(len(df)) // 2).first()

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x