Programs & Examples On #Devart

Devart is a software development company specializing in native data access solutions, tools and database tools for the most popular databases, including MS SQL Server, MySQL, Oracle, PostgreSQL, InterBase, Firebird, and SQLite.

Bulk Insert to Oracle using .NET

Finding the linked examples somewhat confusing, I worked out some code that demonstrates a working array insert into a test table (jkl_test). Here's the table:

create table jkl_test (id number(9));

Here is .Net code for a simple Console application that connects to Oracle using ODP.Net and inserts an array of 5 integers:

using Oracle.DataAccess.Client;

namespace OracleArrayInsertExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Open a connection using ODP.Net
            var connection = new OracleConnection("Data Source=YourDatabase; Password=YourPassword; User Id=YourUser");
            connection.Open();

            // Create an insert command
            var command = connection.CreateCommand();
            command.CommandText = "insert into jkl_test values (:ids)";

            // Set up the parameter and provide values
            var param = new OracleParameter("ids", OracleDbType.Int32);
            param.Value = new int[] { 22, 55, 7, 33, 11 };

            // This is critical to the process; in order for the command to 
            // recognize and bind arrays, an array bind count must be specified.
            // Set it to the length of the array.
            command.ArrayBindCount = 5;
            command.Parameters.Add(param);
            command.ExecuteNonQuery();
        }
    }
}

How to hide a <option> in a <select> menu with CSS?

!!! WARNING !!!

Replace the second "IF" by "WHILE" or doesn't work !

jQuery.fn.toggleOption = function( show ) {
    jQuery( this ).toggle( show );
    if( show ) {
        while( jQuery( this ).parent( 'span.toggleOption' ).length )
            jQuery( this ).unwrap( );
    } else {
        jQuery( this ).wrap( '<span class="toggleOption" style="display: none;" />' );
    }
};

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

I resolved this by adding @Transactional to the base/generic Hibernate DAO implementation class (the parent class which implements the saveOrUpdate() method inherited by the DAO I use in the main program), i.e. the @Transactional needs to be specified on the actual class which implements the method. My assumption was instead that if I declared @Transactional on the child class then it included all of the methods that were inherited by the child class. However it seems that the @Transactional annotation only applies to methods implemented within a class and not to methods inherited by a class.

jQuery detect if textarea is empty

You can simply try this and it should work in most cases, feel free to correct me if I am wrong :

function hereLies(obj) { 
  if(obj.val() != "") { 
    //Do this here 
  }
}

Where obj is the object of your textarea.

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<html>_x000D_
<body>_x000D_
<textarea placeholder="Insert text here..." rows="5" cols="12"></textarea>_x000D_
<button id="checkerx">Check</button>_x000D_
<p>Value is not null!</p>_x000D_
_x000D_
<script>_x000D_
  $("p").hide();_x000D_
  $("#checkerx").click(function(){_x000D_
      if($("textarea").val() != ""){_x000D_
        $("p").show();_x000D_
      }_x000D_
      else{_x000D_
       $("p").replaceWith("<p>Value is null!</p>");_x000D_
      }_x000D_
  });_x000D_
_x000D_
</script>_x000D_
</body></html>
_x000D_
_x000D_
_x000D_

how to remove untracked files in Git?

The command for your rescue is git clean.

How do I install cURL on cygwin?

I just ran into this.

If you're not seeing curl in the list (see ibaralf's screenshot), then you may have out-of-date cygwin sources. In one of the screens in cygwin's setup.exe wizard, you have the option to "Install from Internet" or "Install from Local Directory". If you have the "Install from Local Directory" option enabled, then you may not see curl in the list. Switch to "Install from Internet" and select a mirror and then you should see curl.

How to detect if javascript files are loaded?

I don't have a reference for it handy, but script tags are processed in order, and so if you put your $(document).ready(function1) in a script tag after the script tags that define function1, etc., you should be good to go.

<script type='text/javascript' src='...'></script>
<script type='text/javascript' src='...'></script>
<script type='text/javascript'>
$(document).ready(function1);
</script>

Of course, another approach would be to ensure that you're using only one script tag, in total, by combining files as part of your build process. (Unless you're loading the other ones from a CDN somewhere.) That will also help improve the perceived speed of your page.

EDIT: Just realized that I didn't actually answer your question: I don't think there's a cross-browser event that's fired, no. There is if you work hard enough, see below. You can test for symbols and use setTimeout to reschedule:

<script type='text/javascript'>
function fireWhenReady() {
    if (typeof function1 != 'undefined') {
        function1();
    }
    else {
        setTimeout(fireWhenReady, 100);
    }
}
$(document).ready(fireWhenReady);
</script>

...but you shouldn't have to do that if you get your script tag order correct.


Update: You can get load notifications for script elements you add to the page dynamically if you like. To get broad browser support, you have to do two different things, but as a combined technique this works:

function loadScript(path, callback) {

    var done = false;
    var scr = document.createElement('script');

    scr.onload = handleLoad;
    scr.onreadystatechange = handleReadyStateChange;
    scr.onerror = handleError;
    scr.src = path;
    document.body.appendChild(scr);

    function handleLoad() {
        if (!done) {
            done = true;
            callback(path, "ok");
        }
    }

    function handleReadyStateChange() {
        var state;

        if (!done) {
            state = scr.readyState;
            if (state === "complete") {
                handleLoad();
            }
        }
    }
    function handleError() {
        if (!done) {
            done = true;
            callback(path, "error");
        }
    }
}

In my experience, error notification (onerror) is not 100% cross-browser reliable. Also note that some browsers will do both mechanisms, hence the done variable to avoid duplicate notifications.

Refreshing all the pivot tables in my excel workbook with a macro

You have a PivotTables collection on a the VB Worksheet object. So, a quick loop like this will work:

Sub RefreshPivotTables()
    Dim pivotTable As PivotTable
    For Each pivotTable In ActiveSheet.PivotTables
        pivotTable.RefreshTable
    Next
End Sub

Notes from the trenches:

  1. Remember to unprotect any protected sheets before updating the PivotTable.
  2. Save often.
  3. I'll think of more and update in due course... :)

Good luck!

Limit on the WHERE col IN (...) condition

For MS SQL 2016, passing ints into the in, it looks like it can handle close to 38,000 records.

select * from user where userId in (1,2,3,etc)

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

A clearer solution, works in ASP.Net Core 2.1 / 3.1

Filter class

using Microsoft.AspNetCore.Authorization;
// For ASP.NET 2.1
using Microsoft.AspNetCore.Http.Internal;
// For ASP.NET 3.1
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;

public class ReadableBodyStreamAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        // For ASP.NET 2.1
        // context.HttpContext.Request.EnableRewind();
        // For ASP.NET 3.1
        // context.HttpContext.Request.EnableBuffering();
    }
}

In an Controller

[HttpPost]
[ReadableBodyStream]
public string SomePostMethod()
{
    //Note: if you're late and body has already been read, you may need this next line
    //Note2: if "Note" is true and Body was read using StreamReader too, then it may be necessary to set "leaveOpen: true" for that stream.
    HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);

    using (StreamReader stream = new StreamReader(HttpContext.Request.Body))
    {
        string body = stream.ReadToEnd();
        // body = "param=somevalue&param2=someothervalue"
    }
}

How to assign text size in sp value using java code

When the accepted answer doesn't work (for example when dealing with Paint) you can use:

float spTextSize = 12;
float textSize = spTextSize * getResources().getDisplayMetrics().scaledDensity;
textPaint.setTextSize(textSize);

Java 8 NullPointerException in Collectors.toMap

Retaining all questions ids with small tweak

Map<Integer, Boolean> answerMap = 
  answerList.stream()
            .collect(Collectors.toMap(Answer::getId, a -> 
                       Boolean.TRUE.equals(a.getAnswer())));

GridLayout and Row/Column Span Woe

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <GridLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:columnCount="8"
        android:rowCount="7" >

        <TextView
            android:layout_width="50dip"
            android:layout_height="50dip"
            android:layout_columnSpan="2"
            android:layout_rowSpan="2"
            android:background="#a30000"
            android:gravity="center"
            android:text="1"
            android:textColor="@android:color/white"
            android:textSize="20dip" />

        <TextView
            android:layout_width="50dip"
            android:layout_height="25dip"
            android:layout_columnSpan="2"
            android:layout_rowSpan="1"
            android:background="#0c00a3"
            android:gravity="center"
            android:text="2"
            android:textColor="@android:color/white"
            android:textSize="20dip" />

        <TextView
            android:layout_width="25dip"
            android:layout_height="100dip"
            android:layout_columnSpan="1"
            android:layout_rowSpan="4"
            android:background="#00a313"
            android:gravity="center"
            android:text="3"
            android:textColor="@android:color/white"
            android:textSize="20dip" />

        <TextView
            android:layout_width="75dip"
            android:layout_height="50dip"
            android:layout_columnSpan="3"
            android:layout_rowSpan="2"
            android:background="#a29100"
            android:gravity="center"
            android:text="4"
            android:textColor="@android:color/white"
            android:textSize="20dip" />

        <TextView
            android:layout_width="75dip"
            android:layout_height="25dip"
            android:layout_columnSpan="3"
            android:layout_rowSpan="1"
            android:background="#a500ab"
            android:gravity="center"
            android:text="5"
            android:textColor="@android:color/white"
            android:textSize="20dip" />

        <TextView
            android:layout_width="50dip"
            android:layout_height="25dip"
            android:layout_columnSpan="2"
            android:layout_rowSpan="1"
            android:background="#00a9ab"
            android:gravity="center"
            android:text="6"
            android:textColor="@android:color/white"
            android:textSize="20dip" />
    </GridLayout>

</RelativeLayout>

ScreenShot

How generate unique Integers based on GUIDs

The GetHashCode function is specifically designed to create a well distributed range of integers with a low probability of collision, so for this use case is likely to be the best you can do.

But, as I'm sure you're aware, hashing 128 bits of information into 32 bits of information throws away a lot of data, so there will almost certainly be collisions if you have a sufficiently large number of GUIDs.

how to concatenate two dictionaries to create a new one in Python?

d4 = dict(d1.items() + d2.items() + d3.items())

alternatively (and supposedly faster):

d4 = dict(d1)
d4.update(d2)
d4.update(d3)

Previous SO question that both of these answers came from is here.

Using global variables in a function

If I create a global variable in one function, how can I use that variable in another function?

We can create a global with the following function:

def create_global_variable():
    global global_variable # must declare it to be a global first
    # modifications are thus reflected on the module's global scope
    global_variable = 'Foo' 

Writing a function does not actually run its code. So we call the create_global_variable function:

>>> create_global_variable()

Using globals without modification

You can just use it, so long as you don't expect to change which object it points to:

For example,

def use_global_variable():
    return global_variable + '!!!'

and now we can use the global variable:

>>> use_global_variable()
'Foo!!!'

Modification of the global variable from inside a function

To point the global variable at a different object, you are required to use the global keyword again:

def change_global_variable():
    global global_variable
    global_variable = 'Bar'

Note that after writing this function, the code actually changing it has still not run:

>>> use_global_variable()
'Foo!!!'

So after calling the function:

>>> change_global_variable()

we can see that the global variable has been changed. The global_variable name now points to 'Bar':

>>> use_global_variable()
'Bar!!!'

Note that "global" in Python is not truly global - it's only global to the module level. So it is only available to functions written in the modules in which it is global. Functions remember the module in which they are written, so when they are exported into other modules, they still look in the module in which they were created to find global variables.

Local variables with the same name

If you create a local variable with the same name, it will overshadow a global variable:

def use_local_with_same_name_as_global():
    # bad name for a local variable, though.
    global_variable = 'Baz' 
    return global_variable + '!!!'

>>> use_local_with_same_name_as_global()
'Baz!!!'

But using that misnamed local variable does not change the global variable:

>>> use_global_variable()
'Bar!!!'

Note that you should avoid using the local variables with the same names as globals unless you know precisely what you are doing and have a very good reason to do so. I have not yet encountered such a reason.

We get the same behavior in classes

A follow on comment asks:

what to do if I want to create a global variable inside a function inside a class and want to use that variable inside another function inside another class?

Here I demonstrate we get the same behavior in methods as we do in regular functions:

class Foo:
    def foo(self):
        global global_variable
        global_variable = 'Foo'

class Bar:
    def bar(self):
        return global_variable + '!!!'

Foo().foo()

And now:

>>> Bar().bar()
'Foo!!!'

But I would suggest instead of using global variables you use class attributes, to avoid cluttering the module namespace. Also note we don't use self arguments here - these could be class methods (handy if mutating the class attribute from the usual cls argument) or static methods (no self or cls).

concat scope variables into string in angular directive expression

It's not very clear what the problem is and what you are trying to accomplish from the code you posted, but I'll take a stab at it.

In general, I suggest calling a function on ng-click like so:

<a ng-click="navigateToPath()">click me</a>

obj.val1 & obj.val2 should be available on your controller's $scope, you dont need to pass those into a function from the markup.

then, in your controller:

$scope.navigateToPath = function(){
   var path = '/somePath/' + $scope.obj.val1 + '/' + $scope.obj.val2; //dont need the '#'
   $location.path(path)       
}

Returning JSON object as response in Spring Boot

The reason why your current approach doesn't work is because Jackson is used by default to serialize and to deserialize objects. However, it doesn't know how to serialize the JSONObject. If you want to create a dynamic JSON structure, you can use a Map, for example:

@GetMapping
public Map<String, String> sayHello() {
    HashMap<String, String> map = new HashMap<>();
    map.put("key", "value");
    map.put("foo", "bar");
    map.put("aa", "bb");
    return map;
}

This will lead to the following JSON response:

{ "key": "value", "foo": "bar", "aa": "bb" }

This is a bit limited, since it may become a bit more difficult to add child objects. Jackson has its own mechanism though, using ObjectNode and ArrayNode. To use it, you have to autowire ObjectMapper in your service/controller. Then you can use:

@GetMapping
public ObjectNode sayHello() {
    ObjectNode objectNode = mapper.createObjectNode();
    objectNode.put("key", "value");
    objectNode.put("foo", "bar");
    objectNode.put("number", 42);
    return objectNode;
}

This approach allows you to add child objects, arrays, and use all various types.

How do I convert from stringstream to string in C++?

Use the .str()-method:

Manages the contents of the underlying string object.

1) Returns a copy of the underlying string as if by calling rdbuf()->str().

2) Replaces the contents of the underlying string as if by calling rdbuf()->str(new_str)...

Notes

The copy of the underlying string returned by str is a temporary object that will be destructed at the end of the expression, so directly calling c_str() on the result of str() (for example in auto *ptr = out.str().c_str();) results in a dangling pointer...

How can I autoplay a video using the new embed code style for Youtube?

YouTube auto play works only desktop in need to work mobile just make changes in JavaScript. Like

<div id="player"></div>
                    var tag = document.createElement('script');
                    tag.src = "https://www.youtube.com/iframe_api";
                    var firstScriptTag = document.getElementsByTagName('script')[0];
                    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
                    var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      videoId: 'VideoID',
      playerVars: {   
            'autoplay': 1,   
            'rel': 0,
            'showinfo': 0,
            'modestbranding': 1,
            'playsinline': 1,
            'showinfo': 0,
            'rel': 0,
            'controls': 0,
            'color':'white',
            'loop': 1,
            'mute':1,
            // 'origin': 'https://meeranblog24x7.blogspot.com/'
      },
      events: {
        'onReady': onPlayerReady,
        // 'onStateChange': onPlayerStateChange
      }
    });
  }
  function onPlayerReady(event) {
    player.playVideo();
    player.mute();
  }var done = false;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }

 

See More :- YouTube auto play for 5 seconds

Displaying Image in Java

If you want to load/process/display images I suggest you use an image processing framework. Using Marvin, for instance, you can do that easily with just a few lines of source code.

Source code:

public class Example extends JFrame{

    MarvinImagePlugin prewitt           = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.edge.prewitt");
    MarvinImagePlugin errorDiffusion    = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.halftone.errorDiffusion");
    MarvinImagePlugin emboss            = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.color.emboss");

    public Example(){
        super("Example");

        // Layout
        setLayout(new GridLayout(2,2));

        // Load images
        MarvinImage img1 = MarvinImageIO.loadImage("./res/car.jpg");
        MarvinImage img2 = new MarvinImage(img1.getWidth(), img1.getHeight());
        MarvinImage img3 = new MarvinImage(img1.getWidth(), img1.getHeight());
        MarvinImage img4 = new MarvinImage(img1.getWidth(), img1.getHeight());

        // Image Processing plug-ins
        errorDiffusion.process(img1, img2);
        prewitt.process(img1, img3);
        emboss.process(img1, img4);

        // Set panels
        addPanel(img1);
        addPanel(img2);
        addPanel(img3);
        addPanel(img4);

        setSize(560,380);
        setVisible(true);
    }

    public void addPanel(MarvinImage image){
        MarvinImagePanel imagePanel = new MarvinImagePanel();
        imagePanel.setImage(image);
        add(imagePanel);
    }

    public static void main(String[] args) {
        new Example().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Output:

enter image description here

ASP.NET Background image

write code in body tag like this

<body style="background-image: url('Image URL');" >
</body>

Simultaneously merge multiple data.frames in a list

The function eat of my package safejoin has such feature, if you give it a list of data.frames as a second input it will join them recursively to the first input.

Borrowing and extending the accepted answer's data :

x <- data_frame(i = c("a","b","c"), j = 1:3)
y <- data_frame(i = c("b","c","d"), k = 4:6)
z <- data_frame(i = c("c","d","a"), l = 7:9)
z2 <- data_frame(i = c("a","b","c"), l = rep(100L,3),l2 = rep(100L,3)) # for later

# devtools::install_github("moodymudskipper/safejoin")
library(safejoin)
eat(x, list(y,z), .by = "i")
# # A tibble: 3 x 4
#   i         j     k     l
#   <chr> <int> <int> <int>
# 1 a         1    NA     9
# 2 b         2     4    NA
# 3 c         3     5     7

We don't have to take all columns, we can use select helpers from tidyselect and choose (as we start from .x all .x columns are kept):

eat(x, list(y,z), starts_with("l") ,.by = "i")
# # A tibble: 3 x 3
#   i         j     l
#   <chr> <int> <int>
# 1 a         1     9
# 2 b         2    NA
# 3 c         3     7

or remove specific ones:

eat(x, list(y,z), -starts_with("l") ,.by = "i")
# # A tibble: 3 x 3
#   i         j     k
#   <chr> <int> <int>
# 1 a         1    NA
# 2 b         2     4
# 3 c         3     5

If the list is named the names will be used as prefixes :

eat(x, dplyr::lst(y,z), .by = "i")
# # A tibble: 3 x 4
#   i         j   y_k   z_l
#   <chr> <int> <int> <int>
# 1 a         1    NA     9
# 2 b         2     4    NA
# 3 c         3     5     7

If there are column conflicts the .conflict argument allows you to resolve it, for example by taking the first/second one, adding them, coalescing them, or nesting them.

keep first :

eat(x, list(y, z, z2), .by = "i", .conflict = ~.x)
# # A tibble: 3 x 4
#   i         j     k     l
#   <chr> <int> <int> <int>
# 1 a         1    NA     9
# 2 b         2     4    NA
# 3 c         3     5     7

keep last:

eat(x, list(y, z, z2), .by = "i", .conflict = ~.y)
# # A tibble: 3 x 4
#   i         j     k     l
#   <chr> <int> <int> <dbl>
# 1 a         1    NA   100
# 2 b         2     4   100
# 3 c         3     5   100

add:

eat(x, list(y, z, z2), .by = "i", .conflict = `+`)
# # A tibble: 3 x 4
#   i         j     k     l
#   <chr> <int> <int> <dbl>
# 1 a         1    NA   109
# 2 b         2     4    NA
# 3 c         3     5   107

coalesce:

eat(x, list(y, z, z2), .by = "i", .conflict = dplyr::coalesce)
# # A tibble: 3 x 4
#   i         j     k     l
#   <chr> <int> <int> <dbl>
# 1 a         1    NA     9
# 2 b         2     4   100
# 3 c         3     5     7

nest:

eat(x, list(y, z, z2), .by = "i", .conflict = ~tibble(first=.x, second=.y))
# # A tibble: 3 x 4
#   i         j     k l$first $second
#   <chr> <int> <int>   <int>   <int>
# 1 a         1    NA       9     100
# 2 b         2     4      NA     100
# 3 c         3     5       7     100

NA values can be replaced by using the .fill argument.

eat(x, list(y, z), .by = "i", .fill = 0)
# # A tibble: 3 x 4
#   i         j     k     l
#   <chr> <int> <dbl> <dbl>
# 1 a         1     0     9
# 2 b         2     4     0
# 3 c         3     5     7

By default it's an enhanced left_join but all dplyr joins are supported through the .mode argument, fuzzy joins are also supported through the match_fun argument (it's wrapped around the package fuzzyjoin) or giving a formula such as ~ X("var1") > Y("var2") & X("var3") < Y("var4") to the by argument.

BAT file: Open new cmd window and execute a command in there

You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.

What I found out was to use the K switch like this:

start cmd /k echo Hello, World!

start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.

You can also use the /C switch for something similar.

start cmd /C pause

This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.


Use the following in your batch file:

start cmd.exe /c "more-batch-commands-here"

or

start cmd.exe /k "more-batch-commands-here"

/c Carries out the command specified by string and then terminates

/k Carries out the command specified by string but remains

The /c and /k options controls what happens once your command finishes running. With /c the terminal window will close automatically, leaving your desktop clean. With /k the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.

Consult the cmd.exe documentation using cmd /? for more details.

Escaping Commands with White Spaces

The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.

Examples:

Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt

Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"

Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

Source: http://ss64.com/nt/cmd.html

jQuery: value.attr is not a function

Contents of that jQuery object are plain DOM elements, which doesn't respond to jQuery methods (e.g. .attr). You need to wrap the value by $() to turn it into a jQuery object to use it.

    console.info("cat_id: ", $(value).attr('cat_id'));

or just use the DOM method directly

    console.info("cat_id: ", value.getAttribute('cat_id'));

C - determine if a number is prime

Check the modulus of each integer from 2 up to the root of the number you're checking.

If modulus equals zero then it's not prime.

pseudo code:

bool IsPrime(int target)
{
  for (i = 2; i <= root(target); i++)
  {
    if ((target mod i) == 0)
    {
      return false;
    }
  }

  return true;
}

C# try catch continue execution

Do you mean you want to execute code in function1 regardless of whether function2 threw an exception or not? Have you looked at the finally-block? http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx

How do I break out of a loop in Perl?

Additional data (in case you have more questions):

FOO: {
       for my $i ( @listone ){
          for my $j ( @listtwo ){
                 if ( cond( $i,$j ) ){

                    last FOO;  # --->
                                   # |
                 }                 # |
          }                        # |
       }                           # |
 } # <-------------------------------

How to find path of active app.config file?

The first time I realized that the Unit testing project referenced the app.config in that project rather then the app.config associated with my production code project (off course, DOH) I just added a line in the Post Build Event of the Prod project that will copy the app.config to the bin folder of the test project.

Problem solved

I haven't noticed any weird side effects so far, but I am not sure that this is the right solution, but at least it seems to work.

phpMyAdmin is throwing a #2002 cannot log in to the mysql server phpmyadmin

Right-click My Computer -> Manage -> Services Choose "Services" under the "Services and Application" from right pane Then search for the "mysql" Service. When you find it, double click to start that service.

Now you should be able to run and login to PhpMyAdmin

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

For the upgrade scenario specifically an alternative approach might be to have a web service that delivers the current version number and check that instead of downloading the entire apk just to check its version. It would save some bandwidth, be a little more performant (much faster to download than an apk if the whole apk isn't needed most of the time) and much simpler to implement.

In the simplest form you could have a simple text file on your server... http://some-place.com/current-app-version.txt

Inside of that text file have something like

3.1.4

and then download that file and check against the currently installed version.

Building a more advanced solution to that would be to implement a proper web service and have an api call at launch which could return some json, i.e. http://api.some-place.com/versionCheck:

{
    "current_version": "3.1.4"
}

Fix height of a table row in HTML Table

This works, as long as you remove the height attribute from the table.

<table id="content" border="0px" cellspacing="0px" cellpadding="0px">
  <tr><td height='9px' bgcolor="#990000">Upper</td></tr>
  <tr><td height='100px' bgcolor="#990099">Lower</td></tr>
</table>

Looking to understand the iOS UIViewController lifecycle

The methods viewWillLayoutSubviews and viewDidLayoutSubviews aren't mentioned in the diagrams, but these are called between viewWillAppear and viewDidAppear. They can be called multiple times.

Nuget connection attempt failed "Unable to load the service index for source"

Go to -> Tools -> Extensions and Updates and uninstall NuGet package manager.. restart visual studio and reinstall it.... every thing will set to normal

CSS position absolute full width problem

I don't know if this what you want but try to remove overflow: hidden from #wrap

scroll image with continuous scrolling using marquee tag

I think you set the marquee width related to 5 images total width. It works fine

ex: <marquee style="width:700px"></marquee>

Integer value in TextView

just found an advance and most currently used method to set string in textView

textView.setText(String.valueOf(YourIntegerNumber));

How to use a filter in a controller?

Using following sample code we can filter array in angular controller by name. this is based on following description. http://docs.angularjs.org/guide/filter

this.filteredArray = filterFilter(this.array, {name:'Igor'});

JS:

 angular.module('FilterInControllerModule', []).
    controller('FilterController', ['filterFilter', function(filterFilter) {
      this.array = [
        {name: 'Tobias'},
        {name: 'Jeff'},
        {name: 'Brian'},
        {name: 'Igor'},
        {name: 'James'},
        {name: 'Brad'}
      ];
      this.filteredArray = filterFilter(this.array, {name:'Igor'});
    }]);

HTML

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-example96-production</title>
  

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.3/angular.min.js"></script>
  <script src="script.js"></script>
  

  
</head>
<body ng-app="FilterInControllerModule">
    <div ng-controller="FilterController as ctrl">
    <div>
      All entries:
      <span ng-repeat="entry in ctrl.array">{{entry.name}} </span>
    </div>
    <div>
      Filter By Name in angular controller
      <span ng-repeat="entry in ctrl.filteredArray">{{entry.name}} </span>
    </div>
  </div>
</body>
</html>

How to push both value and key into PHP array

Pushing a value into an array automatically creates a numeric key for it.

When adding a key-value pair to an array, you already have the key, you don't need one to be created for you. Pushing a key into an array doesn't make sense. You can only set the value of the specific key in the array.

// no key
array_push($array, $value);
// same as:
$array[] = $value;

// key already known
$array[$key] = $value;

MySql : Grant read only options?

If you want the view to be read only after granting the read permission you can use the ALGORITHM = TEMPTABLE in you view DDL definition.

Eclipse - "Workspace in use or cannot be created, chose a different one."

An additional reason could be that you're pointing to a workspace on a drive that no longer exists, thinking that you're choosing the valid one. For instance, for me the workspace used to exist on the F drive, but now it is on my D drive. Even though I don't have the F drive anymore it is still listed as a workspace I once used during Eclipse startup. When I choose this old workspace Eclipse complains that the workspace is "in use", which is very strange.

How to find all trigger associated with a table with SQL Server?

With this query you can find all Trigger in all tables and all views.

    ;WITH
        TableTrigger
        AS
        (
            Select 
                Object_Kind = 'Table',
                Sys.Tables.Name As TableOrView_Name , 
                Sys.Tables.Object_Id As Table_Object_Id ,
                Sys.Triggers.Name As Trigger_Name, 
                Sys.Triggers.Object_Id As Trigger_Object_Id 
            From Sys.Tables 
            INNER Join Sys.Triggers On ( Sys.Triggers.Parent_id = Sys.Tables.Object_Id )
            Where ( Sys.Tables.Is_MS_Shipped = 0 )
        ),
        ViewTrigger
        AS
        (
            Select 
                Object_Kind = 'View',
                Sys.Views.Name As TableOrView_Name , 
                Sys.Views.Object_Id As TableOrView_Object_Id ,
                Sys.Triggers.Name As Trigger_Name, 
                Sys.Triggers.Object_Id As Trigger_Object_Id 
            From Sys.Views 
            INNER Join Sys.Triggers On ( Sys.Triggers.Parent_id = Sys.Views.Object_Id )
            Where ( Sys.Views.Is_MS_Shipped = 0 )
        ),
        AllObject
        AS
        (
            SELECT * FROM TableTrigger

            Union ALL

            SELECT * FROM ViewTrigger
        )


    Select 
        * 
    From AllObject
    Order By Object_Kind, Table_Object_Id 

How can I solve equations in Python?

How about SymPy? Their solver looks like what you need. Have a look at their source code if you want to build the library yourself…

Getting values from query string in an url using AngularJS $location

In my NodeJS example, I have an url "localhost:8080/Lists/list1.html?x1=y" that I want to traverse and acquire values.

In order to work with $location.search() to get x1=y, I have done a few things

  1. script source to angular-route.js
  2. Inject 'ngRoute' into your app module's dependencies
  3. Config your locationProvider
  4. Add the base tag for $location (if you don't, your search().x1 would return nothing or undefined. Or if the base tag has the wrong info, your browser would not be able to find your files inside script src that your .html needs. Always open page's view source to test your file locations!)
  5. invoke the location service (search())

my list1.js has

    var app = angular.module('NGApp', ['ngRoute']);  //dependencies : ngRoute
    app.config(function ($locationProvider) { //config your locationProvider
         $locationProvider.html5Mode(true).hashPrefix('');
    });

    app.controller('NGCtrl', function ($scope, datasvc, $location) {// inject your location service
        //var val = window.location.href.toString().split('=')[1];
        var val = $location.search().x1;    alert(val);
        $scope.xout = function () {
           datasvc.out(val)
           .then(function (data) {
              $scope.x1 = val;
              $scope.allMyStuffs = data.all;
           });
        };
        $scope.xout();
    });

and my list1.html has

<head>
    <base href=".">
    </head>
<body ng-controller="NGCtrl">
<div>A<input ng-model="x1"/><br/><textarea ng-model="allMyStuffs"/></div>
<script src="../js/jquery-2.1.4.min.js"></script>
<script src="../js/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-route.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/ui-bootstrap-tpls-0.14.3.min.js"></script>
<script src="list1.js"></script>
</body>

Guide: https://code.angularjs.org/1.2.23/docs/guide/$location

Regular Expression to match string starting with a specific word

I'd advise against a simple regular expression approach to this problem. There are too many words that are substrings of other unrelated words, and you'll probably drive yourself crazy trying to overadapt the simpler solutions already provided.

You'll want at least a naive stemming algorithm (try the Porter stemmer; there's available, free code in most languages) to process text first. Keep this processed text and the preprocessed text in two separate space-split arrays. Make sure each non-alphabetical character also gets its own index in this array. Whatever list of words you're filtering, stem them also.

The next step would be to find the array indices which match to your list of stemmed 'stop' words. Remove those from the unprocessed array, and then rejoin on spaces.

This is only slightly more complicated, but will be much more reliable an approach. If you've got any doubts on the value of a more NLP-oriented approach, you might want to do some research into clbuttic mistakes.

Error in Process.Start() -- The system cannot find the file specified

Try to replace your initialization code with:

ProcessStartInfo info 
    = new ProcessStartInfo(@"C:\Program Files\Internet Explorer\iexplore.exe");

Using non full filepath on Process.Start only works if the file is found in System32 folder.

Should I add the Visual Studio .suo and .user files to source control?

By default Microsoft's Visual SourceSafe does not include these files in the source control because they are user-specific settings files. I would follow that model if you're using SVN as source control.

Adding a month to a date in T SQL

Look at DATEADD

SELECT DATEADD(mm, 1, OrderDate)AS TimeFrame

Here's the MSDN

In your case

...WHERE reference_dt = DATEADD(MM,1, myColDate)

How to zero pad a sequence of integers in bash so that all have the same width?

One way without using external process forking is string manipulation, in a generic case it would look like this:

#start value
CNT=1

for [whatever iterative loop, seq, cat, find...];do
   # number of 0s is at least the amount of decimals needed, simple concatenation
   TEMP="000000$CNT"
   # for example 6 digits zero padded, get the last 6 character of the string
   echo ${TEMP:(-6)}
   # increment, if the for loop doesn't provide the number directly
   TEMP=$(( TEMP + 1 ))
done

This works quite well on WSL as well, where forking is a really heavy operation. I had a 110000 files list, using printf "%06d" $NUM took over 1 minute, the solution above ran in about 1 second.

Removing whitespace from strings in Java

One way to handle String manipulations is StringUtils from Apache commons.

String withoutWhitespace = StringUtils.deleteWhitespace(whitespaces);

You can find it here. commons-lang includes lots more and is well supported.

error_reporting(E_ALL) does not produce error

In your php.ini file check for display_errors. I think it is off.

<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

How do I compare two files using Eclipse? Is there any option provided by Eclipse?

Other than using the Navigator/Proj Explorer and choosing files and doing 'Compare With'->'Each other'... I prefer opening both files in Eclipse and using 'Compare With'->'Opened Editor'->(pick the opened tab)... You can get this feature via the AnyEdit eclipse plugin located here (you can use Install Software via Eclipse->Help->Install New Software screen): http://andrei.gmxhome.de/eclipse/

Validate a username and password against Active Directory?

very simple solution using DirectoryServices:

using System.DirectoryServices;

//srvr = ldap server, e.g. LDAP://domain.com
//usr = user name
//pwd = user password
public bool IsAuthenticated(string srvr, string usr, string pwd)
{
    bool authenticated = false;

    try
    {
        DirectoryEntry entry = new DirectoryEntry(srvr, usr, pwd);
        object nativeObject = entry.NativeObject;
        authenticated = true;
    }
    catch (DirectoryServicesCOMException cex)
    {
        //not authenticated; reason why is in cex
    }
    catch (Exception ex)
    {
        //not authenticated due to some other exception [this is optional]
    }

    return authenticated;
}

the NativeObject access is required to detect a bad user/password

EditorFor() and html properties

I solved this by creating an EditorTemplate named String.ascx in my /Views/Shared/EditorTemplates folder:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<% int size = 10;
   int maxLength = 100;
   if (ViewData["size"] != null)
   {
       size = (int)ViewData["size"];
   }
   if (ViewData["maxLength"] != null)
   {
       maxLength = (int)ViewData["maxLength"];
   }
%>
<%= Html.TextBox("", Model, new { Size=size, MaxLength=maxLength }) %>

In my view, I use

<%= Html.EditorFor(model => model.SomeStringToBeEdited, new { size = 15, maxLength = 10 }) %>

Works like a charm for me!

n-grams in python, four, five, six grams?

For four_grams it is already in NLTK, here is a piece of code that can help you toward this:

 from nltk.collocations import *
 import nltk
 #You should tokenize your text
 text = "I do not like green eggs and ham, I do not like them Sam I am!"
 tokens = nltk.wordpunct_tokenize(text)
 fourgrams=nltk.collocations.QuadgramCollocationFinder.from_words(tokens)
 for fourgram, freq in fourgrams.ngram_fd.items():  
       print fourgram, freq

I hope it helps.

Binding arrow keys in JS/jQuery

You can use the keyCode of the arrow keys (37, 38, 39 and 40 for left, up, right and down):

$('.selector').keydown(function (e) {
  var arrow = { left: 37, up: 38, right: 39, down: 40 };

  switch (e.which) {
    case arrow.left:
      //..
      break;
    case arrow.up:
      //..
      break;
    case arrow.right:
      //..
      break;
    case arrow.down:
      //..
      break;
  }
});

Check the above example here.

Check a radio button with javascript

I was able to select (check) a radio input button by using this Javascript code in Firefox 72, within a Web Extension option page to LOAD the value:

var reloadItem = browser.storage.sync.get('reload_mode');
reloadItem.then((response) => {
    if (response["reload_mode"] == "Periodic") {
        document.querySelector('input[name=reload_mode][value="Periodic"]').click();
    } else if (response["reload_mode"] == "Page Bottom") {
        document.querySelector('input[name=reload_mode][value="Page Bottom"]').click();
    } else {
        document.querySelector('input[name=reload_mode][value="Both"]').click();
    }
});

Where the associated code to SAVE the value was:

reload_mode: document.querySelector('input[name=reload_mode]:checked').value

Given HTML like the following:

    <input type="radio" id="periodic" name="reload_mode" value="Periodic">
    <label for="periodic">Periodic</label><br>
    <input type="radio" id="bottom" name="reload_mode" value="Page Bottom">
    <label for="bottom">Page Bottom</label><br>
    <input type="radio" id="both" name="reload_mode" value="Both">
    <label for="both">Both</label></br></br>

T-SQL: Export to new Excel file

Use PowerShell:

$Server = "TestServer"
$Database = "TestDatabase"
$Query = "select * from TestTable"
$FilePath = "C:\OutputFile.csv"

# This will overwrite the file if it already exists.
Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $Server | Export-Csv $FilePath

In my usual cases, all I really need is a CSV file that can be read by Excel. However, if you need an actual Excel file, then tack on some code to convert the CSV file to an Excel file. This answer gives a solution for this, but I've not tested it.

Import Android volley to Android Studio

So Volley has been updated to Android studio build style which makes it harder create a jar. But the recommended way for eclipse was using it as a library project and this goes for android studio as well, but when working in android studio we call this a module. So here is a guide to how do it the way Google wants us to do it. Guide is based on this nice tutorial.

  1. First get latest volley with git (git clone https://android.googlesource.com/platform/frameworks/volley).

  2. In your current project (android studio) click [File] --> [New] -->[Import Module].

  3. Now select the directory where you downloaded Volley to.

  4. Now Android studio might guide you to do the rest but continue guide to verify that everything works correct

  5. Open settings.gradle (find in root) and add (or verify this is included):

    include ':app', ':volley'

  6. Now go to your build.gradle in your project and add the dependency:

    compile project(":volley")

Thats all there is to it, much simpler and easier than compiling a jar and safer than relying on third parties jars or maven uploads.

Sort tuples based on second parameter

And if you are using python 3.X, you may apply the sorted function on the mylist. This is just an addition to the answer that @Sven Marnach has given above.

# using *sort method*
mylist.sort(lambda x: x[1]) 

# using *sorted function*
sorted(mylist, key = lambda x: x[1]) 

Getting the last element of a list

lst[-1] is the best approach, but with general iterables, consider more_itertools.last:

Code

import more_itertools as mit


mit.last([0, 1, 2, 3])
# 3

mit.last(iter([1, 2, 3]))
# 3

mit.last([], "some default")
# 'some default'

How to call a PHP file from HTML or Javascript

You just need to post the form data to the insert php file function, see below :)

class DbConnect
{
// Database login vars
private $dbHostname = '';
private $dbDatabase = '';
private $dbUsername = '';
private $dbPassword = '';
public $db = null;

public function connect()
{

    try
    {
        $this->db = new PDO("mysql:host=".$this->dbHostname.";dbname=".$this->dbDatabase, $this->dbUsername, $this->dbPassword);
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $e)
    {
        echo "It seems there was an error.  Please refresh your browser and try again. ".$e->getMessage();
    }
}

public function store($email)
{
    $stm = $this->db->prepare('INSERT INTO subscribers (email) VALUES ?');
    $stm->bindValue(1, $email);

    return $stm->execute();
}
}

Extract elements of list at odd positions

For the odd positions, you probably want:

>>>> list_ = list(range(10))
>>>> print list_[1::2]
[1, 3, 5, 7, 9]
>>>>

How Do I 'git fetch' and 'git merge' from a Remote Tracking Branch (like 'git pull')

You don't fetch a branch, you fetch an entire remote:

git fetch origin
git merge origin/an-other-branch

jQuery or JavaScript auto click

You haven't provided your javascript code, but the usual cause of this type of issue is not waiting till the page is loaded. Remember that most javascript is executed before the DOM is loaded, so code trying to manipulate it won't work.

To run code after the page has finished loading, use the $(document).ready callback:

$(document).ready(function(){
  $('#some-id').trigger('click');
});

Make a simple fade in animation in Swift?

The problem is that you're trying start the animation too early in the view controller's lifecycle. In viewDidLoad, the view has just been created, and hasn't yet been added to the view hierarchy, so attempting to animate one of its subviews at this point produces bad results.

What you really should be doing is continuing to set the alpha of the view in viewDidLoad (or where you create your views), and then waiting for the viewDidAppear: method to be called. At this point, you can start your animations without any issue.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    UIView.animate(withDuration: 1.5) {
        self.myFirstLabel.alpha = 1.0
        self.myFirstButton.alpha = 1.0
        self.mySecondButton.alpha = 1.0
    }
}

converting epoch time with milliseconds to datetime

those are miliseconds, just divide them by 1000, since gmtime expects seconds ...

time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807/1000.0))

WARNING: UNPROTECTED PRIVATE KEY FILE! when trying to SSH into Amazon EC2 Instance

I also got the same issue, but I fix it by changing my key file permission to 600.

sudo chmod 600 /path/to/my/key.pem

Link : http://stackabuse.com/how-to-fix-warning-unprotected-private-key-file-on-mac-and-linux/

How to remove leading and trailing zeros in a string? Python

Did you try with strip() :

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']
print [item.strip('0') for item in listOfNum]

>>> ['231512-n', '1209123100000-n', 'alphanumeric', 'alphanumeric']

Javascript Audio Play on click

Try the below code snippet

<!doctype html>
<html>
  <head>
    <title>Audio</title>
  </head>
  <body>

    <script>
      function play() {
        var audio = document.getElementById("audio");
        audio.play();
      }
    </script>

    <input type="button" value="PLAY" onclick="play()">
    <audio id="audio" src="http://dev.interactive-creation-works.net/1/1.ogg"></audio>

  </body>
</html>

Make browser window blink in task Bar

                var oldTitle = document.title;
                var msg = "New Popup!";
                var timeoutId = false;

                var blink = function() {
                    document.title = document.title == msg ? oldTitle : msg;//Modify Title in case a popup

                    if(document.hasFocus())//Stop blinking and restore the Application Title
                    {
                        document.title = oldTitle;
                        clearInterval(timeoutId);
                    }                       
                };

                if (!timeoutId) {
                    timeoutId = setInterval(blink, 500);//Initiate the Blink Call
                };//Blink logic 

Initializing IEnumerable<string> In C#

public static IEnumerable<string> GetData()
{
    yield return "1";
    yield return "2";
    yield return "3";
}

IEnumerable<string> m_oEnum = GetData();

Programmatically extract contents of InstallShield setup.exe

The free and open-source program called cabextract will list and extract the contents of not just .cab-files, but Macrovision's archives too:

% cabextract /tmp/QLWREL.EXE
Extracting cabinet: /tmp/QLWREL.EXE
  extracting ikernel.dll
  extracting IsProBENT.tlb
  ....
  extracting IScript.dll
  extracting iKernel.rgs

All done, no errors.

How can I start an Activity from a non-Activity class?

You can define a context for your application say ExampleContext which will hold the context of your application and then use it to instantiate an activity like this:

var intent = new Intent(Application.ApplicationContext, typeof(Activity2));
intent.AddFlags(ActivityFlags.NewTask);
Application.ApplicationContext.StartActivity(intent);

Please bear in mind that this code is written in C# as I use MonoDroid, but I believe it is very similar to Java. For how to create an ApplicationContext look at this thread

This is how I made my Application Class

    [Application]
    public class Application : Android.App.Application, IApplication
    {
        public Application(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer)
        {

        }
        public object MyObject { get; set; }
    }

Forbidden You don't have permission to access /wp-login.php on this server

Make sure the following lines are not in your wp.config

define( 'FORCE_SSL_LOGIN', true );
define( 'FORCE_SSL_ADMIN', true );
define( 'DISALLOW_FILE_EDIT', true );

I got locked out after deactivating iThemes security plugin

Recreate the default website in IIS

Follow these Steps Restore your "Default Website" Website :

  1. create a new website
  2. set "Default Website" as its name
  3. In the Binding section (bottom panel), enter your local IP address in the "IP Address" edit.
  4. Keep the "Host" edit empty

Creating all possible k combinations of n items in C++

Behind the link below is a generic C# answer to this problem: How to format all combinations out of a list of objects. You can limit the results only to the length of k pretty easily.

https://stackoverflow.com/a/40417765/2613458

Date only from TextBoxFor()

If you insist on using the [DisplayFormat], but you are not using MVC4, you can use this:

@Html.TextBoxFor(m => m.EndDate, new { Value = @Html.DisplayFor(m=>m.EndDate), @class="datepicker" })

How to scroll up or down the page to an anchor using jQuery?

You should also consider that the target has a padding and thus use position instead of offset. You can also account for a potential nav bar you don't want to be overlapping the target.

const $navbar = $('.navbar');

$('a[href^="#"]').on('click', function(e) {
    e.preventDefault();

    const scrollTop =
        $($(this).attr('href')).position().top -
        $navbar.outerHeight();

    $('html, body').animate({ scrollTop });
})

Facebook user url by id

The easiest and the most correct (and legal) way is to use graph api.

Just perform the request: http://graph.facebook.com/4

which returns

{
   "id": "4",
   "name": "Mark Zuckerberg",
   "first_name": "Mark",
   "last_name": "Zuckerberg",
   "link": "http://www.facebook.com/zuck",
   "username": "zuck",
   "gender": "male",
   "locale": "en_US"
}

and take the link key.

You can also reduce the traffic by using fields parameter: http://graph.facebook.com/4?fields=link to get only what you need:

{
   "link": "http://www.facebook.com/zuck",
   "id": "4"
}

Creating a new column based on if-elif-else condition

enter image description here

Lets say above one is your original dataframe and you want to add a new column 'old'

If age greater than 50 then we consider as older=yes otherwise False

step 1: Get the indexes of rows whose age greater than 50

row_indexes=df[df['age']>=50].index

step 2: Using .loc we can assign a new value to column

df.loc[row_indexes,'elderly']="yes"

same for age below less than 50

row_indexes=df[df['age']<50].index

df[row_indexes,'elderly']="no"

How to pass parameters to ThreadStart method in Thread?

How about this: (or is it ok to use like this?)

var test = "Hello";
new Thread(new ThreadStart(() =>
{
    try
    {
        //Staff to do
        Console.WriteLine(test);
    }
    catch (Exception ex)
    {
        throw;
    }
})).Start();

How to make a great R reproducible example

Apart of all above answers which I found very interesting, it could sometimes be very easy as it is discussed here :- HOW TO MAKE A MINIMAL REPRODUCIBLE EXAMPLE TO GET HELP WITH R

There are many ways to make a random vector Create a 100 number vector with random values in R rounded to 2 decimals or random matrix in R

mydf1<- matrix(rnorm(20),nrow=20,ncol=5)

Note that sometimes it is very difficult to share a given data because of various reasons such as dimension etc. However, all above answers are great and very important to think and use when one wants to make a reproducible data example. But note that in order to make a data as representative as the original (in case the OP cannot share the original data), it is good to add some information with the data example as (if we call the data mydf1)

class(mydf1)
# this shows the type of the data you have 
dim(mydf1)
# this shows the dimension of your data

Moreover, one should know the type, length and attributes of a data which can be Data structures

#found based on the following 
typeof(mydf1), what it is.
length(mydf1), how many elements it contains.
attributes(mydf1), additional arbitrary metadata.

#If you cannot share your original data, you can str it and give an idea about the structure of your data
head(str(mydf1))

SQLAlchemy create_all() does not create tables

This is probably not the main reason why the create_all() method call doesn't work for people, but for me, the cobbled together instructions from various tutorials have it such that I was creating my db in a request context, meaning I have something like:

# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy

def get_db():
  if 'db' not in g:
    g.db = SQLAlchemy(current_app)
  return g.db

I also have a separate cli command that also does the create_all:

# tasks/db.py
from lib.db import get_db

@current_app.cli.command('init-db')
def init_db():
  db = get_db()
  db.create_all()

I also am using a application factory.

When the cli command is run, a new app context is used, which means a new db is used. Furthermore, in this world, an import model in the init_db method does not do anything, because it may be that your model file was already loaded(and associated with a separate db).

The fix that I came around to was to make sure that the db was a single global reference:

# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy

db = None
def get_db():
  global db
  if not db:
    db = SQLAlchemy(current_app)
  return db

I have not dug deep enough into flask, sqlalchemy, or flask-sqlalchemy to understand if this means that requests to the db from multiple threads are safe, but if you're reading this you're likely stuck in the baby stages of understanding these concepts too.

How to place div in top right hand corner of page

the style is:

<style type="text/css">
 .topcorner{
   position:absolute;
   top:0;
   right:0;
  }
</style>

hope it will work. Thanks

How do I convert an integer to binary in JavaScript?

I used a different approach to come up with something that does this. I've decided to not use this code in my project, but I thought I'd leave it somewhere relevant in case it is useful for someone.

  • Doesn't use bit-shifting or two's complement coercion.
  • You choose the number of bits that comes out (it checks for valid values of '8', '16', '32', but I suppose you could change that)
  • You choose whether to treat it as a signed or unsigned integer.
  • It will check for range issues given the combination of signed/unsigned and number of bits, though you'll want to improve the error handling.
  • It also has the "reverse" version of the function which converts the bits back to the int. You'll need that since there's probably nothing else that will interpret this output :D

_x000D_
_x000D_
function intToBitString(input, size, unsigned) {_x000D_
 if ([8, 16, 32].indexOf(size) == -1) {_x000D_
  throw "invalid params";_x000D_
 }_x000D_
 var min = unsigned ? 0 : - (2 ** size / 2);_x000D_
        var limit = unsigned ? 2 ** size : 2 ** size / 2;_x000D_
 if (!Number.isInteger(input) || input < min || input >= limit) {_x000D_
  throw "out of range or not an int";_x000D_
 }_x000D_
 if (!unsigned) {_x000D_
  input += limit;_x000D_
 }_x000D_
 var binary = input.toString(2).replace(/^-/, '');_x000D_
 return binary.padStart(size, '0');_x000D_
}_x000D_
_x000D_
function bitStringToInt(input, size, unsigned) {_x000D_
 if ([8, 16, 32].indexOf(size) == -1) {_x000D_
  throw "invalid params";_x000D_
 }_x000D_
 input = parseInt(input, 2);_x000D_
 if (!unsigned) {_x000D_
  input -= 2 ** size / 2;_x000D_
 }_x000D_
 return input;_x000D_
}_x000D_
_x000D_
_x000D_
// EXAMPLES_x000D_
_x000D_
var res;_x000D_
console.log("(uint8)10");_x000D_
res = intToBitString(10, 8, true);_x000D_
console.log("intToBitString(res, 8, true)");_x000D_
console.log(res);_x000D_
console.log("reverse:", bitStringToInt(res, 8, true));_x000D_
console.log("---");_x000D_
_x000D_
console.log("(uint8)127");_x000D_
res = intToBitString(127, 8, true);_x000D_
console.log("intToBitString(res, 8, true)");_x000D_
console.log(res);_x000D_
console.log("reverse:", bitStringToInt(res, 8, true));_x000D_
console.log("---");_x000D_
_x000D_
console.log("(int8)127");_x000D_
res = intToBitString(127, 8, false);_x000D_
console.log("intToBitString(res, 8, false)");_x000D_
console.log(res);_x000D_
console.log("reverse:", bitStringToInt(res, 8, false));_x000D_
console.log("---");_x000D_
_x000D_
console.log("(int8)-128");_x000D_
res = intToBitString(-128, 8, false);_x000D_
console.log("intToBitString(res, 8, true)");_x000D_
console.log(res);_x000D_
console.log("reverse:", bitStringToInt(res, 8, true));_x000D_
console.log("---");_x000D_
_x000D_
console.log("(uint16)5000");_x000D_
res = intToBitString(5000, 16, true);_x000D_
console.log("intToBitString(res, 16, true)");_x000D_
console.log(res);_x000D_
console.log("reverse:", bitStringToInt(res, 16, true));_x000D_
console.log("---");_x000D_
_x000D_
console.log("(uint32)5000");_x000D_
res = intToBitString(5000, 32, true);_x000D_
console.log("intToBitString(res, 32, true)");_x000D_
console.log(res);_x000D_
console.log("reverse:", bitStringToInt(res, 32, true));_x000D_
console.log("---");
_x000D_
_x000D_
_x000D_

How can I maintain fragment state when added to the back stack?

I came across this problem in a Fragment containing a map, which has too many setup details to save/reload. My solution was to basically keep this Fragment active the whole time (similar to what @kaushal mentioned).

Say you have current Fragment A and wants to display Fragment B. Summarizing the consequences:

  • replace() - remove Fragment A and replace it with Fragment B. Fragment A will be recreated once brought to the front again
  • add() - (create and) add a Fragment B and it overlap Fragment A, which is still active in the background
  • remove() - can be used to remove Fragment B and return to A. Fragment B will be recreated when called later on

Hence, if you want to keep both Fragments "saved", just toggle them using hide()/show().

Pros: easy and simple method to keep multiple Fragments running
Cons: you use a lot more memory to keep all of them running. May run into problems, e.g. displaying many large bitmaps

How to get public directory?

Use public_path()

For reference:

// Path to the project's root folder    
echo base_path();

// Path to the 'app' folder    
echo app_path();        

// Path to the 'public' folder    
echo public_path();

// Path to the 'storage' folder    
echo storage_path();

// Path to the 'storage/app' folder    
echo storage_path('app');

Vue js error: Component template should contain exactly one root element

You need to wrap all the html into one single element.

<template>
   <div>
        <div class="form-group">
            <label for="avatar" class="control-label">Avatar</label>
            <input type="file" v-on:change="fileChange" id="avatar">
            <div class="help-block">
                Help block here updated 4  ...
            </div>
        </div>

        <div class="col-md-6">
            <input type="hidden" name="avatar_id">
            <img class="avatar" title="Current avatar">
        </div>
   </div>

</template>

<script>
    export default{
        methods: {
            fileChange(){
                console.log('Test of file input change')
            }
        }
    }
</script>

how to change attribute "hidden" in jquery

You can use jquery attr method

$("#delete").attr("hidden",true);

How to get content body from a httpclient call?

The way you are using await/async is poor at best, and it makes it hard to follow. You are mixing await with Task'1.Result, which is just confusing. However, it looks like you are looking at a final task result, rather than the contents.

I've rewritten your function and function call, which should fix your issue:

async Task<string> GetResponseString(string text)
{
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;

    var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
    var contents = await response.Content.ReadAsStringAsync();

    return contents;
}

And your final function call:

Task<string> result = GetResponseString(text);
var finalResult = result.Result;

Or even better:

var finalResult = await GetResponseString(text);

SQL Query Where Date = Today Minus 7 Days

You can subtract 7 from the current date with this:

WHERE datex BETWEEN DATEADD(day, -7, GETDATE()) AND GETDATE()

Using @property versus getters and setters

The short answer is: properties wins hands down. Always.

There is sometimes a need for getters and setters, but even then, I would "hide" them to the outside world. There are plenty of ways to do this in Python (getattr, setattr, __getattribute__, etc..., but a very concise and clean one is:

def set_email(self, value):
    if '@' not in value:
        raise Exception("This doesn't look like an email address.")
    self._email = value

def get_email(self):
    return self._email

email = property(get_email, set_email)

Here's a brief article that introduces the topic of getters and setters in Python.

How do you delete a column by name in data.table?

You can also use set for this, which avoids the overhead of [.data.table in loops:

dt <- data.table( a=letters, b=LETTERS, c=seq(26), d=letters, e=letters )
set( dt, j=c(1L,3L,5L), value=NULL )
> dt[1:5]
   b d
1: A a
2: B b
3: C c
4: D d
5: E e

If you want to do it by column name, which(colnames(dt) %in% c("a","c","e")) should work for j.

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

I am in the same situation pointed out by malcook in his comment: unfortunately the answer by Thierry does not work with ggplot2 version 0.9.3.1.

png("figure_%d.png")
set.seed(2014)
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"))

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

Here it is the first figure:

ggplot A-E, mixed colors

and the second figure:

ggplot ADE, mixed colors

As we can see the colors do not stay fixed, for example E switches from magenta to blu.

As suggested by malcook in his comment and by hadley in his comment the code which uses limits works properly:

ggplot(subdata, aes(x = x, y = y, colour = fCategory)) +       
    geom_point() + 
    scale_colour_discrete(drop=TRUE,
        limits = levels(dataset$fCategory))

gives the following figure, which is correct:

correct ggplot

This is the output from sessionInfo():

R version 3.0.2 (2013-09-25)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] methods   stats     graphics  grDevices utils     datasets  base     

other attached packages:
[1] ggplot2_0.9.3.1

loaded via a namespace (and not attached):
 [1] colorspace_1.2-4   dichromat_2.0-0    digest_0.6.4       grid_3.0.2        
 [5] gtable_0.1.2       labeling_0.2       MASS_7.3-29        munsell_0.4.2     
 [9] plyr_1.8           proto_0.3-10       RColorBrewer_1.0-5 reshape2_1.2.2    
[13] scales_0.2.3       stringr_0.6.2 

Create own colormap using matplotlib and plot color scale

There is an illustrative example of how to create custom colormaps here. The docstring is essential for understanding the meaning of cdict. Once you get that under your belt, you might use a cdict like this:

cdict = {'red':   ((0.0, 1.0, 1.0), 
                   (0.1, 1.0, 1.0),  # red 
                   (0.4, 1.0, 1.0),  # violet
                   (1.0, 0.0, 0.0)), # blue

         'green': ((0.0, 0.0, 0.0),
                   (1.0, 0.0, 0.0)),

         'blue':  ((0.0, 0.0, 0.0),
                   (0.1, 0.0, 0.0),  # red
                   (0.4, 1.0, 1.0),  # violet
                   (1.0, 1.0, 0.0))  # blue
          }

Although the cdict format gives you a lot of flexibility, I find for simple gradients its format is rather unintuitive. Here is a utility function to help generate simple LinearSegmentedColormaps:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors


def make_colormap(seq):
    """Return a LinearSegmentedColormap
    seq: a sequence of floats and RGB-tuples. The floats should be increasing
    and in the interval (0,1).
    """
    seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
    cdict = {'red': [], 'green': [], 'blue': []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict['red'].append([item, r1, r2])
            cdict['green'].append([item, g1, g2])
            cdict['blue'].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap('CustomMap', cdict)


c = mcolors.ColorConverter().to_rgb
rvb = make_colormap(
    [c('red'), c('violet'), 0.33, c('violet'), c('blue'), 0.66, c('blue')])
N = 1000
array_dg = np.random.uniform(0, 10, size=(N, 2))
colors = np.random.uniform(-2, 2, size=(N,))
plt.scatter(array_dg[:, 0], array_dg[:, 1], c=colors, cmap=rvb)
plt.colorbar()
plt.show()

enter image description here


By the way, the for-loop

for i in range(0, len(array_dg)):
  plt.plot(array_dg[i], markers.next(),alpha=alpha[i], c=colors.next())

plots one point for every call to plt.plot. This will work for a small number of points, but will become extremely slow for many points. plt.plot can only draw in one color, but plt.scatter can assign a different color to each dot. Thus, plt.scatter is the way to go.

Error: fix the version conflict (google-services plugin)

Initially, the firebase database was pointing to 11.8.0 .after changing all the related jars to 11.0.4 this issue is resolved at changes the SDK level.

compile 'com.google.firebase:firebase-database:11.0.4'
compile 'com.google.firebase:firebase-messaging:11.0.4'

how to break the _.each function in underscore.js

You cannot break a forEach in underscore, as it emulates EcmaScript 5 native behaviour.

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

The answers to use

pip install --trusted-host pypi.python.org <package>

work. But you'll have to check if there are redirects or caches pip is hitting. On Windows 7 with pip 9.0.1, I had to run

pip install \
  --trusted-host pypi.python.org \
  --trusted-host pypi.org \
  --trusted-host files.pythonhosted.org \
  <package>

You can find these with the verbose flag.

Creating a jQuery object from a big HTML-string

Update:

From jQuery 1.8, we can use $.parseHTML, which will parse the HTML string to an array of DOM nodes. eg:

var dom_nodes = $($.parseHTML('<div><input type="text" value="val" /></div>'));

alert( dom_nodes.find('input').val() );

DEMO


var string = '<div><input type="text" value="val" /></div>';

$('<div/>').html(string).contents();

DEMO

What's happening in this code:

  • $('<div/>') is a fake <div> that does not exist in the DOM
  • $('<div/>').html(string) appends string within that fake <div> as children
  • .contents() retrieves the children of that fake <div> as a jQuery object

If you want to make .find() work then try this:

var string = '<div><input type="text" value="val" /></div>',
    object = $('<div/>').html(string).contents();

alert( object.find('input').val() );

DEMO

PowerShell Connect to FTP server and get files

For retrieving files /folder from FTP via powerShell I wrote some functions, you can get even hidden stuff from FTP.

Example for getting all files which are not hidden in a specific folder:

Get-FtpChildItem -ftpFolderPath "ftp://myHost.com/root/leaf/" -userName "User" -password "pw" -hidden $false -File

Example for getting all folders(also hidden) in a specific folder:

Get-FtpChildItem -ftpFolderPath"ftp://myHost.com/root/leaf/" -userName "User" -password "pw" -Directory

You can just copy the functions from the following module without needing and 3rd library installing: https://github.com/AstralisSomnium/PowerShell-No-Library-Just-Functions/blob/master/FTPModule.ps1

Android SDK Manager gives "Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml" error when selecting repository

Try this solution and it worked. this problem is caused because ADB is unable to connect to the android servers to fetch updates. (If at home try turning off firewall)

  • Goto Android SDK Manager c://android-sdk-windows/ open SDK-Manager
  • Click Settings - Will be asked for a proxy.
  • If have one enter the IP address and the port number. If not turn off your firewall.
  • Check "Force https://... " (to force SDK Manager to use http, not https)

This should work immediately.

java.time.format.DateTimeParseException: Text could not be parsed at index 21

The default parser can parse your input. So you don't need a custom formatter and

String dateTime = "2012-02-22T02:06:58.147Z";
ZonedDateTime d = ZonedDateTime.parse(dateTime);

works as expected.

OpenSSL and error in reading openssl.conf file

Just try to run openssl.exe as administrator.

How do I send an HTML email?

you have to call

msg.saveChanges();

after setting content type.

java.util.zip.ZipException: duplicate entry during packageAllDebugClassesForMultiDex

In my case the mentioned "duplicate entry" error arised after settingmultiDexEnable=true in the build.gradle.

In order to fully resolve the error first of all have a look at Configure Apps with Over 64K Methods (espescially "Configuring Your App for Multidex with Gradle").

Furthermore search for occurences of the class that causes the "duplicate entry" error using ctrl+n in Android Studio. Determine the module and dependency that contains the duplicate and exclude it from build, e.g.:

compile ('org.roboguice:roboguice:2.0') {
    exclude module: 'support-v4'
}

I had to try multiple module labels till it worked. Excluding "support-v4" solves issues related to "java.util.zip.ZipException: duplicate entry: android/support/v4/*"

Having services in React application

or you can inject the class inheritance "http" into React Component

via props object.

  1. update :

    ReactDOM.render(<ReactApp data={app} />, document.getElementById('root'));
    
  2. Simply edit React Component ReactApp like this:

    class ReactApp extends React.Component {
    
    state = {
    
        data: ''
    
    }
    
        render(){
    
        return (
            <div>
            {this.props.data.getData()}      
            </div>
    
        )
        }
    }
    

Removing nan values from an array

Simply fill with

 x = numpy.array([
 [0.99929941, 0.84724713, -0.1500044],
 [-0.79709026, numpy.NaN, -0.4406645],
 [-0.3599013, -0.63565744, -0.70251352]])

x[numpy.isnan(x)] = .555

print(x)

# [[ 0.99929941  0.84724713 -0.1500044 ]
#  [-0.79709026  0.555      -0.4406645 ]
#  [-0.3599013  -0.63565744 -0.70251352]]

JavaScript module pattern with example

Here https://toddmotto.com/mastering-the-module-pattern you can find the pattern thoroughly explained. I would add that the second thing about modular JavaScript is how to structure your code in multiple files. Many folks may advice you here to go with AMD, yet I can say from experience that you will end up on some point with slow page response because of numerous HTTP requests. The way out is pre-compilation of your JavaScript modules (one per file) into a single file following CommonJS standard. Take a look at samples here http://dsheiko.github.io/cjsc/

Does C# have extension properties?

Because I recently needed this, I looked at the source of the answer in:

c# extend class by adding properties

and created a more dynamic version:

public static class ObjectExtenders
{
    static readonly ConditionalWeakTable<object, List<stringObject>> Flags = new ConditionalWeakTable<object, List<stringObject>>();

    public static string GetFlags(this object objectItem, string key)
    {
        return Flags.GetOrCreateValue(objectItem).Single(x => x.Key == key).Value;
    }

    public static void SetFlags(this object objectItem, string key, string value)
    {
        if (Flags.GetOrCreateValue(objectItem).Any(x => x.Key == key))
        {
            Flags.GetOrCreateValue(objectItem).Single(x => x.Key == key).Value = value;
        }
        else
        {
            Flags.GetOrCreateValue(objectItem).Add(new stringObject()
            {
                Key = key,
                Value = value
            });
        }
    }

    class stringObject
    {
        public string Key;
        public string Value;
    }
}

It can probably be improved a lot (naming, dynamic instead of string), I currently use this in CF 3.5 together with a hacky ConditionalWeakTable (https://gist.github.com/Jan-WillemdeBruyn/db79dd6fdef7b9845e217958db98c4d4)

How to auto import the necessary classes in Android Studio with shortcut?

You can also use Eclipse's keyboard shortcuts: just go on preferences > keymap and choose Eclipse from the drop-down menu. And all your Eclipse shortcuts will be used in here.

Get all child elements

Yes, you can use find_elements_by_ to retrieve children elements into a list. See the python bindings here: http://selenium-python.readthedocs.io/locating-elements.html

Example HTML:

<ul class="bar">
    <li>one</li>
    <li>two</li>
    <li>three</li>
</ul>

You can use the find_elements_by_ like so:

parentElement = driver.find_element_by_class_name("bar")
elementList = parentElement.find_elements_by_tag_name("li")

If you want help with a specific case, you can edit your post with the HTML you're looking to get parent and children elements from.

Does Ruby have a string.startswith("abc") built in method?

It's called String#start_with?, not String#startswith: In Ruby, the names of boolean-ish methods end with ? and the words in method names are separated with an _. Not sure where the s went, personally, I'd prefer String#starts_with? over the actual String#start_with?

The request was rejected because no multipart boundary was found in springboot

I was having the same problem while making a POST request from Postman and later I could solve the problem by setting a custom Content-Type with a boundary value set along with it like this.

I thought people can run into similar problem and hence, I'm sharing my solution.

postman

select records from postgres where timestamp is in certain range

Another option to make PostgreSQL use an index for your original query, is to create an index on the expression you are using:

create index arrival_year on reservations ( extract(year from arrival) );

That will open PostgreSQL with the possibility to use an index for

select * 
FROM reservations 
WHERE extract(year from arrival) = 2012;

Note that the expression in the index must be exactly the same expression as used in the where clause to make this work.

How to bundle vendor scripts separately and require them as needed with Webpack?

I am not sure if I fully understand your problem but since I had similar issue recently I will try to help you out.

Vendor bundle.

You should use CommonsChunkPlugin for that. in the configuration you specify the name of the chunk (e.g. vendor), and file name that will be generated (vendor.js).

new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js", Infinity),

Now important part, you have to now specify what does it mean vendor library and you do that in an entry section. One one more item to entry list with the same name as the name of the newly declared chunk (i.e. 'vendor' in this case). The value of that entry should be the list of all the modules that you want to move to vendor bundle. in your case it should look something like:

entry: {
    app: 'entry.js',
    vendor: ['jquery', 'jquery.plugin1']
}

JQuery as global

Had the same problem and solved it with ProvidePlugin. here you are not defining global object but kind of shurtcuts to modules. i.e. you can configure it like that:

new webpack.ProvidePlugin({
    $: "jquery"
})

And now you can just use $ anywhere in your code - webpack will automatically convert that to

require('jquery')

I hope it helped. you can also look at my webpack configuration file that is here

I love webpack, but I agree that the documentation is not the nicest one in the world... but hey.. people were saying same thing about Angular documentation in the begining :)


Edit:

To have entrypoint-specific vendor chunks just use CommonsChunkPlugins multiple times:

new webpack.optimize.CommonsChunkPlugin("vendor-page1", "vendor-page1.js", Infinity),
new webpack.optimize.CommonsChunkPlugin("vendor-page2", "vendor-page2.js", Infinity),

and then declare different extenral libraries for different files:

entry: {
    page1: ['entry.js'],
    page2: ['entry2.js'],
    "vendor-page1": [
        'lodash'
    ],
    "vendor-page2": [
        'jquery'
    ]
},

If some libraries are overlapping (and for most of them) between entry points then you can extract them to common file using same plugin just with different configuration. See this example.

Android Linear Layout - How to Keep Element At Bottom Of View?

I think it will be perfect solution:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <!-- Other views -->
    <Space
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <!-- Target view below -->
    <View
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

</LinearLayout>

How to check if ZooKeeper is running or up from command prompt?

Go to bin directory of Zookeeper and type

./zkServer.sh status

For More info go through below link:

http://www.ibm.com/developerworks/library/bd-zookeeper/

Hope this could help you.

How to get file name from file path in android

Old thread but thought I would update;

 File theFile = .......
 String theName = theFile.getName();  // Get the file name
 String thePath = theFile.getAbsolutePath(); // Get the full

More info can be found here; Android File Class

How to use KeyListener

Here is an SSCCE,

package experiment;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class KeyListenerTester extends JFrame implements KeyListener {

    JLabel label;

    public KeyListenerTester(String s) {
        super(s);
        JPanel p = new JPanel();
        label = new JLabel("Key Listener!");
        p.add(label);
        add(p);
        addKeyListener(this);
        setSize(200, 100);
        setVisible(true);

    }

    @Override
    public void keyTyped(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key typed");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key typed");
        }

    }

    @Override
    public void keyPressed(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key pressed");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key pressed");
        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key Released");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key Released");
        }
    }

    public static void main(String[] args) {
        new KeyListenerTester("Key Listener Tester");
    }
}

Additionally read upon these links : How to Write a Key Listener and How to Use Key Bindings

Detecting installed programs via registry

User-specific settings should be written to HKCU\Software, machine-specific settings to HKLM\Software. Under these keys, structure [software vendor name]\[application name] (e.g. HKLM\Software\Microsoft\Internet Explorer) may be the most common, but that's just a convention, not a law of nature.

Many (most?) applications also add their uninstall entries to HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\[app name], but again, not all applications do this.

These are the most important keys; however, contents of the registry do not have to represent the installed software exactly - maybe the application was installed once, but then was manually deleted, or maybe the uninstaller didn't remove all traces of it. If you want to be sure, check the filesystem to see if the application still exists where its registry entries say it is.

Edit:

If you're a member of the group Administrators, you can check the HKEY_USERS hive - each user's HKCU actually resides there (you'll need to know the user SID, or go through all of them).

Note: As @Brian Ensink says, "installed" is a bit of a vague concept - are we trying to find what the user could run? Some software doesn't even write to the Registry at all: search for "portable apps" to see apps that have been specifically modified to run directly from media (CD/USB) and not to leave any traces on the computer. We may also have to scan the disks, and network disks, and anything the user downloads, and world-accessible Windows shares in the Internet (yes, such things exist legitimately - \\live.sysinternals.com\tools comes to mind). In this direction, there's no real limit of what the user can run, unless prevented by system policies.

Sending Arguments To Background Worker?

You can use the DoWorkEventArgs.Argument property.

A full example (even using an int argument) can be found on Microsoft's site:

warning: implicit declaration of function

If you have the correct headers defined & are using a non GlibC library (such as Musl C) gcc will also throw error: implicit declaration of function when GNU extensions such as malloc_trim are encountered.

The solution is to wrap the extension & the header:

#if defined (__GLIBC__)
  malloc_trim(0);
#endif

No plot window in matplotlib

--pylab no longer works for Jupyter, but fortunately we can add a tweak in the ipython_config.py file to get both pylab as well as autoreload functionalities.

c.InteractiveShellApp.extensions = ['autoreload', 'pylab']
c.InteractiveShellApp.exec_lines = ['%autoreload 2', '%pylab']

When or Why to use a "SET DEFINE OFF" in Oracle Database

Here is the example:

SQL> set define off;
SQL> select * from dual where dummy='&var';

no rows selected

SQL> set define on
SQL> /
Enter value for var: X
old   1: select * from dual where dummy='&var'
new   1: select * from dual where dummy='X'

D
-
X

With set define off, it took a row with &var value, prompted a user to enter a value for it and replaced &var with the entered value (in this case, X).

Installing Google Protocol Buffers on mac

It's a new year and there's a new mismatch between the version of protobuf in Homebrew and the cutting edge release. As of February 2016, brew install protobuf will give you version 2.6.1.

If you want the 3.0 beta release instead, you can install it with:

brew install --devel protobuf

HTML5 image icon to input placeholder

I don't know whether there's a better answer out there as time goes by but this is simple and it works;

input[type='email'] {
  background: white url(images/mail.svg) no-repeat ;
}
input[type='email']:focus {
  background-image: none;
}

Style it up to suit.

Python non-greedy regexes

Using an ungreedy match is a good start, but I'd also suggest that you reconsider any use of .* -- what about this?

groups = re.search(r"\([^)]*\)", x)

Does GPS require Internet?

GPS does not need any kind of internet or wireless connection, but there are technologies like A-GPS that use the mobile network to shorten the time to first fix, or the initial positioning or increase the precision in situations when there is a low satellite visibility.

Android phones tend to use A-GPS. If there is no connectivity, they use pure GPS. They do not override the data network mode. If you deactivated it, the phone won't use any data connection (which is handy if you are abroad, and do not want to pay expensive data roaming).

How can you undo the last git add?

So the real answer to

Can this programmer now unstage his last changes with some magical git command?

is actually: No, you cannot unstage just the last git add.

That is if we interpret the question as in the following situation:

Initial file:

void foo() {

}

main() {
    foo();
}

First change followed by git add:

void foo(int bar) {
    print("$bar");
}

main() {
    foo(1337);
}

Second change followed by git add:

void foo(int bar, String baz) {
    print("$bar $baz");
}

main() {
    foo(1337, "h4x0r");
}

In this case, git reset -p will not help, since its smallest granularity is lines. git doesn't know that about the intermediate state of:

void foo(int bar) {
    print("$bar");
}

main() {
    foo(1337);
}

any more.

How to add custom validation to an AngularJS form?

In AngularJS the best place to define Custom Validation is Cutsom directive. AngularJS provide a ngMessages module.

ngMessages is a directive that is designed to show and hide messages based on the state of a key/value object that it listens on. The directive itself complements error message reporting with the ngModel $error object (which stores a key/value state of validation errors).

For custom form validation One should use ngMessages Modules with custom directive.Here i have a simple validation which will check if number length is less then 6 display an error on screen

 <form name="myform" novalidate>
                <table>
                    <tr>
                        <td><input name='test' type='text' required  ng-model='test' custom-validation></td>
                        <td ng-messages="myform.test.$error"><span ng-message="invalidshrt">Too Short</span></td>
                    </tr>
                </table>
            </form>

Here is how to create custom validation directive

angular.module('myApp',['ngMessages']);
        angular.module('myApp',['ngMessages']).directive('customValidation',function(){
            return{
            restrict:'A',
            require: 'ngModel',
            link:function (scope, element, attr, ctrl) {// 4th argument contain model information 

            function validationError(value) // you can use any function and parameter name 
                {
                 if (value.length > 6) // if model length is greater then 6 it is valide state
                 {
                 ctrl.$setValidity('invalidshrt',true);
                 }
                 else
                 {
                 ctrl.$setValidity('invalidshrt',false) //if less then 6 is invalide
                 }

                 return value; //return to display  error 
                }
                ctrl.$parsers.push(validationError); //parsers change how view values will be saved in the model
            }
            };
        });

$setValidity is inbuilt function to set model state to valid/invalid

Javascript counting number of objects in object

Try Demo Here

var list ={}; var count= Object.keys(list).length;

Reading/Writing a MS Word file in PHP

2007 might be a bit complicated as well.

The .docx format is a zip file that contains a few folders with other files in them for formatting and other stuff.

Rename a .docx file to .zip and you'll see what I mean.

So if you can work within zip files in PHP, you should be on the right path.

Access multiple viewchildren using @viewchild

Use @ViewChildren from @angular/core to get a reference to the components

template

<div *ngFor="let v of views">
    <customcomponent #cmp></customcomponent>
</div>

component

import { ViewChildren, QueryList } from '@angular/core';

/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components:QueryList<CustomComponent>;

ngAfterViewInit(){
    // print array of CustomComponent objects
    console.log(this.components.toArray());
}

l?i?v?e? ?d?e?m?o?

How to convert a Collection to List?

@Kunigami: I think you may be mistaken about Guava's newArrayList method. It does not check whether the Iterable is a List type and simply return the given List as-is. It always creates a new list:

@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(Iterable<? extends E> elements) {
  checkNotNull(elements); // for GWT
  // Let ArrayList's sizing logic work, if possible
  return (elements instanceof Collection)
      ? new ArrayList<E>(Collections2.cast(elements))
      : newArrayList(elements.iterator());
}

List files with certain extensions with ls and grep

Use regular expressions with find:

find . -iregex '.*\.\(mp3\|mp4\|exe\)' -printf '%f\n'

If you're piping the filenames:

find . -iregex '.*\.\(mp3\|mp4\|exe\)' -printf '%f\0' | xargs -0 dosomething

This protects filenames that contain spaces or newlines.

OS X find only supports alternation when the -E (enhanced) option is used.

find -E . -regex '.*\.(mp3|mp4|exe)'

Convert List<String> to List<Integer> directly

You can use the Lambda functions of Java 8 to achieve this without looping

    String string = "1, 2, 3, 4";
    List<Integer> list = Arrays.asList(string.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());

What is the python keyword "with" used for?

In python the with keyword is used when working with unmanaged resources (like file streams). It is similar to the using statement in VB.NET and C#. It allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running, even if exceptions are thrown. It provides 'syntactic sugar' for try/finally blocks.

From Python Docs:

The with statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.

The with statement is a control-flow structure whose basic structure is:

with expression [as variable]:
    with-block

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has __enter__() and __exit__() methods).

Update fixed VB callout per Scott Wisniewski's comment. I was indeed confusing with with using.

Requery a subform from another form?

All your controls are belong to us!

Fionnuala answered this correctly but skimmers like me would find it easy to miss the point.

You don't refresh the subFORM you refresh the subform CONTROL. In fact, if you check with allforms() the subForm isn't even loaded as far as access is concerned.

On the main form look at the label the subform wizard provided or select the subform by clicking once or on the border around it and look at the "caption" in the "Other" tab in properties. That's the name you use for requerying, not the name of the form that appears in the navigation panel.

In my case I had a subform called frmInvProdSub and I tried for many hours to figure out why Access didn't think it existed. I gave up, deleted the form and re-created it. The very last step is telling it what you want to call the control so I called it frmInvProdSub and finished the wizard. Then I tried and voila, it worked!

When I looked at the form name in the navigation window I realized I'd forgotten to put "Sub" in the name! That's when it clicked. The CONTROL is called frmInvProdSub, not the form and using the control name works.

Of course if both names are identical then you didn't have this problem lol.

How to run mvim (MacVim) from Terminal?

If you have homeBrew installed, this is all you have to do:

brew install macvim
brew linkapps

Then type mvim in your terminal to run MacVim.

Rotate camera in Three.js with mouse

This might serve as a good starting point for moving/rotating/zooming a camera with mouse/trackpad (in typescript):

class CameraControl {
    zoomMode: boolean = false
    press: boolean = false
    sensitivity: number = 0.02

    constructor(renderer: Three.Renderer, public camera: Three.PerspectiveCamera, updateCallback:() => void){
        renderer.domElement.addEventListener('mousemove', event => {
            if(!this.press){ return }

            if(event.button == 0){
                camera.position.y -= event.movementY * this.sensitivity
                camera.position.x -= event.movementX * this.sensitivity        
            } else if(event.button == 2){
                camera.quaternion.y -= event.movementX * this.sensitivity/10
                camera.quaternion.x -= event.movementY * this.sensitivity/10
            }

            updateCallback()
        })    

        renderer.domElement.addEventListener('mousedown', () => { this.press = true })
        renderer.domElement.addEventListener('mouseup', () => { this.press = false })
        renderer.domElement.addEventListener('mouseleave', () => { this.press = false })

        document.addEventListener('keydown', event => {
            if(event.key == 'Shift'){
                this.zoomMode = true
            }
        })

        document.addEventListener('keyup', event => {
            if(event.key == 'Shift'){
                this.zoomMode = false
            }
        })

        renderer.domElement.addEventListener('mousewheel', event => {
            if(this.zoomMode){ 
                camera.fov += event.wheelDelta * this.sensitivity
                camera.updateProjectionMatrix()
            } else {
                camera.position.z += event.wheelDelta * this.sensitivity
            }

            updateCallback()
        })
    }
}

drop it in like:

this.cameraControl = new CameraControl(renderer, camera, () => {
    // you might want to rerender on camera update if you are not rerendering all the time
    window.requestAnimationFrame(() => renderer.render(scene, camera))
})

Controls:

  • move while [holding mouse left / single finger on trackpad] to move camera in x/y plane
  • move [mouse wheel / two fingers on trackpad] to move up/down in z-direction
  • hold shift + [mouse wheel / two fingers on trackpad] to zoom in/out via increasing/decreasing field-of-view
  • move while holding [mouse right / two fingers on trackpad] to rotate the camera (quaternion)

Additionally:

If you want to kinda zoom by changing the 'distance' (along yz) instead of changing field-of-view you can bump up/down camera's position y and z while keeping the ratio of position's y and z unchanged like:

// in mousewheel event listener in zoom mode
const ratio = camera.position.y / camera.position.z
camera.position.y += (event.wheelDelta * this.sensitivity * ratio)
camera.position.z += (event.wheelDelta * this.sensitivity)

Increment value in mysql update query

You could also just do this:

mysql_query("
    UPDATE member_profile 
    SET points = points + 1
    WHERE user_id = '".$userid."'
");

Get filename and path from URI from mediastore

Things are complicated now especially after API level 29 Android Q. This is how you should get filename from the content Uri

        public static String getNameFromContentUri(Context context, Uri contentUri){  
                            Cursor returnCursor = context.getContentResolver().query(contentUri, null, null, null, null);
                            int nameColumnIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                            returnCursor.moveToFirst();
                            String fileName = returnCursor.getString(nameColumnIndex);
                            return fileName;}

and this is how you get full path of the Content Uri for all android versions

public static String getFullPathFromContentUri(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if ("com.android.externalstorage.documents".equals(uri.getAuthority())) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                   Cursor cursor = null;
                   final String column = "_data";
                   final String[] projection = {
                      column
                    };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

private static String getDataColumn(Context context, Uri uri, String selection,
                                 String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu

TL;DR: To access newer versions of mysql/mariadb after as the root user, after a new install, you need to be in a root shell (ie sudo mysql -u root, or mysql -u root inside a shell started by su - or sudo -i first)


Having just done the same upgrade, on Ubuntu, I had the same issue.

What was odd was that

sudo /usr/bin/mysql_secure_installation

Would accept my password, and allow me to set it, but I couldn't log in as root via the mysql client

I had to start mariadb with

sudo mysqld_safe --skip-grant-tables

to get access as root, whilst all the other users could still access fine.

Looking at the mysql.user table I noticed for root the plugin column is set to unix_socket whereas all other users it is set to 'mysql_native_password'. A quick look at this page: https://mariadb.com/kb/en/mariadb/unix_socket-authentication-plugin/ explains that the Unix Socket enables logging in by matching uid of the process running the client with that of the user in the mysql.user table. In other words to access mariadb as root you have to be logged in as root.

Sure enough restarting my mariadb daemon with authentication required I can login as root with

sudo mysql -u root -p

or

sudo su -
mysql -u root -p

Having done this I thought about how to access without having to do the sudo, which is just a matter of running these mysql queries

GRANT ALL PRIVILEGES on *.* to 'root'@'localhost' IDENTIFIED BY '<password>';
FLUSH PRIVILEGES;

(replacing <password> with your desired mysql root password). This enabled password logins for the root user.

Alternatively running the mysql query:

UPDATE mysql.user SET plugin = 'mysql_native_password' WHERE user = 'root' AND plugin = 'unix_socket';
FLUSH PRIVILEGES;

Will change the root account to use password login without changing the password, but this may leave you with a mysql/mariadb install with no root password on it.

After either of these you need to restarting mysql/mariadb:

sudo service mysql restart

And voila I had access from my personal account via mysql -u root -p

PLEASE NOTE THAT DOING THIS IS REDUCING SECURITY Presumably the MariaDB developers have opted to have root access work like this for a good reason.

Thinking about it I'm quite happy to have to sudo mysql -u root -p so I'm switching back to that, but I thought I'd post my solution as I couldn't find one elsewhere.

printf formatting (%d versus %u)

%u is used for unsigned integer. Since the memory address given by the signed integer address operator %d is -12, to get this value in unsigned integer, Compiler returns the unsigned integer value for this address.

How to open CSV file in R when R says "no such file or directory"?

To throw out another option, why not set the working directory (preferably via a script) to the desktop using setwd('C:\John\Desktop') and then read the files just using file names

Getting only hour/minute of datetime

Try this:

String hourMinute = DateTime.Now.ToString("HH:mm");

Now you will get the time in hour:minute format.

GROUP BY and COUNT in PostgreSQL

WITH uniq AS (
        SELECT DISTINCT posts.id as post_id
        FROM posts
        JOIN votes ON votes.post_id = posts.id
        -- GROUP BY not needed anymore
        -- GROUP BY posts.id
        )
SELECT COUNT(*)
FROM uniq;

How to use sed to replace only the first occurrence in a file?

A possible solution here might be to tell the compiler to include the header without it being mentioned in the source files. IN GCC there are these options:

   -include file
       Process file as if "#include "file"" appeared as the first line of
       the primary source file.  However, the first directory searched for
       file is the preprocessor's working directory instead of the
       directory containing the main source file.  If not found there, it
       is searched for in the remainder of the "#include "..."" search
       chain as normal.

       If multiple -include options are given, the files are included in
       the order they appear on the command line.

   -imacros file
       Exactly like -include, except that any output produced by scanning
       file is thrown away.  Macros it defines remain defined.  This
       allows you to acquire all the macros from a header without also
       processing its declarations.

       All files specified by -imacros are processed before all files
       specified by -include.

Microsoft's compiler has the /FI (forced include) option.

This feature can be handy for some common header, like platform configuration. The Linux kernel's Makefile uses -include for this.

How do I convert an ANSI encoded file to UTF-8 with Notepad++?

Regarding this part:

When I convert it to UTF-8 without bom and close file, the file is again ANSI when I reopen.

The easiest solution is to avoid the problem entirely by properly configuring Notepad++.

Try Settings -> Preferences -> New document -> Encoding -> choose UTF-8 without BOM, and check Apply to opened ANSI files.

notepad++ UTF-8 apply to opened ANSI files

That way all the opened ANSI files will be treated as UTF-8 without BOM.

For explanation what's going on, read the comments below this answer.

To fully learn about Unicode and UTF-8, read this excellent article from Joel Spolsky.

How to read Data from Excel sheet in selenium webdriver

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

String FilePath = "/home/lahiru/Desktop/Sample.xls";
FileInputStream fs = new FileInputStream(FilePath);
Workbook wb = Workbook.getWorkbook(fs);

String <variable> = sh.getCell("A2").getContents();

What are carriage return, linefeed, and form feed?

Carriage return and line feed are also references to typewriters, in that the with a small push on the handle on the left side of the carriage (the place where the paper goes), the paper would rotate a small amount around the cylinder, advancing the document one line. If you had finished typing one line, and wanted to continue on to the next, you pushed harder, both advancing a line and sliding the carriage all the way to the right, then resuming typing left to right again as the carriage traveled with each keystroke. Needless to say, word-wrap was the default setting for all word processing of the era. P:D

How to solve java.lang.OutOfMemoryError trouble in Android

If you are getting this Error java.lang.OutOfMemoryError this is the most common problem occurs in Android. This error is thrown by the Java Virtual Machine (JVM) when an object cannot be allocated due to lack of memory space.

Try this android:hardwareAccelerated="false" , android:largeHeap="true"in your manifest.xml file under application like this:

<application
  android:name=".MyApplication"
  android:allowBackup="true"
  android:icon="@mipmap/ic_launcher"
  android:label="@string/app_name"
  android:theme="@style/AppTheme"
  android:hardwareAccelerated="false"
  android:largeHeap="true" />

VS2010 command prompt gives error: Cannot determine the location of the VS Common Tools folder

The same problem occurred for me when iI was installing a python library and it said unable to find the path of Visual Studio 2008/10. I have change the PATH from environmental variables. So to change it you the following process can be adopted: Start=> Computer=>Properties=>Advance System Settings=>Environment Variables=>System Variables. Here you will find path variable. If some already some path is set then you can use semicolon(;) to add the given path "C:\Windows\System32" else directly add the same.

How to mock void methods with Mockito

Adding another answer to the bunch (no pun intended)...

You do need to call the doAnswer method if you can't\don't want to use spy's. However, you don't necessarily need to roll your own Answer. There are several default implementations. Notably, CallsRealMethods.

In practice, it looks something like this:

doAnswer(new CallsRealMethods()).when(mock)
        .voidMethod(any(SomeParamClass.class));

Or:

doAnswer(Answers.CALLS_REAL_METHODS.get()).when(mock)
        .voidMethod(any(SomeParamClass.class));

How do I remove the top margin in a web page?

_x000D_
_x000D_
body{_x000D_
margin:0;_x000D_
padding:0;_x000D_
}
_x000D_
<span>Example</span>
_x000D_
_x000D_
_x000D_

Adding System.Web.Script reference in class library

The ScriptIgnoreAttribute class is in the System.Web.Extensions.dll assembly (Located under Assemblies > Framework in the VS Reference Manager). You have to add a reference to that assembly in your class library project.

You can find this information at top of the MSDN page for the ScriptIgnoreAttribute class.

How do we control web page caching, across all browsers?

you can use location block for set individual file instead of whole app get caching in IIS

 <location path="index.html">
    <system.webServer>
      <httpProtocol>
        <customHeaders>
          <add name="Cache-Control" value="no-cache" />
        </customHeaders>
      </httpProtocol>
    </system.webServer>
  </location>

How to access nested elements of json object using getJSONArray method

I would also try it this way

1) Create the Java Beans from the JSON schema

2) Use JSON parser libraries to avoid any sort of exception

3) Cast the parse result to the Java object that was created from the initial JSON schema.

Below is an example JSON Schema"

{
  "USD" : {"15m" : 478.68, "last" : 478.68, "buy" : 478.55, "sell" : 478.68,  "symbol" : "$"},
  "JPY" : {"15m" : 51033.99, "last" : 51033.99, "buy" : 51020.13, "sell" : 51033.99,  "symbol" : "¥"},
}

Code

public class Container { 

    private JPY JPY;

    private USD USD;

    public JPY getJPY ()
    {
        return JPY;
    }

    public void setJPY (JPY JPY)
    {
        this.JPY = JPY;
    }

    public USD getUSD ()
    {
        return USD;
    }

    public void setUSD (USD USD)
    {
        this.USD = USD;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [JPY = "+JPY+", USD = "+USD+"]";
    }
}


public class JPY
{    
    @SerializedName("15m")
    private double  fifitenM;

    private String symbol;

    private double last;

    private double sell;

    private double buy;

    public double getFifitenM ()
    {
        return fifitenM;
    }

    public void setFifitenM (double fifitenM)
    {
        this.fifitenM = fifitenM;
    }

    public String getSymbol ()
    {
        return symbol;
    }

    public void setSymbol (String symbol)
    {
        this.symbol = symbol;
    }

    public double getLast ()
    {
        return last;
    }

    public void setLast (double last)
    {
        this.last = last;
    }

    public double getSell ()
    {
        return sell;
    }

    public void setSell (double sell)
    {
        this.sell = sell;
    }

    public double getBuy ()
    {
        return buy;
    }

    public void setBuy (double buy)
    {
        this.buy = buy;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [15m = "+fifitenM+", symbol = "+symbol+", last = "+last+", sell = "+sell+", buy = "+buy+"]";
    }
}


public class USD
{
    @SerializedName("15m")
    private double fifitenM;

    private String symbol;

    private double last;

    private double sell;

    private double buy;

    public double getFifitenM ()
    {
        return fifitenM;
    }

    public void setFifitenM (double fifitenM)
    {
        this.fifitenM = fifitenM;
    }

    public String getSymbol ()
    {
        return symbol;
    }

    public void setSymbol (String symbol)
    {
        this.symbol = symbol;
    }

    public double getLast ()
    {
        return last;
    }

    public void setLast (double last)
    {
        this.last = last;
    }

    public double getSell ()
    {
        return sell;
    }

    public void setSell (double sell)
    {
        this.sell = sell;
    }

    public double getBuy ()
    {
        return buy;
    }

    public void setBuy (double buy)
    {
        this.buy = buy;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [15m = "+fifitenM+", symbol = "+symbol+", last = "+last+", sell = "+sell+", buy = "+buy+"]";
    }
}


public class MainMethd
{
    public static void main(String[] args) throws JsonIOException, JsonSyntaxException, FileNotFoundException {
        // TODO Auto-generated method stub
        JsonParser parser = new JsonParser();
        Object obj = parser.parse(new FileReader("C:\\Users\\Documents\\file.json"));
        String res = obj.toString();
        Gson gson = new Gson();
        Container container = new Container();
        container = gson.fromJson(res, Container.class);
        System.out.println(container.getUSD());
        System.out.println("Sell Price : " + container.getUSD().getSymbol()+""+ container.getUSD().getSell());
        System.out.println("Buy Price : " + container.getUSD().getSymbol()+""+ container.getUSD().getBuy());
    }

}

Output from the main method is:

ClassPojo [15m = 478.68, symbol = $, last = 478.68, sell = 478.68, buy = 478.55]

Sell Price : $478.68

Buy Price : $478.55

Hope this helps.

How to send PUT, DELETE HTTP request in HttpURLConnection?

public  HttpURLConnection getHttpConnection(String url, String type){
        URL uri = null;
        HttpURLConnection con = null;
        try{
            uri = new URL(url);
            con = (HttpURLConnection) uri.openConnection();
            con.setRequestMethod(type); //type: POST, PUT, DELETE, GET
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setConnectTimeout(60000); //60 secs
            con.setReadTimeout(60000); //60 secs
            con.setRequestProperty("Accept-Encoding", "Your Encoding");
            con.setRequestProperty("Content-Type", "Your Encoding");
        }catch(Exception e){
            logger.info( "connection i/o failed" );
        }
        return con;
}

Then in your code :

public void yourmethod(String url, String type, String reqbody){
    HttpURLConnection con = null;
    String result = null;
    try {
        con = conUtil.getHttpConnection( url , type);
    //you can add any request body here if you want to post
         if( reqbody != null){  
                con.setDoInput(true);
                con.setDoOutput(true);
                DataOutputStream out = new  DataOutputStream(con.getOutputStream());
                out.writeBytes(reqbody);
                out.flush();
                out.close();
            }
        con.connect();
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String temp = null;
        StringBuilder sb = new StringBuilder();
        while((temp = in.readLine()) != null){
            sb.append(temp).append(" ");
        }
        result = sb.toString();
        in.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        logger.error(e.getMessage());
    }
//result is the response you get from the remote side
}

How to change the button text of <input type="file" />?

You can simply add some css trick. you don't need javascript or more input files and i keep existing value attribute. you need to add only css. you can try this solution.

_x000D_
_x000D_
.btn-file-upload{_x000D_
     width: 187px;_x000D_
     position:relative;_x000D_
 }_x000D_
_x000D_
.btn-file-upload:after{_x000D_
    content:  attr(value);_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    bottom: 0;    _x000D_
    width: 48%;_x000D_
    background: #795548;_x000D_
    color: white;_x000D_
    border-radius: 2px;_x000D_
    text-align: center;_x000D_
    font-size: 12px;_x000D_
    line-height: 2;_x000D_
 }
_x000D_
<input type="file" class="btn-file-upload" value="Uploadfile" />
_x000D_
_x000D_
_x000D_

How to preview a part of a large pandas DataFrame, in iPython notebook?

This line will allow you to see all rows (up to the number that you set as 'max_rows') without any rows being hidden by the dots ('.....') that normally appear between head and tail in the print output.

pd.options.display.max_rows = 500

What is the difference between prefix and postfix operators?

The function returns before i is incremented because you are using a post-fix operator (++). At any rate, the increment of i is not global - only to respective function. If you had used a pre-fix operator, it would be 11 and then decremented to 10.

So you then return i as 10 and decrement it in the printf function, which shows 9 not 10 as you think.

What is the correct way to represent null XML elements?

There is no canonical answer, since XML fundamentally has no null concept. But I assume you want Xml/Object mapping (since object graphs have nulls); so the answer for you is "whatever your tool uses". If you write handling, that means whatever you prefer. For tools that use XML Schema, xsi:nil is the way to go. For most mappers, omitting matching element/attribute is the way to do it.

Write a file on iOS

Your code is working at my end, i have just tested it. Where are you checking your changes? Use Documents directory path. To get path -

NSLog(@"%@",documentsDirectory);

and copy path from console and then open finder and press Cmd+shift+g and paste path here and then open your file

How to getElementByClass instead of GetElementById with JavaScript?

My solution:

First create "<style>" tags with an ID.

<style id="YourID">
    .YourClass {background-color:red}
</style>

Then, I create a function in JavaScript like this:

document.getElementById('YourID').innerHTML = '.YourClass {background-color:blue}'

Worked like a charm for me.

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

You want a parameter source:

Set<Integer> ids = ...;

MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("ids", ids);

List<Foo> foo = getJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",
     parameters, getRowMapper());

This only works if getJdbcTemplate() returns an instance of type NamedParameterJdbcTemplate

Classes vs. Modules in VB.NET

Modules are VB counterparts to C# static classes. When your class is designed solely for helper functions and extension methods and you don't want to allow inheritance and instantiation, you use a Module.

By the way, using Module is not really subjective and it's not deprecated. Indeed you must use a Module when it's appropriate. .NET Framework itself does it many times (System.Linq.Enumerable, for instance). To declare an extension method, it's required to use Modules.

How do I restart a program based on user input?

I create this program:

import pygame, sys, time, random, easygui

skier_images = ["skier_down.png", "skier_right1.png",
                "skier_right2.png", "skier_left2.png",
                "skier_left1.png"]

class SkierClass(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("skier_down.png")
        self.rect = self.image.get_rect()
        self.rect.center = [320, 100]
        self.angle = 0

    def turn(self, direction):
        self.angle = self.angle + direction
        if self.angle < -2:  self.angle = -2
        if self.angle >  2:  self.angle =  2
        center = self.rect.center
        self.image = pygame.image.load(skier_images[self.angle])
        self.rect = self.image.get_rect()
        self.rect.center = center
        speed = [self.angle, 6 - abs(self.angle) * 2]
        return speed

    def move(self,speed):
        self.rect.centerx = self.rect.centerx + speed[0]
        if self.rect.centerx < 20:  self.rect.centerx = 20
        if self.rect.centerx > 620: self.rect.centerx = 620

class ObstacleClass(pygame.sprite.Sprite):
    def __init__(self,image_file, location, type):
        pygame.sprite.Sprite.__init__(self)
        self.image_file = image_file
        self.image = pygame.image.load(image_file)
        self.location = location
        self.rect = self.image.get_rect()
        self.rect.center = location
        self.type = type
        self.passed = False

    def scroll(self, t_ptr):
        self.rect.centery = self.location[1] - t_ptr

def create_map(start, end):
    obstacles = pygame.sprite.Group()
    gates = pygame.sprite.Group()
    locations = []
    for i in range(10):
        row = random.randint(start, end)
        col = random.randint(0, 9)
        location = [col * 64 + 20, row * 64 + 20]
        if not (location in locations) :
            locations.append(location)
            type = random.choice(["tree", "flag"])
            if type == "tree": img = "skier_tree.png"
            elif type == "flag": img = "skier_flag.png"
            obstacle = ObstacleClass(img, location, type)
            obstacles.add(obstacle)
    return obstacles

def animate():
    screen.fill([255,255,255])
    pygame.display.update(obstacles.draw(screen))
    screen.blit(skier.image, skier.rect)
    screen.blit(score_text, [10,10])
    pygame.display.flip()

def updateObstacleGroup(map0, map1):
    obstacles = pygame.sprite.Group()
    for ob in map0:  obstacles.add(ob)
    for ob in map1:  obstacles.add(ob)
    return obstacles

pygame.init()
screen = pygame.display.set_mode([640,640])
clock = pygame.time.Clock()
skier = SkierClass()
speed = [0, 6]
map_position = 0
points = 0
map0 = create_map(20, 29)
map1 = create_map(10, 19)
activeMap = 0
obstacles = updateObstacleGroup(map0, map1)
font = pygame.font.Font(None, 50)

a = True

while a:
    clock.tick(30)
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                speed = skier.turn(-1)
            elif event.key == pygame.K_RIGHT:
                speed = skier.turn(1)
    skier.move(speed)
    map_position += speed[1]

    if map_position >= 640 and activeMap == 0:
        activeMap = 1
        map0 = create_map(20, 29)
        obstacles = updateObstacleGroup(map0, map1)
    if map_position >=1280 and activeMap == 1:
        activeMap = 0
        for ob in map0:
            ob.location[1] = ob.location[1] - 1280
        map_position = map_position - 1280
        map1 = create_map(10, 19)
        obstacles = updateObstacleGroup(map0, map1)
    for obstacle in obstacles:
        obstacle.scroll(map_position)

    hit = pygame.sprite.spritecollide(skier, obstacles, False)
    if hit:
        if hit[0].type == "tree" and not hit[0].passed:
            skier.image = pygame.image.load("skier_crash.png")
            easygui.msgbox(msg="OOPS!!!")
            choice = easygui.buttonbox("Do you want to play again?", "Play", ("Yes", "No"))
            if choice == "Yes":
                skier = SkierClass()
                speed = [0, 6]
                map_position = 0
                points = 0
                map0 = create_map(20, 29)
                map1 = create_map(10, 19)
                activeMap = 0
                obstacles = updateObstacleGroup(map0, map1)
            elif choice == "No":
                a = False
                quit()
        elif hit[0].type == "flag" and not hit[0].passed:
            points += 10
            obstacles.remove(hit[0])

    score_text = font.render("Score: " + str(points), 1, (0, 0, 0))
    animate()

Link: https://docs.google.com/document/d/1U8JhesA6zFE5cG1Ia3OsTL6dseq0Vwv_vuIr3kqJm4c/edit

JQUERY: Uncaught Error: Syntax error, unrecognized expression

Try this (ES5)

console.log($("#" +  d));

ES6

console.log($(`#${d}`));

Write HTML file using Java

I would highly recommend you use a very simple templating language such as Freemarker

Drop all tables whose names begin with a certain string

You may need to modify the query to include the owner if there's more than one in the database.

DECLARE @cmd varchar(4000)
DECLARE cmds CURSOR FOR
SELECT 'drop table [' + Table_Name + ']'
FROM INFORMATION_SCHEMA.TABLES
WHERE Table_Name LIKE 'prefix%'

OPEN cmds
WHILE 1 = 1
BEGIN
    FETCH cmds INTO @cmd
    IF @@fetch_status != 0 BREAK
    EXEC(@cmd)
END
CLOSE cmds;
DEALLOCATE cmds

This is cleaner than using a two-step approach of generate script plus run. But one advantage of the script generation is that it gives you the chance to review the entirety of what's going to be run before it's actually run.

I know that if I were going to do this against a production database, I'd be as careful as possible.

Edit Code sample fixed.

How to enable bulk permission in SQL Server

Try GRANT ADMINISTER BULK OPERATIONS TO [server_login]. It is a server level permission, not a database level. This has fixed a similar issue for me in that past (using OPENROWSET I believe).

Passing a 2D array to a C++ function

Surprised that no one mentioned this yet, but you can simply template on anything 2D supporting [][] semantics.

template <typename TwoD>
void myFunction(TwoD& myArray){
     myArray[x][y] = 5;
     etc...
}

// call with
double anArray[10][10];
myFunction(anArray);

It works with any 2D "array-like" datastructure, such as std::vector<std::vector<T>>, or a user defined type to maximize code reuse.

How to replace url parameter with javascript/jquery?

The following solution combines other answers and handles some special cases:

  • The parameter does not exist in the original url
  • The parameter is the only parameter
  • The parameter is first or last
  • The new parameter value is the same as the old
  • The url ends with a ? character
  • \b ensures another parameter ending with paramName won't be matched

Solution:

function replaceUrlParam(url, paramName, paramValue)
{
    if (paramValue == null) {
        paramValue = '';
    }
    var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
    if (url.search(pattern)>=0) {
        return url.replace(pattern,'$1' + paramValue + '$2');
    }
    url = url.replace(/[?#]$/,'');
    return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}

Known limitations:

Force GUI update from UI Thread

If you only need to update a couple controls, .update() is sufficient.

btnMyButton.BackColor=Color.Green; // it eventually turned green, after a delay
btnMyButton.Update(); // after I added this, it turned green quickly

Get resultset from oracle stored procedure

CREATE OR REPLACE PROCEDURE SP_Invoices(p_nameClient IN CHAR)
AS
BEGIN       
    FOR c_invoice IN 
    (
       SELECT CodeInvoice, NameClient FROM Invoice
       WHERE NameClient = p_nameClient
    )
    LOOP
        dbms_output.put_line('Code Invoice: ' || c_invoice.CodeInvoice);
        dbms_output.put_line('Name Client : ' ||  c_invoice.NameClient );
    END LOOP;
END;

Executing in SQL Developer:

BEGIN
    SP_Invoices('Perico de los palotes');
END;
-- Or:
EXEC SP_Invoices('Perico de los palotes');

Output:

> Code Invoice: 1 
> Name Client : Perico de los palotes
> Code Invoice: 2 
> Name Client : Perico de los palotes

Select rows with same id but different value in another column

Select A.ARIDNR,A.LIEFNR
from Table A
join Table B
on A.ARIDNR = B.ARIDNR
and A.LIEFNR<> B.LIEFNR
group by A.ARIDNR,A.LIEFNR

How do I set specific environment variables when debugging in Visual Studio?

You can set it at Property > Configuration Properties > Debugging > Environment enter image description here

Search for a particular string in Oracle clob column

You can just CAST your CLOB value into a VARCHAR value and make your querie like a

The controller for path was not found or does not implement IController

I've found it.

When a page, that is located inside an area, wants to access a controller that is located outside of this area (such as a shared layout page or a certain page inside a different area), the area of this controller needs to be added. Since the common controller is not in a specific area but part of the main project, you have to leave area empty:

@Html.Action("MenuItems", "Common", new {area="" }) 

The above needs to be added to all of the actions and actionlinks since the layout page is shared throughout the various areas.

It's exactly the same problem as here: ASP.NET MVC Areas with shared layout

Edit: To be clear, this is marked as the answer because it was the answer for my problem. The above answers might solve the causes that trigger the same error.

Passing a string array as a parameter to a function java

look at familiar main method which takes string array as param

Amazon S3 boto - how to create a folder?

Although you can create a folder by appending "/" to your folder_name. Under the hood, S3 maintains flat structure unlike your regular NFS.

var params = {
            Bucket : bucketName,
            Key : folderName + "/"
        };
s3.putObject(params, function (err, data) {});

Java: how to add image to Jlabel?

the shortest code is :

JLabel jLabelObject = new JLabel();
jLabelObject.setIcon(new ImageIcon(stringPictureURL));

stringPictureURL is PATH of image .

What are the git concepts of HEAD, master, origin?

HEAD is not the latest revision, it's the current revision. Usually, it's the latest revision of the current branch, but it doesn't have to be.

master is a name commonly given to the main branch, but it could be called anything else (or there could be no main branch).

origin is a name commonly given to the main remote. remote is another repository that you can pull from and push to. Usually it's on some server, like github.

Best practice for REST token-based authentication with JAX-RS and Jersey

How token-based authentication works

In token-based authentication, the client exchanges hard credentials (such as username and password) for a piece of data called token. For each request, instead of sending the hard credentials, the client will send the token to the server to perform authentication and then authorization.

In a few words, an authentication scheme based on tokens follow these steps:

  1. The client sends their credentials (username and password) to the server.
  2. The server authenticates the credentials and, if they are valid, generate a token for the user.
  3. The server stores the previously generated token in some storage along with the user identifier and an expiration date.
  4. The server sends the generated token to the client.
  5. The client sends the token to the server in each request.
  6. The server, in each request, extracts the token from the incoming request. With the token, the server looks up the user details to perform authentication.
    • If the token is valid, the server accepts the request.
    • If the token is invalid, the server refuses the request.
  7. Once the authentication has been performed, the server performs authorization.
  8. The server can provide an endpoint to refresh tokens.

Note: The step 3 is not required if the server has issued a signed token (such as JWT, which allows you to perform stateless authentication).

What you can do with JAX-RS 2.0 (Jersey, RESTEasy and Apache CXF)

This solution uses only the JAX-RS 2.0 API, avoiding any vendor specific solution. So, it should work with JAX-RS 2.0 implementations, such as Jersey, RESTEasy and Apache CXF.

It is worthwhile to mention that if you are using token-based authentication, you are not relying on the standard Java EE web application security mechanisms offered by the servlet container and configurable via application's web.xml descriptor. It's a custom authentication.

Authenticating a user with their username and password and issuing a token

Create a JAX-RS resource method which receives and validates the credentials (username and password) and issue a token for the user:

@Path("/authentication")
public class AuthenticationEndpoint {

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response authenticateUser(@FormParam("username") String username, 
                                     @FormParam("password") String password) {

        try {

            // Authenticate the user using the credentials provided
            authenticate(username, password);

            // Issue a token for the user
            String token = issueToken(username);

            // Return the token on the response
            return Response.ok(token).build();

        } catch (Exception e) {
            return Response.status(Response.Status.FORBIDDEN).build();
        }      
    }

    private void authenticate(String username, String password) throws Exception {
        // Authenticate against a database, LDAP, file or whatever
        // Throw an Exception if the credentials are invalid
    }

    private String issueToken(String username) {
        // Issue a token (can be a random String persisted to a database or a JWT token)
        // The issued token must be associated to a user
        // Return the issued token
    }
}

If any exceptions are thrown when validating the credentials, a response with the status 403 (Forbidden) will be returned.

If the credentials are successfully validated, a response with the status 200 (OK) will be returned and the issued token will be sent to the client in the response payload. The client must send the token to the server in every request.

When consuming application/x-www-form-urlencoded, the client must to send the credentials in the following format in the request payload:

username=admin&password=123456

Instead of form params, it's possible to wrap the username and the password into a class:

public class Credentials implements Serializable {

    private String username;
    private String password;

    // Getters and setters omitted
}

And then consume it as JSON:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response authenticateUser(Credentials credentials) {

    String username = credentials.getUsername();
    String password = credentials.getPassword();

    // Authenticate the user, issue a token and return a response
}

Using this approach, the client must to send the credentials in the following format in the payload of the request:

{
  "username": "admin",
  "password": "123456"
}

Extracting the token from the request and validating it

The client should send the token in the standard HTTP Authorization header of the request. For example:

Authorization: Bearer <token-goes-here>

The name of the standard HTTP header is unfortunate because it carries authentication information, not authorization. However, it's the standard HTTP header for sending credentials to the server.

JAX-RS provides @NameBinding, a meta-annotation used to create other annotations to bind filters and interceptors to resource classes and methods. Define a @Secured annotation as following:

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured { }

The above defined name-binding annotation will be used to decorate a filter class, which implements ContainerRequestFilter, allowing you to intercept the request before it be handled by a resource method. The ContainerRequestContext can be used to access the HTTP request headers and then extract the token:

@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

    private static final String REALM = "example";
    private static final String AUTHENTICATION_SCHEME = "Bearer";

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Get the Authorization header from the request
        String authorizationHeader =
                requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

        // Validate the Authorization header
        if (!isTokenBasedAuthentication(authorizationHeader)) {
            abortWithUnauthorized(requestContext);
            return;
        }

        // Extract the token from the Authorization header
        String token = authorizationHeader
                            .substring(AUTHENTICATION_SCHEME.length()).trim();

        try {

            // Validate the token
            validateToken(token);

        } catch (Exception e) {
            abortWithUnauthorized(requestContext);
        }
    }

    private boolean isTokenBasedAuthentication(String authorizationHeader) {

        // Check if the Authorization header is valid
        // It must not be null and must be prefixed with "Bearer" plus a whitespace
        // The authentication scheme comparison must be case-insensitive
        return authorizationHeader != null && authorizationHeader.toLowerCase()
                    .startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " ");
    }

    private void abortWithUnauthorized(ContainerRequestContext requestContext) {

        // Abort the filter chain with a 401 status code response
        // The WWW-Authenticate header is sent along with the response
        requestContext.abortWith(
                Response.status(Response.Status.UNAUTHORIZED)
                        .header(HttpHeaders.WWW_AUTHENTICATE, 
                                AUTHENTICATION_SCHEME + " realm=\"" + REALM + "\"")
                        .build());
    }

    private void validateToken(String token) throws Exception {
        // Check if the token was issued by the server and if it's not expired
        // Throw an Exception if the token is invalid
    }
}

If any problems happen during the token validation, a response with the status 401 (Unauthorized) will be returned. Otherwise the request will proceed to a resource method.

Securing your REST endpoints

To bind the authentication filter to resource methods or resource classes, annotate them with the @Secured annotation created above. For the methods and/or classes that are annotated, the filter will be executed. It means that such endpoints will only be reached if the request is performed with a valid token.

If some methods or classes do not need authentication, simply do not annotate them:

@Path("/example")
public class ExampleResource {

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response myUnsecuredMethod(@PathParam("id") Long id) {
        // This method is not annotated with @Secured
        // The authentication filter won't be executed before invoking this method
        ...
    }

    @DELETE
    @Secured
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response mySecuredMethod(@PathParam("id") Long id) {
        // This method is annotated with @Secured
        // The authentication filter will be executed before invoking this method
        // The HTTP request must be performed with a valid token
        ...
    }
}

In the example shown above, the filter will be executed only for the mySecuredMethod(Long) method because it's annotated with @Secured.

Identifying the current user

It's very likely that you will need to know the user who is performing the request agains your REST API. The following approaches can be used to achieve it:

Overriding the security context of the current request

Within your ContainerRequestFilter.filter(ContainerRequestContext) method, a new SecurityContext instance can be set for the current request. Then override the SecurityContext.getUserPrincipal(), returning a Principal instance:

final SecurityContext currentSecurityContext = requestContext.getSecurityContext();
requestContext.setSecurityContext(new SecurityContext() {

        @Override
        public Principal getUserPrincipal() {
            return () -> username;
        }

    @Override
    public boolean isUserInRole(String role) {
        return true;
    }

    @Override
    public boolean isSecure() {
        return currentSecurityContext.isSecure();
    }

    @Override
    public String getAuthenticationScheme() {
        return AUTHENTICATION_SCHEME;
    }
});

Use the token to look up the user identifier (username), which will be the Principal's name.

Inject the SecurityContext in any JAX-RS resource class:

@Context
SecurityContext securityContext;

The same can be done in a JAX-RS resource method:

@GET
@Secured
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod(@PathParam("id") Long id, 
                         @Context SecurityContext securityContext) {
    ...
}

And then get the Principal:

Principal principal = securityContext.getUserPrincipal();
String username = principal.getName();

Using CDI (Context and Dependency Injection)

If, for some reason, you don't want to override the SecurityContext, you can use CDI (Context and Dependency Injection), which provides useful features such as events and producers.

Create a CDI qualifier:

@Qualifier
@Retention(RUNTIME)
@Target({ METHOD, FIELD, PARAMETER })
public @interface AuthenticatedUser { }

In your AuthenticationFilter created above, inject an Event annotated with @AuthenticatedUser:

@Inject
@AuthenticatedUser
Event<String> userAuthenticatedEvent;

If the authentication succeeds, fire the event passing the username as parameter (remember, the token is issued for a user and the token will be used to look up the user identifier):

userAuthenticatedEvent.fire(username);

It's very likely that there's a class that represents a user in your application. Let's call this class User.

Create a CDI bean to handle the authentication event, find a User instance with the correspondent username and assign it to the authenticatedUser producer field:

@RequestScoped
public class AuthenticatedUserProducer {

    @Produces
    @RequestScoped
    @AuthenticatedUser
    private User authenticatedUser;

    public void handleAuthenticationEvent(@Observes @AuthenticatedUser String username) {
        this.authenticatedUser = findUser(username);
    }

    private User findUser(String username) {
        // Hit the the database or a service to find a user by its username and return it
        // Return the User instance
    }
}

The authenticatedUser field produces a User instance that can be injected into container managed beans, such as JAX-RS services, CDI beans, servlets and EJBs. Use the following piece of code to inject a User instance (in fact, it's a CDI proxy):

@Inject
@AuthenticatedUser
User authenticatedUser;

Note that the CDI @Produces annotation is different from the JAX-RS @Produces annotation:

Be sure you use the CDI @Produces annotation in your AuthenticatedUserProducer bean.

The key here is the bean annotated with @RequestScoped, allowing you to share data between filters and your beans. If you don't wan't to use events, you can modify the filter to store the authenticated user in a request scoped bean and then read it from your JAX-RS resource classes.

Compared to the approach that overrides the SecurityContext, the CDI approach allows you to get the authenticated user from beans other than JAX-RS resources and providers.

Supporting role-based authorization

Please refer to my other answer for details on how to support role-based authorization.

Issuing tokens

A token can be:

  • Opaque: Reveals no details other than the value itself (like a random string)
  • Self-contained: Contains details about the token itself (like JWT).

See details below:

Random string as token

A token can be issued by generating a random string and persisting it to a database along with the user identifier and an expiration date. A good example of how to generate a random string in Java can be seen here. You also could use:

Random random = new SecureRandom();
String token = new BigInteger(130, random).toString(32);

JWT (JSON Web Token)

JWT (JSON Web Token) is a standard method for representing claims securely between two parties and is defined by the RFC 7519.

It's a self-contained token and it enables you to store details in claims. These claims are stored in the token payload which is a JSON encoded as Base64. Here are some claims registered in the RFC 7519 and what they mean (read the full RFC for further details):

  • iss: Principal that issued the token.
  • sub: Principal that is the subject of the JWT.
  • exp: Expiration date for the token.
  • nbf: Time on which the token will start to be accepted for processing.
  • iat: Time on which the token was issued.
  • jti: Unique identifier for the token.

Be aware that you must not store sensitive data, such as passwords, in the token.

The payload can be read by the client and the integrity of the token can be easily checked by verifying its signature on the server. The signature is what prevents the token from being tampered with.

You won't need to persist JWT tokens if you don't need to track them. Althought, by persisting the tokens, you will have the possibility of invalidating and revoking the access of them. To keep the track of JWT tokens, instead of persisting the whole token on the server, you could persist the token identifier (jti claim) along with some other details such as the user you issued the token for, the expiration date, etc.

When persisting tokens, always consider removing the old ones in order to prevent your database from growing indefinitely.

Using JWT

There are a few Java libraries to issue and validate JWT tokens such as:

To find some other great resources to work with JWT, have a look at http://jwt.io.

Handling token revocation with JWT

If you want to revoke tokens, you must keep the track of them. You don't need to store the whole token on server side, store only the token identifier (that must be unique) and some metadata if you need. For the token identifier you could use UUID.

The jti claim should be used to store the token identifier on the token. When validating the token, ensure that it has not been revoked by checking the value of the jti claim against the token identifiers you have on server side.

For security purposes, revoke all the tokens for a user when they change their password.

Additional information

  • It doesn't matter which type of authentication you decide to use. Always do it on the top of a HTTPS connection to prevent the man-in-the-middle attack.
  • Take a look at this question from Information Security for more information about tokens.
  • In this article you will find some useful information about token-based authentication.

Difference between fprintf, printf and sprintf?

sprintf: Writes formatted data to a character string in memory instead of stdout

Syntax of sprintf is:

#include <stdio.h>
int sprintf (char *string, const char *format
[,item [,item]…]);

Here,

String refers to the pointer to a buffer in memory where the data is to be written.

Format refers to pointer to a character string defining the format.

Each item is a variable or expression specifying the data to write.

The value returned by sprintf is greater than or equal to zero if the operation is successful or in other words the number of characters written, not counting the terminating null character is returned and returns a value less than zero if an error occurred.

printf: Prints to stdout

Syntax for printf is:

printf format [argument]…

The only difference between sprintf() and printf() is that sprintf() writes data into a character array, while printf() writes data to stdout, the standard output device.

Hide the browse button on a input type=file

You may just without making the element hidden, simply make it transparent by making its opacity to 0.

Making the input file hidden will make it STOP working. So DON'T DO THAT..

Here you can find an example for a transparent Browse operation;

Overriding the java equals() method - not working?

Another fast solution that saves boilerplate code is Lombok EqualsAndHashCode annotation. It is easy, elegant and customizable. And does not depends on the IDE. For example;

import lombok.EqualsAndHashCode;

@EqualsAndHashCode(of={"errorNumber","messageCode"}) // Will only use this fields to generate equals.
public class ErrorMessage{

    private long        errorNumber;
    private int         numberOfParameters;
    private Level       loggingLevel;
    private String      messageCode;

See the options avaliable to customize which fields to use in the equals. Lombok is avalaible in maven. Just add it with provided scope:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.14.8</version>
    <scope>provided</scope>
</dependency>

Linking static libraries to other static libraries

If you are using Visual Studio then yes, you can do this.

The library builder tool that comes with Visual Studio allows you to join libraries together on the command line. I don't know of any way to do this in the visual editor though.

lib.exe /OUT:compositelib.lib  lib1.lib lib2.lib

How do you check if a certain index exists in a table?

AdaTheDEV, I used your syntax and created the following and why.

Problem: Process runs once a quarter taking an hour due to missing index.

Correction: Alter query process or Procedure to check for index and create it if missing... Same code is placed at the end of the query and procedure to remove index since it is not needed but quarterly. Showing Only drop syntax here

-- drop the index 
begin

  IF EXISTS (SELECT *  FROM sys.indexes  WHERE name='Index_Name' 
    AND object_id = OBJECT_ID('[SchmaName].[TableName]'))
  begin
    DROP INDEX [Index_Name] ON [SchmaName].[TableName];
  end

end

pip install from git repo branch

You used the egg files install procedure. This procedure supports installing over git, git+http, git+https, git+ssh, git+git and git+file. Some of these are mentioned.

It's good you can use branches, tags, or hashes to install.

@Steve_K noted it can be slow to install with "git+" and proposed installing via zip file:

pip install https://github.com/user/repository/archive/branch.zip

Alternatively, I suggest you may install using the .whl file if this exists.

pip install https://github.com/user/repository/archive/branch.whl

It's pretty new format, newer than egg files. It requires wheel and setuptools>=0.8 packages. You can find more in here.

Change span text?

document.getElementById("serverTime").innerHTML = ...;

Is it possible to remove inline styles with jQuery?

$("#element").css({ display: "none" });

At first I tried to remove inline style in css, but it does not work and new style like display: none will be overwritten. But in JQuery it works like this.

Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()

If you are running your application just on localhost and it is not yet live, I believe it is very difficult to send mail using this.

Once you put your application online, I believe that this problem should be automatically solved. By the way,ini_set() helps you to change the values in php.ini during run time.

This is the same question as Failed to connect to mailserver at "localhost" port 25

also check this php mail function not working

What is a semaphore?

I've created the visualization which should help to understand the idea. Semaphore controls access to a common resource in a multithreading environment. enter image description here

ExecutorService executor = Executors.newFixedThreadPool(7);

Semaphore semaphore = new Semaphore(4);

Runnable longRunningTask = () -> {
    boolean permit = false;
    try {
        permit = semaphore.tryAcquire(1, TimeUnit.SECONDS);
        if (permit) {
            System.out.println("Semaphore acquired");
            Thread.sleep(5);
        } else {
            System.out.println("Could not acquire semaphore");
        }
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    } finally {
        if (permit) {
            semaphore.release();
        }
    }
};

// execute tasks
for (int j = 0; j < 10; j++) {
    executor.submit(longRunningTask);
}
executor.shutdown();

Output

Semaphore acquired
Semaphore acquired
Semaphore acquired
Semaphore acquired
Could not acquire semaphore
Could not acquire semaphore
Could not acquire semaphore

Sample code from the article