Programs & Examples On #Mux

How to rename a pane in tmux?

For those scripting tmux, there is a command called rename-window so e.g.

tmux rename-window -t <window> <newname>

Ubuntu apt-get unable to fetch packages

I have been fighting the same thing for a while.

after all the research, this is the best solution.....

add the following to your resolve.conf file /etc/resolv.conf
nameserver 8.8.8.8
nameserver 8.8.4.4

https://serverfault.com/questions/717226/ubuntu14-04-unable-to-apt-get-update/771826#771826

Import cycle not allowed

You may have imported,

project/controllers/base

inside the

project/controllers/routes

You have already imported before. That's not supported.

What steps are needed to stream RTSP from FFmpeg?

You can use FFserver to stream a video using RTSP.

Just change console syntax to something like this:

ffmpeg -i space.mp4 -vcodec libx264 -tune zerolatency -crf 18 http://localhost:1234/feed1.ffm

Create a ffserver.config file (sample) where you declare HTTPPort, RTSPPort and SDP stream. Your config file could look like this (some important stuff might be missing):

HTTPPort 1234
RTSPPort 1235

<Feed feed1.ffm>
        File /tmp/feed1.ffm
        FileMaxSize 2M
        ACL allow 127.0.0.1
</Feed>

<Stream test1.sdp>
    Feed feed1.ffm
    Format rtp
    Noaudio
    VideoCodec libx264
    AVOptionVideo flags +global_header
    AVOptionVideo me_range 16
    AVOptionVideo qdiff 4
    AVOptionVideo qmin 10
    AVOptionVideo qmax 51
    ACL allow 192.168.0.0 192.168.255.255
</Stream>

With such setup you can watch the stream with i.e. VLC by typing:

rtsp://192.168.0.xxx:1235/test1.sdp

Here is the FFserver documentation.

Best approach to real time http streaming to HTML5 video client

This is a very common misconception. There is no live HTML5 video support (except for HLS on iOS and Mac Safari). You may be able to 'hack' it using a webm container, but I would not expect that to be universally supported. What you are looking for is included in the Media Source Extensions, where you can feed the fragments to the browser one at a time. but you will need to write some client side javascript.

How to increase scrollback buffer size in tmux?

The history limit is a pane attribute that is fixed at the time of pane creation and cannot be changed for existing panes. The value is taken from the history-limit session option (the default value is 2000).

To create a pane with a different value you will need to set the appropriate history-limit option before creating the pane.

To establish a different default, you can put a line like the following in your .tmux.conf file:

set-option -g history-limit 3000

Note: Be careful setting a very large default value, it can easily consume lots of RAM if you create many panes.

For a new pane (or the initial pane in a new window) in an existing session, you can set that session’s history-limit. You might use a command like this (from a shell):

tmux set-option history-limit 5000 \; new-window

For (the initial pane of the initial window in) a new session you will need to set the “global” history-limit before creating the session:

tmux set-option -g history-limit 5000 \; new-session

Note: If you do not re-set the history-limit value, then the new value will be also used for other panes/windows/sessions created in the future; there is currently no direct way to create a single new pane/window/session with its own specific limit without (at least temporarily) changing history-limit (though show-option (especially in 1.7 and later) can help with retrieving the current value so that you restore it later).

Run ssh and immediately execute command

This isn't quite what you're looking for, but I've found it useful in similar circumstances.

I recently added the following to my $HOME/.bashrc (something similar should be possible with shells other than bash):

if [ -f $HOME/.add-screen-to-history ] ; then
    history -s 'screen -dr'
fi

I keep a screen session running on one particular machine, and I've had problems with ssh connections to that machine being dropped, requiring me to re-run screen -dr every time I reconnect.

With that addition, and after creating that (empty) file in my home directory, I automatically have the screen -dr command in my history when my shell starts. After reconnecting, I can just type Control-P Enter and I'm back in my screen session -- or I can ignore it. It's flexible, but not quite automatic, and in your case it's easier than typing tmux list-sessions.

You might want to make the history -s command unconditional.

This does require updating your $HOME/.bashrc on each of the target systems, which might or might not make it unsuitable for your purposes.

Setting HTTP headers

I create wrapper for this case:

func addDefaultHeaders(fn http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Access-Control-Allow-Origin", "*")
        fn(w, r)
    }
}

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

tmux set -g mouse-mode on doesn't work

Paste here in ~/.tmux.conf

set -g mouse on

and run on terminal

tmux source-file ~/.tmux.conf

Requested bean is currently in creation: Is there an unresolvable circular reference?

I think you could use Spring's

@Lazy

annotation on one of the autowired fields to break circular dependency.

I'm not sure if this works/exists in mentioned Spring version.

tmux status bar configuration

Do C-b, :show which will show you all your current settings. /green, nnn will find you which properties have been set to green, the default. Do C-b, :set window-status-bg cyan and the bottom bar should change colour.

List available colours for tmux

You can tell more easily by the titles and the colours as they're actually set in your live session :show, than by searching through the man page, in my opinion. It is a very well-written man page when you have the time though.

If you don't like one of your changes and you can't remember how it was originally set, you can open do a new tmux session. To change settings for good edit ~/.tmux.conf with a line like set window-status-bg -g cyan. Here's mine: https://gist.github.com/9083598

Is there any way to redraw tmux window when switching smaller monitor to bigger one?

tmux limits the dimensions of a window to the smallest of each dimension across all the sessions to which the window is attached. If it did not do this there would be no sensible way to display the whole window area for all the attached clients.

The easiest thing to do is to detach any other clients from the sessions when you attach:

tmux attach -d

Alternately, you can move any other clients to a different session before attaching to the session:

takeover() {
    # create a temporary session that displays the "how to go back" message
    tmp='takeover temp session'
    if ! tmux has-session -t "$tmp"; then
        tmux new-session -d -s "$tmp"
        tmux set-option -t "$tmp" set-remain-on-exit on
        tmux new-window -kt "$tmp":0 \
            'echo "Use Prefix + L (i.e. ^B L) to return to session."'
    fi

    # switch any clients attached to the target session to the temp session
    session="$1"
    for client in $(tmux list-clients -t "$session" | cut -f 1 -d :); do
        tmux switch-client -c "$client" -t "$tmp"
    done

    # attach to the target session
    tmux attach -t "$session"
}
takeover 'original session' # or the session number if you do not name sessions

The screen will shrink again if a smaller client switches to the session.

There is also a variation where you only "take over" the window (link the window into a new session, set aggressive-resize, and switch any other sessions that have that window active to some other window), but it is harder to script in the general case (and different to “exit” since you would want to unlink the window or kill the session instead of just detaching from the session).

How to terminate a window in tmux?

While you asked how to kill a window resp. pane, I often wouldn't want to kill it but simply to get it back to a working state (the layout of panes is of importance to me, killing a pane destroys it so I must recreate it); tmux provides the respawn commands to that effect: respawn-pane resp. respawn-window. Just that people like me may find this solution here.

How to set up tmux so that it starts up with specified windows opened?

And this is how I do it:

#!/bin/bash

function has-session {
  tmux has-session -t name_of_my_session 2>/dev/null
}

if has-session ; then
  echo "Session already exists"
else
  cd /path/to/my/project
  tmux new-session -d -s name_of_my_session 'vim'
  tmux split-window -h -p 40 start_web_server
  tmux split-window -v
  tmux attach-session -d -t name_of_my_session
fi

I have one file for each of my project. Also you can group them to have some for work some for hobby projects.

Also you can move it to ~/bin folder, add it to PATH and give tmux_my_awesome_project name. Then you will be able to run it from each place.

jQuery: Get the cursor position of text in input without browser specific code?

A warning about the Jquery Caret plugin.

It will conflict with the Masked Input plugin (or vice versa). Fortunately the Masked Input plugin includes a caret() function of its own, which you can use very similarly to the Caret plugin for your basic needs - $(element).caret().begin or .end

C++11 rvalues and move semantics confusion (return statement)

First example

std::vector<int> return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return tmp;
}

std::vector<int> &&rval_ref = return_vector();

The first example returns a temporary which is caught by rval_ref. That temporary will have its life extended beyond the rval_ref definition and you can use it as if you had caught it by value. This is very similar to the following:

const std::vector<int>& rval_ref = return_vector();

except that in my rewrite you obviously can't use rval_ref in a non-const manner.

Second example

std::vector<int>&& return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return std::move(tmp);
}

std::vector<int> &&rval_ref = return_vector();

In the second example you have created a run time error. rval_ref now holds a reference to the destructed tmp inside the function. With any luck, this code would immediately crash.

Third example

std::vector<int> return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return std::move(tmp);
}

std::vector<int> &&rval_ref = return_vector();

Your third example is roughly equivalent to your first. The std::move on tmp is unnecessary and can actually be a performance pessimization as it will inhibit return value optimization.

The best way to code what you're doing is:

Best practice

std::vector<int> return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return tmp;
}

std::vector<int> rval_ref = return_vector();

I.e. just as you would in C++03. tmp is implicitly treated as an rvalue in the return statement. It will either be returned via return-value-optimization (no copy, no move), or if the compiler decides it can not perform RVO, then it will use vector's move constructor to do the return. Only if RVO is not performed, and if the returned type did not have a move constructor would the copy constructor be used for the return.

how to convert long date value to mm/dd/yyyy format

Refer Below code which give the date in String form.

import java.text.SimpleDateFormat;
import java.util.Date;



public class Test{

    public static void main(String[] args) {
        long val = 1346524199000l;
        Date date=new Date(val);
        SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
        String dateText = df2.format(date);
        System.out.println(dateText);
    }
}

How can I make a JUnit test wait?

How about Thread.sleep(2000); ? :)

How to List All Redis Databases?

Or you can just run the following command and you will see all databases of the Redis instance without firing up redis-cli:

$ redis-cli INFO | grep ^db
db0:keys=1500,expires=2
db1:keys=200000,expires=1
db2:keys=350003,expires=1

Javascript Get Element by Id and set the value

<html>
<head>
<script>
function updateTextarea(element)
{
document.getElementById(element).innerText = document.getElementById("ment").value;
}
</script>
</head>
<body>

<input type="text" value="Enter your text here." id = "ment" style = " border: 1px solid grey; margin-bottom: 4px;"  

onKeyUp="updateTextarea('myDiv')" />

<br>

<textarea id="myDiv" ></textarea>

</body>
</html>

how to convert JSONArray to List of Object using camel-jackson

I had similar json response coming from client. Created one main list class, and one POJO class.

Postgres Error: More than one row returned by a subquery used as an expression

This error means that the SELECT store_key FROM store query has returned two or more rows in the SERVER1 database. If you would like to update all customers, use a join instead of a scalar = operator. You need a condition to "connect" customers to store items in order to do that.

If you wish to update all customer_ids to the same store_key, you need to supply a WHERE clause to the remotely executed SELECT so that the query returns a single row.

Read the current full URL with React?

If you need the full path of your URL, you can use vanilla Javascript:

window.location.href

To get just the path (minus domain name), you can use:

window.location.pathname

_x000D_
_x000D_
console.log(window.location.pathname); //yields: "/js" (where snippets run)_x000D_
console.log(window.location.href);     //yields: "https://stacksnippets.net/js"
_x000D_
_x000D_
_x000D_

Source: Location pathname Property - W3Schools

If you are not already using "react-router" you can install it using:

yarn add react-router

then in a React.Component within a "Route", you can call:

this.props.location.pathname

This returns the path, not including the domain name.

Thanks @abdulla-zulqarnain!

Bootstrap full responsive navbar with logo or brand name text

Just set the height and width where you are adding that logo. I tried and its working fine

Is it possible to create a 'link to a folder' in a SharePoint document library?

The simplest way is to use the following pattern:

http://[server]/[site]/[ListName]/[Folder]/[SubFolder]

To place a shortcut to a document library:

  1. Upload it as *.url file. However, by default, this file type is not allowed.
  2. Go to you Document Library settings > Advanced Settings > Allow management of content types. Add the "Link to document" content type to a document library and paste the link

React.js: onChange event for contentEditable

This is the is simplest solution that worked for me.

<div
  contentEditable='true'
  onInput={e => console.log('Text inside div', e.currentTarget.textContent)}
>
Text inside div
</div>

What is the usefulness of PUT and DELETE HTTP request methods?

DELETE is for deleting the request resource:

The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be overridden by human intervention (or other means) on the origin server. The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully …

PUT is for putting or updating a resource on the server:

The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI …

For the full specification visit:

Since current browsers unfortunately do not support any other verbs than POST and GET in HTML forms, you usually cannot utilize HTTP to it's full extent with them (you can still hijack their submission via JavaScript though). The absence of support for these methods in HTML forms led to URIs containing verbs, like for instance

POST http://example.com/order/1/delete

or even worse

POST http://example.com/deleteOrder/id/1

effectively tunneling CRUD semantics over HTTP. But verbs were never meant to be part of the URI. Instead HTTP already provides the mechanism and semantics to CRUD a Resource (e.g. an order) through the HTTP methods. HTTP is a protocol and not just some data tunneling service.

So to delete a Resource on the webserver, you'd call

DELETE http://example.com/order/1

and to update it you'd call

PUT http://example.com/order/1

and provide the updated Resource Representation in the PUT body for the webserver to apply then.

So, if you are building some sort of client for a REST API, you will likely make it send PUT and DELETE requests. This could be a client built inside a browser, e.g. sending requests via JavaScript or it could be some tool running on a server, etc.

For some more details visit:

Why does Git say my master branch is "already up to date" even though it is not?

Just a friendly reminder if you have files locally that aren't in github and yet your git status says

Your branch is up to date with 'origin/master'. nothing to commit, working tree clean

It can happen if the files are in .gitignore

Try running

cat .gitignore 

and seeing if these files show up there. That would explain why git doesn't want to move them to the remote.

SQL RANK() over PARTITION on joined tables

SELECT a.C_ID,a.QRY_ID,a.RES_ID,b.SCORE,ROW_NUMBER() OVER (ORDER BY SCORE DESC) AS [RANK]
FROM CONTACTS a JOIN RSLTS b ON a.QRY_ID=b.QRY_ID AND a.RES_ID=b.RES_ID
ORDER BY a.C_ID

How to reset a form using jQuery with .reset() method

I use this simple code:

//reset form 
$("#mybutton").click(function(){
    $("#myform").find('input:text, input:password, input:file, select, textarea').val('');
    $("#myform").find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
});

Align button at the bottom of div using CSS

Goes to the right and can be used the same way for the left

.yourComponent
{
   float: right;
   bottom: 0;
}

print spaces with String.format()

You need to specify the minimum width of the field.

String.format("%" + numberOfSpaces + "s", ""); 

Why do you want to generate a String of spaces of a certain length.

If you want a column of this length with values then you can do:

String.format("%" + numberOfSpaces + "s", "Hello"); 

which gives you numberOfSpaces-5 spaces followed by Hello. If you want Hello to appear on the left then add a minus sign in before numberOfSpaces.

Upgrading Node.js to latest version

Upgrading node.js to the latest version on Windows

  1. Install chocolatey if you haven't already: Installing Chocolatey

  2. From the command prompt, type

    cup nodejs

(which is equivalent to typing choco upgrade nodejs -- assumes you already have node installed)

NOTE: You may need to run cinst nodejs.install for chocolatey to register your existing installation. (thanks for the comment, @mikecheel)


Installing node.js on Windows

If you have never installed node, you can use chocolatey to do that as well. Install chocolatey (see step 1 above). Then from a command prompt, type:

cinst nodejs.install

Chocolatey Gallery Node JS (Install)


Installing a specific version of node on Windows with chocolatey

cinst nodejs.install -Version 0.10.26

Regarding C++ Include another class

you need to forward declare the name of the class if you don't want a header:

class ClassTwo;

Important: This only works in some cases, see Als's answer for more information..

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

Another great option is the free V-Tools addin for Microsoft Access. Among other helpful tools it has a form to edit and save the Import/Export specifications.

enter image description here

enter image description here

Note: As of version 1.83, there is a bug in enumerating the code pages on Windows 10. (Apparently due to a missing/changed API function in Windows 10) The tools still works great, you just need to comment out a few lines of code or step past it in the debug window.

This has been a real life-saver for me in editing a complex import spec for our online orders.

Count number of lines in a git repository

If you want to get the number of lines from a certain author, try the following code:

git ls-files "*.java" | xargs -I{} git blame {} | grep ${your_name} | wc -l

How to change color of Android ListView separator line?

For a single color line use:

list.setDivider(new ColorDrawable(0x99F10529));   //0xAARRGGBB
list.setDividerHeight(1);

It's important that DividerHeight is set after the divider, else you won't get anything.

Plotting with C#

I just wanted to supplement MajesticRa's recommendation of OxyPlot, and point out how OxyPlot can be used for a variety of plotting cases. The software is free and Open-Source, very polished, and allows for a variety of uses beyon normal 2D mapping.

I've been using OxyPlot for an unorthodox project, where I display (in WPF/C#) a map (Robotic Occupancy Grid) which I could overlay with LineSeries (Path Traveled) and PointSeries (Way Points). Using the OxyPlot ImageAnnotation feature I am able to display 60Hz Video within my OxyPlot, by periodically updating the ImageAnnotation on its own thread, while mapping Series of points overtop the video. The background video and points are even scalable and translatable.

Hopefully this is helpful for other looking to display plots overtop of images and videos.

What's the difference between [ and [[ in Bash?

  • [ is the same as the test builtin, and works like the test binary (man test)
    • works about the same as [ in all the other sh-based shells in many UNIX-like environments
    • only supports a single condition. Multiple tests with the bash && and || operators must be in separate brackets.
    • doesn't natively support a 'not' operator. To invert a condition, use a ! outside the first bracket to use the shell's facility for inverting command return values.
    • == and != are literal string comparisons
  • [[ is a bash
    • is bash-specific, though others shells may have implemented similar constructs. Don't expect it in an old-school UNIX sh.
    • == and != apply bash pattern matching rules, see "Pattern Matching" in man bash
    • has a =~ regex match operator
    • allows use of parentheses and the !, &&, and || logical operators within the brackets to combine subexpressions

Aside from that, they're pretty similar -- most individual tests work identically between them, things only get interesting when you need to combine different tests with logical AND/OR/NOT operations.

Create thumbnail image

This is the code I'm using. Also works for .NET Core > 2.0 using System.Drawing.Common NuGet.

https://www.nuget.org/packages/System.Drawing.Common/

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
        const string input = "C:\\background1.png";
        const string output = "C:\\thumbnail.png";

        // Load image.
        Image image = Image.FromFile(input);

        // Compute thumbnail size.
        Size thumbnailSize = GetThumbnailSize(image);

        // Get thumbnail.
        Image thumbnail = image.GetThumbnailImage(thumbnailSize.Width,
            thumbnailSize.Height, null, IntPtr.Zero);

        // Save thumbnail.
        thumbnail.Save(output);
    }

    static Size GetThumbnailSize(Image original)
    {
        // Maximum size of any dimension.
        const int maxPixels = 40;

        // Width and height.
        int originalWidth = original.Width;
        int originalHeight = original.Height;

        // Return original size if image is smaller than maxPixels
        if (originalWidth <= maxPixels || originalHeight <= maxPixels)
        {
            return new Size(originalWidth, originalHeight);
        }   

        // Compute best factor to scale entire image based on larger dimension.
        double factor;
        if (originalWidth > originalHeight)
        {
            factor = (double)maxPixels / originalWidth;
        }
        else
        {
            factor = (double)maxPixels / originalHeight;
        }

        // Return thumbnail size.
        return new Size((int)(originalWidth * factor), (int)(originalHeight * factor));
    }
}

Source:

https://www.dotnetperls.com/getthumbnailimage

COPY with docker but with exclusion

For those who can't use a .dockerignore file (e.g. if you need the file in one COPY but not another):

Yes, but you need multiple COPY instructions. Specifically, you need a COPY for each letter in the filename you wish to exclude.

COPY [^n]*    # All files that don't start with 'n'
COPY n[^o]*   # All files that start with 'n', but not 'no'
COPY no[^d]*  # All files that start with 'no', but not 'nod'

Continuing until you have the full file name, or just the prefix you're reasonably sure won't have any other files.

Permanently Set Postgresql Schema Path

(And if you have no admin access to the server)

ALTER ROLE <your_login_role> SET search_path TO a,b,c;

Two important things to know about:

  1. When a schema name is not simple, it needs to be wrapped in double quotes.
  2. The order in which you set default schemas a, b, c matters, as it is also the order in which the schemas will be looked up for tables. So if you have the same table name in more than one schema among the defaults, there will be no ambiguity, the server will always use the table from the first schema you specified for your search_path.

Mockito : how to verify method was called on an object created within a method?

If you don't want to use DI or Factories. You can refactor your class in a little tricky way:

public class Foo {
    private Bar bar;

    public void foo(Bar bar){
        this.bar = (bar != null) ? bar : new Bar();
        bar.someMethod();
        this.bar = null;  // for simulating local scope
    }
}

And your test class:

@RunWith(MockitoJUnitRunner.class)
public class FooTest {
    @Mock Bar barMock;
    Foo foo;

    @Test
    public void testFoo() {
       foo = new Foo();
       foo.foo(barMock);
       verify(barMock, times(1)).someMethod();
    }
}

Then the class that is calling your foo method will do it like this:

public class thirdClass {

   public void someOtherMethod() {
      Foo myFoo = new Foo();
      myFoo.foo(null);
   }
}

As you can see when calling the method this way, you don't need to import the Bar class in any other class that is calling your foo method which is maybe something you want.

Of course the downside is that you are allowing the caller to set the Bar Object.

Hope it helps.

How to declare and add items to an array in Python?

{} represents an empty dictionary, not an array/list. For lists or arrays, you need [].

To initialize an empty list do this:

my_list = []

or

my_list = list()

To add elements to the list, use append

my_list.append(12)

To extend the list to include the elements from another list use extend

my_list.extend([1,2,3,4])
my_list
--> [12,1,2,3,4]

To remove an element from a list use remove

my_list.remove(2)

Dictionaries represent a collection of key/value pairs also known as an associative array or a map.

To initialize an empty dictionary use {} or dict()

Dictionaries have keys and values

my_dict = {'key':'value', 'another_key' : 0}

To extend a dictionary with the contents of another dictionary you may use the update method

my_dict.update({'third_key' : 1})

To remove a value from a dictionary

del my_dict['key']

How to solve “Microsoft Visual Studio (VS)” error “Unable to connect to the configured development Web server”

I solved the error by changing the port for the project.

I did the following steps:

  1. Right click on the project.
  2. Go to properties.
  3. Go to Server tab.
  4. On tab section, change the project URL for other port, like 8080 or 3000.

Good luck!

Has an event handler already been added?

This example shows how to use the method GetInvocationList() to retrieve delegates to all the handlers that have been added. If you are looking to see if a specific handler (function) has been added then you can use array.

public class MyClass
{
  event Action MyEvent;
}

...

MyClass myClass = new MyClass();
myClass.MyEvent += SomeFunction;

...

Action[] handlers = myClass.MyEvent.GetInvocationList(); //this will be an array of 1 in this example

Console.WriteLine(handlers[0].Method.Name);//prints the name of the method

You can examine various properties on the Method property of the delegate to see if a specific function has been added.

If you are looking to see if there is just one attached, you can just test for null.

If statement in aspx page

A complete answer for optional content in the header of a VB.NET aspx page using a master page:

 <%@ Page Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="some_vb_page.aspx.vb" Inherits="some_vb_page" %> 
 <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">          
     <% If Request.QueryString("id_query_param") = 123 Then 'Add some VB comment here, 
         'which will not be visible in the rendered source code of the aspx page later %>        
         <!-- add some html content depending on -->
         <!-- the condition in the if statement: -->                
         <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript" charset="utf-8"></script>
     <% End If %>
</asp:Content>

Where your current page url is something like:

http://mywebpage.com/some_vb_page.aspx?id_query_param=123

How to set corner radius of imageView?

I created an UIView extension which allows to round specific corners :

import UIKit

enum RoundType {
    case top
    case none
    case bottom
    case both
}

extension UIView {

    func round(with type: RoundType, radius: CGFloat = 3.0) {
        var corners: UIRectCorner

        switch type {
        case .top:
            corners = [.topLeft, .topRight]
        case .none:
            corners = []
        case .bottom:
            corners = [.bottomLeft, .bottomRight]
        case .both:
            corners = [.allCorners]
        }

        DispatchQueue.main.async {
            let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
            let mask = CAShapeLayer()
            mask.path = path.cgPath
            self.layer.mask = mask
        }
    }

}

How do I run a Python script on my web server?

Very simply, you can rename your Python script to "pythonscript.cgi". Post that in your cgi-bin directory, add the appropriate permissions and browse to it.

This is a great link you can start with.

Here's another good one.

Hope that helps.


EDIT (09/12/2015): The second link has long been removed. Replaced it with one that provides information referenced from the original.

How to change Label Value using javascript

This will work in Chrome

// get your input
var input = document.getElementById('txt206451');
// get it's (first) label
var label = input.labels[0];
// change it's content
label.textContent = 'thanks'

But after looking, labels doesn't seem to be widely supported..


You can use querySelector

// get txt206451's (first) label
var label = document.querySelector('label[for="txt206451"]');
// change it's content
label.textContent = 'thanks'

Checkout one file from Subversion

I'd just browse it and export the single file. If you have HTTP access, just use the web browser to find the file and grab it.

If you need to get it back in after editing it, that might be slightly more tedious, but I'm sure there might be an svn import function...

How should I have explained the difference between an Interface and an Abstract class?

hmm now the people are hungery practical approach, you are quite right but most of interviewer looks as per their current requirment and want a practical approach.

after finishing your answer you should jump on the example:

Abstract:

for example we have salary function which have some parametar common to all employee. then we can have a abstract class called CTC with partialy defined method body and it will got extends by all type of employee and get redeined as per their extra beefits. For common functonality.

public abstract class CTC {

    public int salary(int hra, int da, int extra)
    {
        int total;
        total = hra+da+extra;
        //incentive for specific performing employee
        //total = hra+da+extra+incentive;
        return total;
    }
}

class Manger extends CTC
{
}


class CEO extends CTC
{
}

class Developer extends CTC
{   
}

Interface

interface in java allow to have interfcae functionality without extending that one and you have to be clear with the implementation of signature of functionality that you want to introduce in your application. it will force you to have definiton. For different functionality.

public interface EmployeType {

    public String typeOfEmployee();
}

class ContarctOne implements EmployeType
{

    @Override
    public String typeOfEmployee() {
        return "contract";
    }

}

class PermanentOne implements EmployeType
{

    @Override
    public String typeOfEmployee() {
        return "permanent";
    }

}

you can have such forced activity with abstract class too by defined methgos as a abstract one, now a class tha extends abstract class remin abstract one untill it override that abstract function.

How can I submit a POST form using the <a href="..."> tag?

In case you use MVC to accomplish it - you will have to do something like this

 <form action="/ControllerName/ActionName" method="post">
        <a href="javascript:;" onclick="parentNode.submit();"><%=n%></a>
        <input type="hidden" name="mess" value=<%=n%>/>
    </form>

I just went through some examples here and did not see the MVC one figured it won't hurt to post it.

Then on your Action in the Controller I would just put <HTTPPost> On the top of it. I believe if you don't have <HTTPGET> on the top of it it would still work but explicitly putting it there feels a bit safer.

How can I add private key to the distribution certificate?

For Developer certificate, you need to create a developer .mobileprovision profile and install add it to your XCode. In case you want to distribute the app using an adhoc distribution profile you will require AdHoc Distribution certificate and private key installed in your keychain.

If you have not created the cert, here are steps to create it. Incase it has already been created by someone in your team, ask him to share the cert and private key. If that someone is no longer in your team then you can revoke the cert from developer account and create new.

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

You need to start the Apache Tomcat services.

Win+R --> sevices.msc

Then, search for Apache Tomcat and right click on it and click on Start. This will start the service and then you'll be able to see Apache Tomcat homepage on the localhost .

Redirect parent window from an iframe action

If you'd like to redirect to another domain without the user having to do anything you can use a link with the property:

target="_parent"

as said previously, and then use:

document.getElementById('link').click();

to have it automatically redirect.

Example:

<!DOCTYPE HTML>

<html>

<head>

</head>

<body>

<a id="link" target="_parent" href="outsideDomain.html"></a>

<script type="text/javascript">
    document.getElementById('link').click();
</script>

</body>

</html>

Note: The javascript click() command must come after you declare the link.

How to use variables in a command in sed?

Say:

sed "s|\$ROOT|${HOME}|" abc.sh

Note:

  • Use double quotes so that the shell would expand variables.
  • Use a separator different than / since the replacement contains /
  • Escape the $ in the pattern since you don't want to expand it.

EDIT: In order to replace all occurrences of $ROOT, say

sed "s|\$ROOT|${HOME}|g" abc.sh

Limit to 2 decimal places with a simple pipe

Currency pipe uses the number one internally for number formatting. So you can use it like this:

{{ number | number : '1.2-2'}}

How to upgrade PowerShell version from 2.0 to 3.0

do use the links above. If you run into error "This update is not applicable to your computer. " then make sure you are in fact using the right file for your os. for example i tried running windows 2012 server from that link on windows 7 service pack 1 and I got the above error so be sure to use the right zip. If you don't know which os you have then go to start and system and it should pop right up This should be self explanatory but

Razor View Without Layout

You (and KMulligan) are misunderstanding _ViewStart pages.

_ViewStart will always execute, before your page starts.
It is intended to be used to initialize properties (such as Layout); it generally should not contain markup. (Since there is no way to override it).

The correct pattern is to make a separate layout page which calls RenderBody, and set the Layout property to point to this page in _ViewStart.

You can then change Layout in your content pages, and the changes will take effect.

Selenium Webdriver move mouse to Point

Got it working with

Actions builder = new Actions(driver);
WebElement el = some element;
builder.keyDown(Keys.CONTROL)
.moveByOffset( 10, 25 )
.clickAndHold(el)
.build().perform();

Depend on a branch or tag using a git URL in a package.json?

On latest version of NPM you can just do:

npm install gitAuthor/gitRepo#tag

If the repo is a valid NPM package it will be auto-aliased in package.json as:

{ "NPMPackageName": "gitAuthor/gitRepo#tag" }

If you could add this to @justingordon 's answer there is no need for manual aliasing now !

Detect browser or tab closing

window.addEventListener("beforeunload", function (e) {
 var confirmationMessage = "tab close";

 (e || window.event).returnValue = confirmationMessage;     //Gecko + IE
 sendkeylog(confirmationMessage);
 return confirmationMessage;                                //Webkit, Safari, Chrome etc.
}); 

How can I do a line break (line continuation) in Python?

If you want to break your line because of a long literal string, you can break that string into pieces:

long_string = "a very long string"
print("a very long string")

will be replaced by

long_string = (
  "a "
  "very "
  "long "
  "string"
)
print(
  "a "
  "very "
  "long "
  "string"
)

Output for both print statements:

a very long string

Notice the parenthesis in the affectation.

Notice also that breaking literal strings into pieces allows to use the literal prefix only on parts of the string and mix the delimiters:

s = (
  '''2+2='''
  f"{2+2}"
)

How to create friendly URL in php?

There are lots of different ways to do this. One way is to use the RewriteRule techniques mentioned earlier to mask query string values.

One of the ways I really like is if you use the front controller pattern, you can also use urls like http://yoursite.com/index.php/path/to/your/page/here and parse the value of $_SERVER['REQUEST_URI'].

You can easily extract the /path/to/your/page/here bit with the following bit of code:

$route = substr($_SERVER['REQUEST_URI'], strlen($_SERVER['SCRIPT_NAME']));

From there, you can parse it however you please, but for pete's sake make sure you sanitise it ;)

Android: Unable to add window. Permission denied for this window type

I just added simple view to WindowManager with the following steps:

  1. Create one layout file to show(dummy_layout in my case)
  2. Add permission in manifest and dynamically.
// 1. Show view
private void showCustomPopupMenu()
{
    windowManager = (WindowManager)getSystemService(WINDOW_SERVICE);
    // LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    // View view = layoutInflater.inflate(R.layout.dummy_layout, null);
    ViewGroup valetModeWindow = (ViewGroup) View.inflate(this, R.layout.dummy_layout, null);
    int LAYOUT_FLAG;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
    } else {
        LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE;
    }
    WindowManager.LayoutParams params=new WindowManager.LayoutParams(
        WindowManager.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.WRAP_CONTENT,
        LAYOUT_FLAG,
        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
        PixelFormat.TRANSLUCENT);

    params.gravity= Gravity.CENTER|Gravity.CENTER;
    params.x=0;
    params.y=0;
    windowManager.addView(valetModeWindow, params);
}

// 2. Get permissions by asking
if (!Settings.canDrawOverlays(this)) {
    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
    startActivityForResult(intent, 1234);
}

With this you can add a view to WM.

Tested in Pie.

How can I undo a `git commit` locally and on a remote after `git push`

Generally, make an "inverse" commit, using:

git revert 364705c

then send it to the remote as usual:

git push

This won't delete the commit: it makes an additional commit that undoes whatever the first commit did. Anything else, not really safe, especially when the changes have already been propagated.

Array Length in Java

Arrays are allocated memory at compile time in java, so they are static, the elements not explicitly set or modified are set with the default values. You could use some code like this, though it is not recommended as it does not count default values, even if you explicitly initialize them that way, it is also likely to cause bugs down the line. As others said, when looking for the actual size, ".length" must be used instead of ".length()".

public int logicalArrayLength(type[] passedArray) {
    int count = 0;
    for (int i = 0; i < passedArray.length; i++) {
        if (passedArray[i] != defaultValue) {
            count++;
        }
    }
    return count;
}

How to pass the password to su/sudo/ssh without overriding the TTY?

Set SSH up for Public Key Authentication, with no pasphrase on the Key. Loads of guides on the net. You won't need a password to login then. You can then limit connections for a key based on client hostname. Provides reasonable security and is great for automated logins.

Resizing an Image without losing any quality

There is something out there, context aware resizing, don't know if you will be able to use it, but it's worth looking at, that's for sure

A nice video demo (Enlarging appears towards the middle) http://www.youtube.com/watch?v=vIFCV2spKtg

Here there could be some code. http://www.semanticmetadata.net/2007/08/30/content-aware-image-resizing-gpl-implementation/

Was that overkill? Maybe there are some easy filters you can apply to an enlarged image to blur the pixels a bit, you could look into that.

"CASE" statement within "WHERE" clause in SQL Server 2008

here is my solution

AND CLI.PE_NOM Like '%' + ISNULL(@NomClient, CLI.PE_NOM) + '%'

Regads Davy

Get index of a key in json

You don't need a numerical index for an object key, but many others have told you that.

Here's the actual answer:

var json = { "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" };

console.log( getObjectKeyIndex(json, 'key2') ); 
// Returns int(1) (or null if the key doesn't exist)

function getObjectKeyIndex(obj, keyToFind) {
    var i = 0, key;

    for (key in obj) {
        if (key == keyToFind) {
            return i;
        }

        i++;
    }

    return null;
}

Though you're PROBABLY just searching for the same loop that I've used in this function, so you can go through the object:

for (var key in json) {
    console.log(key + ' is ' + json[key]);
}

Which will output

key1 is watevr1
key2 is watevr2
key3 is watevr3

Is there a difference between PhoneGap and Cordova commands?

I have also noticed that cordova has a "serve" command that Phonegap doesn't. This command launches a local server on port 8000. This is handy for running your app in Chrome and using the Ripple emulator.

Find a private field with Reflection?

Nice Syntax With Extension Method

You can access any private field of an arbitrary type with code like this:

Foo foo = new Foo();
string c = foo.GetFieldValue<string>("_bar");

For that you need to define an extension method that will do the work for you:

public static class ReflectionExtensions {
    public static T GetFieldValue<T>(this object obj, string name) {
        // Set the flags so that private and public fields from instances will be found
        var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
        var field = obj.GetType().GetField(name, bindingFlags);
        return (T)field?.GetValue(obj);
    }
}

How to resize superview to fit all subviews with autolayout?

This can be done for a normal subview inside a larger UIView, but it doesn't work automatically for headerViews. The height of a headerView is determined by what's returned by tableView:heightForHeaderInSection: so you have to calculate the height based on the height of the UILabel plus space for the UIButton and any padding you need. You need to do something like this:

-(CGFloat)tableView:(UITableView *)tableView 
          heightForHeaderInSection:(NSInteger)section {
    NSString *s = self.headeString[indexPath.section];
    CGSize size = [s sizeWithFont:[UIFont systemFontOfSize:17] 
                constrainedToSize:CGSizeMake(281, CGFLOAT_MAX)
                    lineBreakMode:NSLineBreakByWordWrapping];
    return size.height + 60;
}

Here headerString is whatever string you want to populate the UILabel, and the 281 number is the width of the UILabel (as setup in Interface Builder)

VBScript to send email without running Outlook

You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:

Set MyEmail=CreateObject("CDO.Message")

MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."

MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2

'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"

'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25 

MyEmail.Configuration.Fields.Update
MyEmail.Send

set MyEmail=nothing

If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update line:

'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username" 
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"

More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm

What is the format for the PostgreSQL connection string / URL?

The following worked for me

const conString = "postgres://YourUserName:YourPassword@YourHostname:5432/YourDatabaseName";

Delete empty rows

To delete rows empty in table

syntax:

DELETE FROM table_name 
WHERE column_name IS NULL;

example:

Table name: data ---> column name: pkdno

DELETE FROM data 
WHERE pkdno IS NULL;

Answer: 5 rows deleted. (sayso)

Faster way to zero memory than with memset?

That's an interesting question. I made this implementation that is just slightly faster (but hardly measurable) when 32-bit release compiling on VC++ 2012. It probably can be improved on a lot. Adding this in your own class in a multithreaded environment would probably give you even more performance gains since there are some reported bottleneck problems with memset() in multithreaded scenarios.

// MemsetSpeedTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include "Windows.h"
#include <time.h>

#pragma comment(lib, "Winmm.lib") 
using namespace std;

/** a signed 64-bit integer value type */
#define _INT64 __int64

/** a signed 32-bit integer value type */
#define _INT32 __int32

/** a signed 16-bit integer value type */
#define _INT16 __int16

/** a signed 8-bit integer value type */
#define _INT8 __int8

/** an unsigned 64-bit integer value type */
#define _UINT64 unsigned _INT64

/** an unsigned 32-bit integer value type */
#define _UINT32 unsigned _INT32

/** an unsigned 16-bit integer value type */
#define _UINT16 unsigned _INT16

/** an unsigned 8-bit integer value type */
#define _UINT8 unsigned _INT8

/** maximum allo

wed value in an unsigned 64-bit integer value type */
    #define _UINT64_MAX 18446744073709551615ULL

#ifdef _WIN32

/** Use to init the clock */
#define TIMER_INIT LARGE_INTEGER frequency;LARGE_INTEGER t1, t2;double elapsedTime;QueryPerformanceFrequency(&frequency);

/** Use to start the performance timer */
#define TIMER_START QueryPerformanceCounter(&t1);

/** Use to stop the performance timer and output the result to the standard stream. Less verbose than \c TIMER_STOP_VERBOSE */
#define TIMER_STOP QueryPerformanceCounter(&t2);elapsedTime=(t2.QuadPart-t1.QuadPart)*1000.0/frequency.QuadPart;wcout<<elapsedTime<<L" ms."<<endl;
#else
/** Use to init the clock */
#define TIMER_INIT clock_t start;double diff;

/** Use to start the performance timer */
#define TIMER_START start=clock();

/** Use to stop the performance timer and output the result to the standard stream. Less verbose than \c TIMER_STOP_VERBOSE */
#define TIMER_STOP diff=(clock()-start)/(double)CLOCKS_PER_SEC;wcout<<fixed<<diff<<endl;
#endif    


void *MemSet(void *dest, _UINT8 c, size_t count)
{
    size_t blockIdx;
    size_t blocks = count >> 3;
    size_t bytesLeft = count - (blocks << 3);
    _UINT64 cUll = 
        c 
        | (((_UINT64)c) << 8 )
        | (((_UINT64)c) << 16 )
        | (((_UINT64)c) << 24 )
        | (((_UINT64)c) << 32 )
        | (((_UINT64)c) << 40 )
        | (((_UINT64)c) << 48 )
        | (((_UINT64)c) << 56 );

    _UINT64 *destPtr8 = (_UINT64*)dest;
    for (blockIdx = 0; blockIdx < blocks; blockIdx++) destPtr8[blockIdx] = cUll;

    if (!bytesLeft) return dest;

    blocks = bytesLeft >> 2;
    bytesLeft = bytesLeft - (blocks << 2);

    _UINT32 *destPtr4 = (_UINT32*)&destPtr8[blockIdx];
    for (blockIdx = 0; blockIdx < blocks; blockIdx++) destPtr4[blockIdx] = (_UINT32)cUll;

    if (!bytesLeft) return dest;

    blocks = bytesLeft >> 1;
    bytesLeft = bytesLeft - (blocks << 1);

    _UINT16 *destPtr2 = (_UINT16*)&destPtr4[blockIdx];
    for (blockIdx = 0; blockIdx < blocks; blockIdx++) destPtr2[blockIdx] = (_UINT16)cUll;

    if (!bytesLeft) return dest;

    _UINT8 *destPtr1 = (_UINT8*)&destPtr2[blockIdx];
    for (blockIdx = 0; blockIdx < bytesLeft; blockIdx++) destPtr1[blockIdx] = (_UINT8)cUll;

    return dest;
}

int _tmain(int argc, _TCHAR* argv[])
{
    TIMER_INIT

    const size_t n = 10000000;
    const _UINT64 m = _UINT64_MAX;
    const _UINT64 o = 1;
    char test[n];
    {
        cout << "memset()" << endl;
        TIMER_START;

        for (int i = 0; i < m ; i++)
            for (int j = 0; j < o ; j++)
                memset((void*)test, 0, n);  

        TIMER_STOP;
    }
    {
        cout << "MemSet() took:" << endl;
        TIMER_START;

        for (int i = 0; i < m ; i++)
            for (int j = 0; j < o ; j++)
                MemSet((void*)test, 0, n);

        TIMER_STOP;
    }

    cout << "Done" << endl;
    int wait;
    cin >> wait;
    return 0;
}

Output is as follows when release compiling for 32-bit systems:

memset() took:
5.569000
MemSet() took:
5.544000
Done

Output is as follows when release compiling for 64-bit systems:

memset() took:
2.781000
MemSet() took:
2.765000
Done

Here you can find the source code Berkley's memset(), which I think is the most common implementation.

MySQL string replace

In addition to gmaggio's answer if you need to dynamically REPLACE and UPDATE according to another column you can do for example:

UPDATE your_table t1
INNER JOIN other_table t2
ON t1.field_id = t2.field_id
SET t1.your_field = IF(LOCATE('articles/updates/', t1.your_field) > 0, 
REPLACE(t1.your_field, 'articles/updates/', t2.new_folder), t1.your_field) 
WHERE...

In my example the string articles/news/ is stored in other_table t2 and there is no need to use LIKE in the WHERE clause.

How to know elastic search installed version from kibana?

navigate to the folder where you have installed your kibana if you have used yum to install kibana it will be placed in following location by default

/usr/share/kibana

then use the following command

bin/kibana --version

How can I access my localhost from my Android device?

Having a netconfig xml and assign it in the manifest.xml is the best work around. This will bypass the androids default https only contraint.

SqlServer: Login failed for user

If you are using Windows Authentication, make sure to log-in to Windows at least once with that user.

Laravel 5: Display HTML with Blade

By default, Blade {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:

According to the doc, you must do the following to render your html in your Blade files:

{!! $text !!}

Be very careful when echoing content that is supplied by users of your application. You should typically use the escaped, double curly brace syntax to prevent XSS attacks when displaying user supplied data.

How to write a comment in a Razor view?

Note that in general, IDE's like Visual Studio will markup a comment in the context of the current language, by selecting the text you wish to turn into a comment, and then using the Ctrl+K Ctrl+C shortcut, or if you are using Resharper / Intelli-J style shortcuts, then Ctrl+/.

Server side Comments:

Razor .cshtml

Like so:

@* Comment goes here *@

.aspx
For those looking for the older .aspx view (and Asp.Net WebForms) server side comment syntax:

<%-- Comment goes here --%>

Client Side Comments

HTML Comment

<!-- Comment goes here -->

Javascript Comment

// One line Comment goes Here
/* Multiline comment
   goes here */

As OP mentions, although not displayed on the browser, client side comments will still be generated for the page / script file on the server and downloaded by the page over HTTP, which unless removed (e.g. minification), will waste I/O, and, since the comment can be viewed by the user by viewing the page source or intercepting the traffic with the browser's Dev Tools or a tool like Fiddler or Wireshark, can also pose a security risk, hence the preference to use server side comments on server generated code (like MVC views or .aspx pages).

Java - Create a new String instance with specified length and filled with specific character. Best solution?

using Dollar is simple:

String filled = $("=").repeat(10).toString(); // produces "=========="

Decorators with parameters?

It is a decorator that can be called in a variety of ways (tested in python3.7):

import functools


def my_decorator(*args_or_func, **decorator_kwargs):

    def _decorator(func):

        @functools.wraps(func)
        def wrapper(*args, **kwargs):

            if not args_or_func or callable(args_or_func[0]):
                # Here you can set default values for positional arguments
                decorator_args = ()
            else:
                decorator_args = args_or_func

            print(
                "Available inside the wrapper:",
                decorator_args, decorator_kwargs
            )

            # ...
            result = func(*args, **kwargs)
            # ...

            return result

        return wrapper

    return _decorator(args_or_func[0]) \
        if args_or_func and callable(args_or_func[0]) else _decorator


@my_decorator
def func_1(arg): print(arg)

func_1("test")
# Available inside the wrapper: () {}
# test


@my_decorator()
def func_2(arg): print(arg)

func_2("test")
# Available inside the wrapper: () {}
# test


@my_decorator("any arg")
def func_3(arg): print(arg)

func_3("test")
# Available inside the wrapper: ('any arg',) {}
# test


@my_decorator("arg_1", 2, [3, 4, 5], kwarg_1=1, kwarg_2="2")
def func_4(arg): print(arg)

func_4("test")
# Available inside the wrapper: ('arg_1', 2, [3, 4, 5]) {'kwarg_1': 1, 'kwarg_2': '2'}
# test

PS thanks to user @norok2 - https://stackoverflow.com/a/57268935/5353484

UPD Decorator for validating arguments and/or result of functions and methods of a class against annotations. Can be used in synchronous or asynchronous version: https://github.com/EvgeniyBurdin/valdec

Add onclick event to newly added element in JavaScript

Not sure but try :

elemm.addEventListener('click', function(){ alert('blah');}, false);

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

These issue arise generally due to mismatch between @ngx-translate/core version and Angular .Before installing check compatible version of corresponding ngx_trnalsate/Core, @ngx-translate/http-loader and Angular at https://www.npmjs.com/package/@ngx-translate/core

Eg: For Angular 6.X versions,

npm install @ngx-translate/core@10 @ngx-translate/http-loader@3 rxjs --save

Like as above, follow below command and rest of code part is common for all versions(Note: Version can obtain from( https://www.npmjs.com/package/@ngx-translate/core)

npm install @ngx-translate/core@version @ngx-translate/http-loader@version rxjs --save

jQuery.ajax returns 400 Bad Request

I think you just need to add 2 more options (contentType and dataType):

$('#my_get_related_keywords').click(function() {

    $.ajax({
            type: "POST",
            url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
            data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
            contentType: "application/json; charset=utf-8", // this
            dataType: "json", // and this
            success: function (msg) {
               //do something
            },
            error: function (errormessage) {
                //do something else
            }
        });
}

How to make an authenticated web request in Powershell?

The PowerShell is almost exactly the same.

$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
$webpage = $webclient.DownloadString($url)

Missing Authentication Token while accessing API Gateway?

Looks like (as of April 2019) AWS API Gateway throws this exception for a variety of reasons - mostly when you are hitting an endpoint that API Gateway is not able to reach, either because it is not deployed, or also in cases where that particular HTTP method is not supported.

I wish the gateway sends more appropriate error codes like HTTP 405 Method not supported or HTTP 404 not found, instead of a generic HTTP 403 Forbidden.

Change Primary Key

Sometimes when we do these steps:

 alter table my_table drop constraint my_pk; 
 alter table my_table add constraint my_pk primary key (city_id, buildtime, time);

The last statement fails with

ORA-00955 "name is already used by an existing object"

Oracle usually creates an unique index with the same name my_pk. In such a case you can drop the unique index or rename it based on whether the constraint is still relevant.

You can combine the dropping of primary key constraint and unique index into a single sql statement:

alter table my_table drop constraint my_pk drop index; 

check this: ORA-00955 "name is already used by an existing object"

Delete all documents from index/type without deleting type

I'm using elasticsearch 7.5 and when I use

curl -XPOST 'localhost:9200/materials/_delete_by_query?conflicts=proceed&pretty' -d'
{
    "query": {
        "match_all": {}
    }
}'

which will throw below error.

{
  "error" : "Content-Type header [application/x-www-form-urlencoded] is not supported",
  "status" : 406
}

I also need to add extra -H 'Content-Type: application/json' header in the request to make it works.

curl -XPOST 'localhost:9200/materials/_delete_by_query?conflicts=proceed&pretty'  -H 'Content-Type: application/json' -d'
{
    "query": {
        "match_all": {}
    }
}'
{
  "took" : 465,
  "timed_out" : false,
  "total" : 2275,
  "deleted" : 2275,
  "batches" : 3,
  "version_conflicts" : 0,
  "noops" : 0,
  "retries" : {
    "bulk" : 0,
    "search" : 0
  },
  "throttled_millis" : 0,
  "requests_per_second" : -1.0,
  "throttled_until_millis" : 0,
  "failures" : [ ]
}

How to load URL in UIWebView in Swift?

Try this:

  1. Add UIWebView to View.

  2. Connect UIWebview outlet using assistant editor and name your "webview".

  3. UIWebView Load URL.

    @IBOutlet weak var webView: UIWebView!
    
    override func viewDidLoad() {
       super.viewDidLoad()
        // Your webView code goes here
       let url = URL(string: "https://www.example.com")
       let requestObj = URLRequest(url: url! as URL)
       webView.load(requestObj)
    }
    

And run the app!!

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

For Tomcat 8, I had to add the following line to catalina.properties for preventing jars scanned by Tomcat:

tomcat.util.scan.StandardJarScanFilter.jarsToSkip=jsp-api.jar,servlet-api.jar

RSA: Get exponent and modulus given a public key

Mostly for my own reference, here's how you get it from a private key generated by ssh-keygen

openssl rsa -text -noout -in ~/.ssh/id_rsa

Of course, this only works with the private key.

Angular CLI SASS options

For Angular 9.0 and above, update the "schematics":{} object in angular.json file like this:

"schematics": {
  "@schematics/angular:component": {
    "style": "scss"
  }
}

Specified cast is not valid.. how to resolve this

Use Convert.ToDouble(value) rather than (double)value. It takes an object and supports all of the types you asked for! :)

Also, your method is always returning a string in the code above; I'd recommend having the method indicate so, and give it a more obvious name (public string FormatLargeNumber(object value))

How to declare Return Types for Functions in TypeScript

You can read more about function types in the language specification in sections 3.5.3.5 and 3.5.5.

The TypeScript compiler will infer types when it can, and this is done you do not need to specify explicit types. so for the greeter example, greet() returns a string literal, which tells the compiler that the type of the function is a string, and no need to specify a type. so for instance in this sample, I have the greeter class with a greet method that returns a string, and a variable that is assigned to number literal. the compiler will infer both types and you will get an error if you try to assign a string to a number.

class Greeter {
    greet() {
        return "Hello, ";  // type infered to be string
    }
} 

var x = 0; // type infered to be number

// now if you try to do this, you will get an error for incompatable types
x = new Greeter().greet(); 

Similarly, this sample will cause an error as the compiler, given the information, has no way to decide the type, and this will be a place where you have to have an explicit return type.

function foo(){
    if (true)
        return "string"; 
    else 
        return 0;
}

This, however, will work:

function foo() : any{
    if (true)
        return "string"; 
    else 
        return 0;
}

How to create Drawable from resource

You must get it via compatible way, others are deprecated:

Drawable drawable = ResourcesCompat.getDrawable(context.getResources(), R.drawable.my_drawable, null);

Large Numbers in Java

import java.math.BigInteger;
import java.util.*;
class A
{
    public static void main(String args[])
    {
        Scanner in=new Scanner(System.in);
        System.out.print("Enter The First Number= ");
        String a=in.next();
        System.out.print("Enter The Second Number= ");
        String b=in.next();

        BigInteger obj=new BigInteger(a);
        BigInteger obj1=new BigInteger(b);
        System.out.println("Sum="+obj.add(obj1));
    }
}

Exception from HRESULT: 0x800A03EC Error

I was receiving the same error some time back. The issue was that my XLS file contained more than 65531 records(500 thousand to be precise). I was attempting to read a range of cells.

Excel.Range rng = (Excel.Range) myExcelWorkbookObj.UsedRange.Rows[i];

The exception was thrown while trying to read the range of cells when my counter, i.e. 'i', exceeded this limit of 65531 records.

Conditional formatting based on another cell's value

Basically all you need to do is add $ as prefix at column letter and row number. Please see image below

enter image description here

Ways to iterate over a list in Java

In Java 8 we have multiple ways to iterate over collection classes.

Using Iterable forEach

The collections that implement Iterable (for example all lists) now have forEach method. We can use method-reference introduced in Java 8.

Arrays.asList(1,2,3,4).forEach(System.out::println);

Using Streams forEach and forEachOrdered

We can also iterate over a list using Stream as:

Arrays.asList(1,2,3,4).stream().forEach(System.out::println);
Arrays.asList(1,2,3,4).stream().forEachOrdered(System.out::println);

We should prefer forEachOrdered over forEach because the behaviour of forEach is explicitly nondeterministic where as the forEachOrdered performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach does not guarantee that the order would be kept.

The advantage with streams is that we can also make use of parallel streams wherever appropriate. If the objective is only to print the items irrespective of the order then we can use parallel stream as:

Arrays.asList(1,2,3,4).parallelStream().forEach(System.out::println);

In PHP, what is a closure and why does it use the "use" identifier?

Until very recent years, PHP has defined its AST and PHP interpreter has isolated the parser from the evaluation part. During the time when the closure is introduced, PHP's parser is highly coupled with the evaluation.

Therefore when the closure was firstly introduced to PHP, the interpreter has no method to know which which variables will be used in the closure, because it is not parsed yet. So user has to pleased the zend engine by explicit import, doing the homework that zend should do.

This is the so-called simple way in PHP.

Newtonsoft JSON Deserialize

A much easier solution: Using a dynamic type

As of Json.NET 4.0 Release 1, there is native dynamic support. You don't need to declare a class, just use dynamic :

dynamic jsonDe = JsonConvert.DeserializeObject(json);

All the fields will be available:

foreach (string typeStr in jsonDe.Type[0])
{
    // Do something with typeStr
} 

string t = jsonDe.t;
bool a = jsonDe.a;
object[] data = jsonDe.data;
string[][] type = jsonDe.Type;

With dynamic you don't need to create a specific class to hold your data.

How do I use ROW_NUMBER()?

Need to create virtual table by using WITH table AS, which is mention in given Query.

By using this virtual table, you can perform CRUD operation w.r.t row_number.

QUERY:

WITH table AS
-
(SELECT row_number() OVER(ORDER BY UserId) rn, * FROM Users)
-
SELECT * FROM table WHERE UserName='Joe'
-

You can use INSERT, UPDATE or DELETE in last sentence by in spite of SELECT.

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

How can I run another application within a panel of my C# program?

I don't know if this is still the recommended thing to use but the "Object Linking and Embedding" framework allows you to embed certain objects/controls directly into your application. This will probably only work for certain applications, I'm not sure if Notepad is one of them. For really simple things like notepad, you'll probably have an easier time just working with the text box controls provided by whatever medium you're using (e.g. WinForms).

Here's a link to OLE info to get started:

http://en.wikipedia.org/wiki/Object_Linking_and_Embedding

Load external css file like scripts in jquery which is compatible in ie also

I think what the OP wanted to do was to load a style sheet asynchronously and add it. This works for me in Chrome 22, FF 16 and IE 8 for sets of CSS rules stored as text:

$.ajax({
    url: href,
    dataType: 'text',
    success: function(data) {
        $('<style type="text/css">\n' + data + '</style>').appendTo("head");                    
    }                  
});

In my case, I also sometimes want the loaded CSS to replace CSS that was previously loaded this way. To do that, I put a comment at the beginning, say "/* Flag this ID=102 */", and then I can do this:

// Remove old style
$("head").children().each(function(index, ele) {
    if (ele.innerHTML && ele.innerHTML.substring(0, 30).match(/\/\* Flag this ID=102 \*\//)) {
        $(ele).remove();
        return false;    // Stop iterating since we removed something
    }
});

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

@article = user.articles.build(:title => "MainTitle")
@article.save

How to convert strings into integers in Python?

T3=[]

for i in range(0,len(T1)):
    T3.append([])
    for j in range(0,len(T1[i])):
        b=int(T1[i][j])
        T3[i].append(b)

print T3

Full Screen Theme for AppCompat

This theme only works after API 21(included). And make both the StatusBar and NavigationBar transparent.

<style name="TransparentAppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
  <item name="windowActionBar">false</item>
  <item name="windowNoTitle">true</item>
  <item name="android:statusBarColor">@android:color/transparent</item>
  <item name="android:windowBackground">@android:color/transparent</item>
  <item name="android:navigationBarColor">@android:color/transparent</item>
  <item name="android:windowIsTranslucent">true</item>
  <item name="android:windowContentOverlay">@null</item>
</style>

RegEx: How can I match all numbers greater than 49?

The fact that the first digit has to be in the range 5-9 only applies in case of two digits. So, check for that in the case of 2 digits, and allow any more digits directly:

^([5-9]\d|\d{3,})$

This regexp has beginning/ending anchors to make sure you're checking all digits, and the string actually represents a number. The | means "or", so either [5-9]\d or any number with 3 or more digits. \d is simply a shortcut for [0-9].

Edit: To disallow numbers like 001:

^([5-9]\d|[1-9]\d{2,})$

This forces the first digit to be not a zero in the case of 3 or more digits.

Creating a UITableView Programmatically

Creating a tableview using tableViewController .

import UIKit

class TableViewController: UITableViewController
{
    let tableViewModel = TableViewModel()
    var product: [String] = []
    var price: [String] = []
    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.tableView.contentInset = UIEdgeInsetsMake( 20, 20 , 0, 0)
        let priceProductDetails = tableViewModel.dataProvider()

        for (key, value) in priceProductDetails
        {
            product.append(key)
            price.append(value)
        }
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return product.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = UITableViewCell(style: .Value1, reuseIdentifier: "UITableViewCell")
        cell.textLabel?.text = product[indexPath.row]
        cell.detailTextLabel?.text = price[indexPath.row]
        return cell
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        print("You tapped cell number \(indexPath.row).")
    }
}

Selecting a Record With MAX Value

Note: An incorrect revision of this answer was edited out. Please review all answers.

A subselect in the WHERE clause to retrieve the greatest BALANCE aggregated over all rows. If multiple ID values share that balance value, all would be returned.

SELECT 
  ID,
  BALANCE
FROM CUSTOMERS
WHERE BALANCE = (SELECT MAX(BALANCE) FROM CUSTOMERS)

Use Awk to extract substring

Or just use cut:

echo aaa0.bbb.ccc | cut -d'.' -f1

How to format a URL to get a file from Amazon S3?

As @stevebot said, do this:

https://<bucket-name>.s3.amazonaws.com/<key>

The one important thing I would like to add is that you either have to make your bucket objects all publicly accessible OR you can add a custom policy to your bucket policy. That custom policy could allow traffic from your network IP range or a different credential.

How to search and replace text in a file?

I have worked this out as an exercise of a course: open file, find and replace string and write to a new file.

class Letter:

    def __init__(self):

        with open("./Input/Names/invited_names.txt", "r") as file:
            # read the list of names
            list_names = [line.rstrip() for line in file]
            with open("./Input/Letters/starting_letter.docx", "r") as f:
                # read letter
                file_source = f.read()
            for name in list_names:
                with open(f"./Output/ReadyToSend/LetterTo{name}.docx", "w") as f:
                    # replace [name] with name of the list in the file
                    replace_string = file_source.replace('[name]', name)
                    # write to a new file
                    f.write(replace_string)


brief = Letter()

AngularJS is rendering <br> as text not as a newline

Why so complicated?

I solved my problem this way simply:

  <pre>{{existingCategory+thisCategory}}</pre>

It will make <br /> automatically if the string contains '\n' that contain when I was saving data from textarea.

Accessing clicked element in angularjs

While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event argument to the setMaster function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):

function AdminController($scope) {    
  $scope.setMaster = function(obj, $event){
    console.log($event.target);
  }
}

this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.

The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event argument) would be:

<div ng-controller="AdminController">
    <ul class="list-holder">
        <li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
            <a ng-click="setMaster(section)">{{section.name}}</a>
        </li>
    </ul>
    <hr>
    {{selected | json}}
</div>

where methods in the controller would look like this:

$scope.setMaster = function(section) {
    $scope.selected = section;
}

$scope.isSelected = function(section) {
    return $scope.selected === section;
}

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/

OS X Terminal shortcut: Jump to beginning/end of line

You could download Better Touch Tools. It's an app that allows you to make custom key-bindings and shortcuts over your entire system or individual apps. Using it, you could make a shortcut in the terminal that emulates ctrl-a/ctrl-e whenever you press cmd-left/cmd-right, respectively. I definitely recommend it! I've been using it for years and I have over 50 shortcuts spread across several different apps.

Indent List in HTML and CSS

You can use [Adjacent sibling combinators] as described in the W3 CSS Selectors Recommendation1 So you can use a + sign (or even a ~ tilde) apply a padding to the nested ul tag, as you described in your question and you'll get the result you need. I also think what you want it to override the main css, locally. You can do this:

<style>
    li+ul {padding-left: 20px;}
</style>

This way the inner ul will be nested including the bullets of the li elements. I wish this was helpful! =)

jQuery - Create hidden form element on the fly

$('<input>').attr('type','hidden').appendTo('form');

To answer your second question:

$('<input>').attr({
    type: 'hidden',
    id: 'foo',
    name: 'bar'
}).appendTo('form');

How can I update my ADT in Eclipse?

You have updated the android sdk but not updated the adt to match with it.

You can update the adt from here

You might need to update the software source for your adt update

Go to eclipse > help > Check for updates.

It should list the latest update of adt. If it is not working try the same *Go to eclipse > help > Install new software * but now please do the follwing:

It will list the updates available- which should ideally be adt 20.xx

Eclipse will restart and hopefully everything should work fine for you.

Closing pyplot windows

plt.close() will close current instance.

plt.close(2) will close figure 2

plt.close(plot1) will close figure with instance plot1

plt.close('all') will close all fiures

Found here.

Remember that plt.show() is a blocking function, so in the example code you used above, plt.close() isn't being executed until the window is closed, which makes it redundant.

You can use plt.ion() at the beginning of your code to make it non-blocking, although this has other implications.

EXAMPLE

After our discussion in the comments, I've put together a bit of an example just to demonstrate how the plot functionality can be used.

Below I create a plot:

fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
....
par_plot, = plot(x_data,y_data, lw=2, color='red')

In this case, ax above is a handle to a pair of axes. Whenever I want to do something to these axes, I can change my current set of axes to this particular set by calling axes(ax).

par_plot is a handle to the line2D instance. This is called an artist. If I want to change a property of the line, like change the ydata, I can do so by referring to this handle.

I can also create a slider widget by doing the following:

axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)

The first line creates a new axes for the slider (called axsliderA), the second line creates a slider instance sA which is placed in the axes, and the third line specifies a function to call when the slider value changes (update).

My update function could look something like this:

def update(val):
    A = sA.val
    B = sB.val
    C = sC.val
    y_data = A*x_data*x_data + B*x_data + C
    par_plot.set_ydata(y_data)
    draw()

The par_plot.set_ydata(y_data) changes the ydata property of the Line2D object with the handle par_plot.

The draw() function updates the current set of axes.

Putting it all together:

from pylab import *
import matplotlib.pyplot as plt
import numpy

def update(val):
    A = sA.val
    B = sB.val
    C = sC.val
    y_data = A*x_data*x_data + B*x_data + C
    par_plot.set_ydata(y_data)
    draw()


x_data = numpy.arange(-100,100,0.1);

fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
subplots_adjust(top=0.8)

ax.set_xlim(-100, 100);
ax.set_ylim(-100, 100);
ax.set_xlabel('X')
ax.set_ylabel('Y')

axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)

axsliderB = axes([0.43, 0.85, 0.16, 0.075])
sB = Slider(axsliderB, 'B', -30, 30.0, valinit=2)
sB.on_changed(update)

axsliderC = axes([0.74, 0.85, 0.16, 0.075])
sC = Slider(axsliderC, 'C', -30, 30.0, valinit=1)
sC.on_changed(update)

axes(ax)
A = 1;
B = 2;
C = 1;
y_data = A*x_data*x_data + B*x_data + C;

par_plot, = plot(x_data,y_data, lw=2, color='red')

show()

A note about the above: When I run the application, the code runs sequentially right through (it stores the update function in memory, I think), until it hits show(), which is blocking. When you make a change to one of the sliders, it runs the update function from memory (I think?).

This is the reason why show() is implemented in the way it is, so that you can change values in the background by using functions to process the data.

How to use a App.config file in WPF applications?

This also works

WpfApplication1.Properties.Settings.Default["appsetting"].ToString()

pycharm convert tabs to spaces automatically

ctrl + shift + A => open pop window to select options, select to spaces to convert all tabs as space, or to tab to convert all spaces as tab.

How can I copy a file from a remote server to using Putty in Windows?

One of the putty tools is pscp.exe; it will allow you to copy files from your remote host.

Make TextBox uneditable

This is for GridView.

 grid.Rows[0].Cells[1].ReadOnly = true;

How to tag docker image with docker-compose

Original answer Nov 20 '15:

No option for a specific tag as of Today. Docker compose just does its magic and assigns a tag like you are seeing. You can always have some script call docker tag <image> <tag> after you call docker-compose.

Now there's an option as described above or here

build: ./dir
image: webapp:tag

How do I align a label and a textarea?

  1. Set the height of your label to the same height as the multiline textbox.
  2. Add the cssClass .alignTop{vertical-align: middle;} for the label control.

    <p>
        <asp:Label ID="DescriptionLabel" runat="server" Text="Description: " Width="70px" Height="200px" CssClass="alignTop"></asp:Label>
        <asp:Textbox id="DescriptionTextbox" runat="server" Width="400px" Height="200px" TextMode="MultiLine"></asp:Textbox>
        <asp:RequiredFieldValidator id="DescriptionRequiredFieldValidator" runat="server" ForeColor="Red"
        ControlToValidate="DescriptionTextbox" ErrorMessage="Description is a required field.">    
    </asp:RequiredFieldValidator>
    

IndexError: list index out of range and python

Always keep in mind when you want to overcome this error, the default value of indexing and range starts from 0, so if total items is 100 then l[99] and range(99) will give you access up to the last element.

whenever you get this type of error please cross check with items that comes between/middle in range, and insure that their index is not last if you get output then you have made perfect error that mentioned above.

Nesting CSS classes

Not directly. But you can use extensions such as LESS to help you achieve the same.

Class Diagrams in VS 2017

A further note on Dmitry's 2017 answer. I opened up

C:\Program Files (x86)\Microsoft Visual 
Studio\2017\Community\MSBuild\Microsoft\VisualStudio\Managed\ 
Microsoft.CSharp.DesignTime.targets 

and went to the <ProjectCapability> element. I already had this:

<ProjectCapability Include="
                          CSharp;
                          Managed;
                          ClassDesigner**;**" />

with ClassDesigner already there, and yet I was still unable to drag items to my hack-made Diagram.cd using the XML editing method Dmitry mentioned (

Manually create text file, say MyClasses.cd with following content:

<?xml version="1.0" encoding="utf-8"?> <ClassDiagram MajorVersion="1"
> MinorVersion="1">
>     <Font Name="Segoe UI" Size="9" /> </ClassDiagram>

). But when I took off the semicolon off 'ClassDesigner' in that element then reopened Visual Studio, voila, I was able to drag classes from my Solution Explorer to my Diagram.cd window.

So in conclusion, this element in Microsoft.CSharp.DesignTime.targets worked:

<ProjectCapability Include="
                              CSharp;
                              Managed;
                              ClassDesigner" />

I am using VS 2019, version 16.1.5.

Remove quotes from a character vector in R

If:

> char<-c("one", "two", "three")

You can:

> print(char[1],quote = FALSE)

Your result should be:

[1] one

How do I do a not equal in Django queryset filtering?

While you can filter Models with =, __gt, __gte, __lt, __lte, you cannot use ne or !=. However, you can achieve better filtering using the Q object.

You can avoid chaining QuerySet.filter() and QuerySet.exclude(), and use this:

from django.db.models import Q
object_list = QuerySet.filter(~Q(field='not wanted'), field='wanted')

Path to Powershell.exe (v 2.0)

I believe it's in C:\Windows\System32\WindowsPowershell\v1.0\. In order to confuse the innocent, MS kept it in a directory labeled "v1.0". Running this on Windows 7 and checking the version number via $Host.Version (Determine installed PowerShell version) shows it's 2.0.

Another option is type $PSVersionTable at the command prompt. If you are running v2.0, the output will be:

Name                           Value
----                           -----
CLRVersion                     2.0.50727.4927
BuildVersion                   6.1.7600.16385
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1

If you're running version 1.0, the variable doesn't exist and there will be no output.

Localization PowerShell version 1.0, 2.0, 3.0, 4.0:

  • 64 bits version: C:\Windows\System32\WindowsPowerShell\v1.0\
  • 32 bits version: C:\Windows\SysWOW64\WindowsPowerShell\v1.0\

Attempt to set a non-property-list object as an NSUserDefaults

Swift with @propertyWrapper

Save Codable object to UserDefault

@propertyWrapper
    struct UserDefault<T: Codable> {
        let key: String
        let defaultValue: T

        init(_ key: String, defaultValue: T) {
            self.key = key
            self.defaultValue = defaultValue
        }

        var wrappedValue: T {
            get {

                if let data = UserDefaults.standard.object(forKey: key) as? Data,
                    let user = try? JSONDecoder().decode(T.self, from: data) {
                    return user

                }

                return  defaultValue
            }
            set {
                if let encoded = try? JSONEncoder().encode(newValue) {
                    UserDefaults.standard.set(encoded, forKey: key)
                }
            }
        }
    }




enum GlobalSettings {

    @UserDefault("user", defaultValue: User(name:"",pass:"")) static var user: User
}

Example User model confirm Codable

struct User:Codable {
    let name:String
    let pass:String
}

How to use it

//Set value 
 GlobalSettings.user = User(name: "Ahmed", pass: "Ahmed")

//GetValue
print(GlobalSettings.user)

Javascript: 'window' is not defined

Trying to access an undefined variable will throw you a ReferenceError.

A solution to this is to use typeof:

if (typeof window === "undefined") {
  console.log("Oops, `window` is not defined")
}

or a try catch:

try { window } catch (err) {
  console.log("Oops, `window` is not defined")
}

While typeof window is probably the cleanest of the two, the try catch can still be useful in some cases.

How do I find the date a video (.AVI .MP4) was actually recorded?

Have a try to exiftools or mediainfo, which provides you an export function as text. Just pay attention to daylight saving.

NodeJS: How to decode base64 encoded string back to binary?

As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:

var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da

For Node.js v5.11.1 and below

Construct a new Buffer and pass 'base64' as the second argument:

var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da

If you want to be clean, you can check whether from exists :

if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions, now deprecated
    buf = new Buffer(b64string, 'base64'); // Ta-da
}

How to split large text file in windows?

You can use the command split for this task. For example this command entered into the command prompt

split YourLogFile.txt -b 500m

creates several files with a size of 500 MByte each. This will take several minutes for a file of your size. You can rename the output files (by default called "xaa", "xab",... and so on) to *.txt to open it in the editor of your choice.

Make sure to check the help file for the command. You can also split the log file by number of lines or change the name of your output files.

(tested on Windows 7 64 bit)

String or binary data would be truncated. The statement has been terminated

In my case, I was getting this error because my table had

varchar(50)

but I was injecting 67 character long string, which resulted in thi error. Changing it to

varchar(255)

fixed the problem.

Editing the date formatting of x-axis tick labels in matplotlib

While the answer given by Paul H shows the essential part, it is not a complete example. On the other hand the matplotlib example seems rather complicated and does not show how to use days.

So for everyone in need here is a full working example:

from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

myDates = [datetime(2012,1,i+3) for i in range(10)]
myValues = [5,6,4,3,7,8,1,2,5,4]
fig, ax = plt.subplots()
ax.plot(myDates,myValues)

myFmt = DateFormatter("%d")
ax.xaxis.set_major_formatter(myFmt)

## Rotate date labels automatically
fig.autofmt_xdate()
plt.show()

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE

MySQL will assume the part before the equals references the columns named in the INSERT INTO clause, and the second part references the SELECT columns.

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, 
                inact, inadur, inadist, 
                smlct, smldur, smldist, 
                larct, lardur, lardist, 
                emptyct, emptydur)
SELECT id, uid, t.location, t.animal, t.starttime, t.endtime, t.entct, 
       t.inact, t.inadur, t.inadist, 
       t.smlct, t.smldur, t.smldist, 
       t.larct, t.lardur, t.lardist, 
       t.emptyct, t.emptydur 
FROM tmp t WHERE uid=x
ON DUPLICATE KEY UPDATE entct=t.entct, inact=t.inact, ...

How to send emails from my Android application?

 Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
            "mailto","[email protected]", null));
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Forgot Password");
    emailIntent.putExtra(Intent.EXTRA_TEXT, "Write your Pubg user name or Phone Number");
    startActivity(Intent.createChooser(emailIntent, "Send email..."));**strong text**

How to align linearlayout to vertical center?

use RelativeLayout inside LinearLayout

example:

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:text="Status"/>
        </RelativeLayout>
</LinearLayout>

Convert js Array() to JSon object for use with JQuery .ajax

Don't make it an Array if it is not an Array, make it an object:

var saveData = {};
saveData.a = 2;
saveData.c = 1;

// equivalent to...
var saveData = {a: 2, c: 1}

// equivalent to....
var saveData = {};
saveData['a'] = 2;
saveData['c'] = 1;

Doing it the way you are doing it with Arrays is just taking advantage of Javascript's treatment of Arrays and not really the right way of doing it.

Connection string using Windows Authentication

Replace the username and password with Integrated Security=SSPI;

So the connection string should be

<connectionStrings> 
<add name="NorthwindContex" 
   connectionString="data source=localhost;
   initial catalog=northwind;persist security info=True; 
   Integrated Security=SSPI;" 
   providerName="System.Data.SqlClient" /> 
</connectionStrings> 

Access all Environment properties as a Map or Properties object

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

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

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

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

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

    return result;
}

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

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

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

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

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

    return result;

}

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

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

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

@Autowired
private ConfigurableEnvironment  myEnv;

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

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

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

myEnv.getProperty( key );

How to select a schema in postgres when using psql?

if playing with psql inside docker exec it like this:

docker exec -e "PGOPTIONS=--search_path=<your_schema>" -it docker_pg psql -U user db_name

warning about too many open figures

This is also useful if you only want to temporarily suppress the warning:

import matplotlib.pyplot as plt
       
with plt.rc_context(rc={'figure.max_open_warning': 0}):
    lots_of_plots()

Access a global variable in a PHP function

It's a matter of scope. In short, global variables should be avoided so:

You either need to pass it as a parameter:

$data = 'My data';

function menugen($data)
{
    echo $data;
}

Or have it in a class and access it

class MyClass
{
    private $data = "";

    function menugen()
    {
        echo this->data;
    }

}

See @MatteoTassinari answer as well, as you can mark it as global to access it, but global variables are generally not required, so it would be wise to re-think your coding.

How to change indentation in Visual Studio Code?

Problem: The accepted answer does not actually fix the indentation in the current document.

Solution: Run Format Document to re-process the document according to current (new) settings.

Problem: The HTML docs in my projects are of type "Django HTML" not "HTML" and there is no formatter available.

Solution: Switch them to syntax "HTML", format them, then switch back to "Django HTML."

Problem: The HTML formatter doesn't know how to handle Django template tags and undoes much of my carefully applied nesting.

Solution: Install the Indent 4-2 extension, which performs indentation strictly, without regard to the current language syntax (which is what I want in this case).

Symfony 2 EntityManager injection in service

Since 2017 and Symfony 3.3 you can register Repository as service, with all its advantages it has.

Check my post How to use Repository with Doctrine as Service in Symfony for more general description.


To your specific case, original code with tuning would look like this:

1. Use in your services or Controller

<?php

namespace Test\CommonBundle\Services;

use Doctrine\ORM\EntityManagerInterface;

class UserService
{
    private $userRepository;

    // use custom repository over direct use of EntityManager
    // see step 2
    public function __constructor(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function getUser($userId)
    {
        return $this->userRepository->find($userId);
    }
}

2. Create new custom repository

<?php

namespace Test\CommonBundle\Repository;

use Doctrine\ORM\EntityManagerInterface;

class UserRepository
{
    private $repository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->repository = $entityManager->getRepository(UserEntity::class);
    }

    public function find($userId)
    {
        return  $this->repository->find($userId);
    }
}

3. Register services

# app/config/services.yml
services:
    _defaults:
        autowire: true

    Test\CommonBundle\:
       resource: ../../Test/CommonBundle

Inserting data into a temporary table

To insert all data from all columns, just use this:

SELECT * INTO #TempTable
FROM OriginalTable

Don't forget to DROP the temporary table after you have finished with it and before you try creating it again:

DROP TABLE #TempTable

Requested bean is currently in creation: Is there an unresolvable circular reference?

I think you could use Spring's

@Lazy

annotation on one of the autowired fields to break circular dependency.

I'm not sure if this works/exists in mentioned Spring version.

How to find out if you're using HTTPS without $_SERVER['HTTPS']

On my server (Ubuntu 14.10, Apache 2.4, php 5.5) variable $_SERVER['HTTPS'] is not set when php script is loaded via https. I don't know what is wrong. But following lines in .htaccess file fix this problem:

RewriteEngine on

RewriteCond %{HTTPS} =on [NC] 
RewriteRule .* - [E=HTTPS:on,NE]

Reading Data From Database and storing in Array List object

I am trying to fetch record from database first and store in ArrayList but when i return array list on html page it display only last record repeatedly as count of my database table

This part has mostly been covered by all the previous answers. So you would need to create a new instance of your CustomerDTO within your while loop and add it to your ArrayList.

There's one more thing that I wanted to comment about:

  • Make sure that you release all your resources after you're done using them. From the code that you've posted, you've not closed your Statement or your Connection objects (not so sure if you're pooling your connection, in that case you would need to release this connection to the pool)

So, when you consider these points, the structure of your code might look something like this:

public ArrayList<CustomerDTO> getAllCustomers() 
{
    ArrayList<CustomerDTO> customers = new ArrayList<CustomerDTO>();
    Connection c = null;
    Statement statement = null;
    ResultSet rs        = null;

    try {
        c           = openConnection();
        statement   = c.createStatement();
        String s    = "SELECT * FROM customer";

        rs          = statement.executeQuery(s);
        int g =0;

        while (rs.next()) {
            CustomerDTO customer = new CustomerDTO();
            //Code to fill up your DTO
            customers.add(customer);
        }
    } catch (Exception e) {
        System.out.println(e);
    }finally{
        //Code to release your resources
    }

    return customers;
}

MVC4 HTTP Error 403.14 - Forbidden

Before applying

runAllManagedModulesForAllRequests="true"/>

consider the link below that suggests a less drastic alternative. In the post the author offers the following alteration to the local web.config:

  <system.webServer>
    <modules>
    <remove name="UrlRoutingModule-4.0" />
    <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
    </modules>

http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html

Does a finally block always get executed in Java?

Finally is always run that's the whole point, just because it appears in the code after the return doesn't mean that that's how it's implemented. The Java runtime has the responsibility to run this code when exiting the try block.

For example if you have the following:

int foo() { 
    try {
        return 42;
    }
    finally {
        System.out.println("done");
    }
}

The runtime will generate something like this:

int foo() {
    int ret = 42;
    System.out.println("done");
    return 42;
}

If an uncaught exception is thrown the finally block will run and the exception will continue propagating.

What file uses .md extension and how should I edit them?

Microsoft's Visual Studio Code text editor has built in support for .md files written in markdown syntax.

The syntax is automatically color-coded inside of the .md file, and a preview window of the rendered markdown can be viewed by pressing Shift+Ctrl+V (Windows) or Shift+Cmd+V (Mac).

To see them side-by-side, drag the preview tab to the right side of the editor, or use Ctrl+K V (Windows) or Cmd+K V (Mac) instead.

enter image description here

VS Code uses the marked library for parsing, and has Github Flavored Markdown support enabled by default, but it will not display the Github Emoji inline like Github's Atom text editor does.

Also, VS Code supports has several markdown plugins available for extended functionality.

How do I create a unique ID in Java?

Generate Unique ID Using Java

UUID is the fastest and easiest way to generate unique ID in Java.

import java.util.UUID;

public class UniqueIDTest {
  public static void main(String[] args) {
    UUID uniqueKey = UUID.randomUUID();
    System.out.println (uniqueKey);
  }
}

Twitter Bootstrap modal on mobile devices

Albeit this question is quite old, some people still may stumble upon it when looking for solution to improve UX of modals on mobile phones.

I've made a lib to improve Bootrsrap modals' behavior on phones.

Bootstrap 3: https://github.com/keaukraine/bootstrap-fs-modal

Bootstrap 4: https://github.com/keaukraine/bootstrap4-fs-modal

How to build a 'release' APK in Android Studio?

Follow this steps:

-Build
-Generate Signed Apk
-Create new

Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)

enter image description here

enter image description here enter image description here

enter image description here enter image description here

Java foreach loop: for (Integer i : list) { ... }

One way to do that is to use a counter:

ArrayList<Integer> list = new ArrayList<Integer>();
...
int size = list.size();
for (Integer i : list) { 
    ...
    if (--size == 0) {
        // Last item.
        ...
    }
}

Edit

Anyway, as Tom Hawtin said, it is sometimes better to use the "old" syntax when you need to get the current index information, by using a for loop or the iterator, as everything you win when using the Java5 syntax will be lost in the loop itself...

for (int i = 0; i < list.size(); i++) {
    ...

    if (i == (list.size() - 1)) {
        // Last item...
    }
}

or

for (Iterator it = list.iterator(); it.hasNext(); ) {
    ...

    if (!it.hasNext()) {
        // Last item...
    }
}

How can I add NSAppTransportSecurity to my info.plist file?

Xcode 9.2, Swift 4, this works for me.

<key>App Transport Security Settings</key>
<dict>
    <key>Allow Arbitrary Loads</key>
    <true/>
</dict>

pip install gives error: Unable to find vcvarsall.bat

I spent hours researching this vcvarsall.bat as well. Most answers on SO focus on Python 2.7 and / or creating workarounds by modifying system paths. None worked for me. This solution worked out of the box for Python 3.5 and (I think) is the "correct" way of doing it.

  1. See this link -- it describes the Windows Compilers to use for different versions of Python: https://wiki.python.org/moin/WindowsCompilers#Microsoft_Visual_C.2B-.2B-_14.0_standalone:_Visual_C.2B-.2B-_Build_Tools_2015_.28x86.2C_x64.2C_ARM.29

  2. For Python 3.5, download this: https://www.microsoft.com/en-us/download/details.aspx?id=49983

  3. For me, I had to run C:\Program Files (x86)\Microsoft Visual C++ Build Tools\Visual C++ x64 Native Build Tools Command Prompt for it to work. From that command prompt, I ran "pip install django_compressor" which was the particular package that was causing me an issue, and it worked perfectly.

Hope this saves someone some time!

MySQL timestamp select date range

Usually it would be this:

SELECT * 
  FROM yourtable
 WHERE yourtimetimefield>='2010-10-01'
   AND yourtimetimefield< '2010-11-01'

But because you have a unix timestamps, you'll need something like this:

SELECT * 
  FROM yourtable
 WHERE yourtimetimefield>=unix_timestamp('2010-10-01')
   AND yourtimetimefield< unix_timestamp('2010-11-01')

How to display alt text for an image in chrome

I use this, it works with php...

<span><?php
if (file_exists("image/".$data['img_name'])) {
  ?>
  <img src="image/<?php echo $data['img_name']; ?>" width="100" height="100">
  <?php
}else{
  echo "Image Not Found";
}>?
</span>

Essentially what the code is doing, is checking for the File. The $data variable will be used with our array then actually make the desired change. If it isn't found, it will throw an Exception.

How do I print the elements of a C++ vector in GDB?

A little late to the party, so mostly a reminder to me next time I do this search!

I have been able to use:

p/x *(&vec[2])@4

to print 4 elements (as hex) from vec starting at vec[2].

How can I get the corresponding table header (th) from a table cell (td)?

That's simple, if you reference them by index. If you want to hide the first column, you would:

Copy code

$('#thetable tr').find('td:nth-child(1),th:nth-child(1)').toggle();

The reason I first selected all table rows and then both td's and th's that were the n'th child is so that we wouldn't have to select the table and all table rows twice. This improves script execution speed. Keep in mind, nth-child() is 1 based, not 0.

How to add a Hint in spinner in XML

It is very simple if position is '0' then call onNothingSelected method in OnItemSelectedListener. It worked fine for me.

      spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            **if (position == 0)
            {
                onNothingSelected(parent);
            }**
            else {

                String mechanicType = mechanicTpes[position];
                Toast.makeText(FirstUser.this, "Mechanic Tpye : "+mechanicType, Toast.LENGTH_SHORT).show();
            }




        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            Toast.makeText(FirstUser.this, "NOTHING SELECTED IN SPINNER", Toast.LENGTH_SHORT).show();


        }
    });

How to create a file on Android Internal Storage?

Write a file

When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:

getFilesDir()

      Returns a File representing an internal directory for your app.

getCacheDir()

     Returns a File representing an internal directory for your 
     app's temporary cache files.
     Be sure to delete each file once it is no longer needed and implement a reasonable 
     size limit for the amount of memory you use at any given time, such as 1MB.

Caution: If the system runs low on storage, it may delete your cache files without warning.

addID in jQuery?

I've used something like this before which addresses @scunliffes concern. It finds all instances of items with a class of (in this case .button), and assigns an ID and appends its index to the id name:

_x000D_
_x000D_
$(".button").attr('id', function (index) {_x000D_
 return "button-" + index;_x000D_
});
_x000D_
_x000D_
_x000D_

So let's say you have 3 items with the class name of .button on a page. The result would be adding a unique ID to all of them (in addition to their class of "button").

In this case, #button-0, #button-1, #button-2, respectively. This can come in very handy. Simply replace ".button" in the first line with whatever class you want to target, and replace "button" in the return statement with whatever you'd like your unique ID to be. Hope this helps!

How are parameters sent in an HTTP POST request?

Some of the webservices require you to place request data and metadata separately. For example a remote function may expect that the signed metadata string is included in a URI, while the data is posted in a HTTP-body.

The POST request may semantically look like this:

POST /?AuthId=YOURKEY&Action=WebServiceAction&Signature=rcLXfkPldrYm04 HTTP/1.1
Content-Type: text/tab-separated-values; charset=iso-8859-1
Content-Length: []
Host: webservices.domain.com
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: identity
User-Agent: Mozilla/3.0 (compatible; Indy Library)

name    id
John    G12N
Sarah   J87M
Bob     N33Y

This approach logically combines QueryString and Body-Post using a single Content-Type which is a "parsing-instruction" for a web-server.

Please note: HTTP/1.1 is wrapped with the #32 (space) on the left and with #10 (Line feed) on the right.

Android Studio: Where is the Compiler Error Output Window?

It's really straightforward to set up! Just go to the Compiler settings at Android Studio 2.2.3 and set the --stacktrace command:

Compiler settings to add --stacktrace command

Then run the app again

"Too many characters in character literal error"

Here's an example:

char myChar = '|';
string myString = "||";

Chars are delimited by single quotes, and strings by double quotes.

The good news is C# switch statements work with strings!

switch (mytoken)
{
    case "==":
        //Something here.
        break;
    default:
        //Handle when no token is found.
        break;
}

How can I make a UITextField move up when the keyboard is present - on starting to edit?

Swift 2.0:

Add a UIScrollView and add textFields on the top of it. Make storyboard references to VC.

@IBOutlet weak var username: UITextField!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var scrollView: UIScrollView!

Add these methods : UITextFieldDelegate & UIScrollViewDelegate.

//MARK:- TEXTFIELD METHODS
    func textFieldShouldReturn(textField: UITextField) -> Bool {

        if(username.returnKeyType == UIReturnKeyType.Default) {
            password.becomeFirstResponder()
        }
        textField.resignFirstResponder()
        return true
    }
    func textFieldDidBeginEditing(textField: UITextField) {

        dispatch_async(dispatch_get_main_queue()) {

            let scrollPoint:CGPoint = CGPointMake(0,textField.frame.origin.y/4)
            self.scrollView!.setContentOffset(scrollPoint, animated: true);
        }
    }
    func textFieldShouldEndEditing(textField: UITextField) -> Bool {

        dispatch_async(dispatch_get_main_queue()) {
          UIView.animateWithDuration(0, animations: { self.scrollView!.setContentOffset(CGPointZero,animated: true) })
        }
        return true
    }
    override func touchesBegan(touches: Set<UITouch>,
        withEvent event: UIEvent?) {
            self.view.endEditing(true)
    }
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.scrollView.scrollEnabled =  true

        dispatch_async(dispatch_get_main_queue()) {
            UIView.animateWithDuration(0, animations: { self.scrollView!.setContentOffset(CGPointZero,animated: true)

            })
        }
    }

Multiple conditions in if statement shell script

You are trying to compare strings inside an arithmetic command (((...))). Use [[ instead.

if [[ $username == "$username1" && $password == "$password1" ]] ||
   [[ $username == "$username2" && $password == "$password2" ]]; then

Note that I've reduced this to two separate tests joined by ||, with the && moved inside the tests. This is because the shell operators && and || have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d is equivalent to the intended ( a && b ) || ( c && d ).

Is there a way to cast float as a decimal without rounding and preserving its precision?

cast (field1 as decimal(53,8)
) field 1

The default is: decimal(18,0)

What is the most appropriate way to store user settings in Android application

About the simplest way to store a single preference in an Android Activity is to do something like this:

Editor e = this.getPreferences(Context.MODE_PRIVATE).edit();
e.putString("password", mPassword);
e.commit();

If you're worried about the security of these then you could always encrypt the password before storing it.

Convert row to column header for Pandas DataFrame,

You can specify the row index in the read_csv or read_html constructors via the header parameter which represents Row number(s) to use as the column names, and the start of the data. This has the advantage of automatically dropping all the preceding rows which supposedly are junk.

import pandas as pd
from io import StringIO

In[1]
    csv = '''junk1, junk2, junk3, junk4, junk5
    junk1, junk2, junk3, junk4, junk5
    pears, apples, lemons, plums, other
    40, 50, 61, 72, 85
    '''

    df = pd.read_csv(StringIO(csv), header=2)
    print(df)

Out[1]
       pears   apples   lemons   plums   other
    0     40       50       61      72      85

How to create a HTML Table from a PHP array?

    <table>
      <thead>
        <tr><th>title</th><th>price><th>number</th></tr>
      </thead>
      <tbody>
<?php
  foreach ($shop as $row) {
    echo '<tr>';
    foreach ($row as $item) {
      echo "<td>{$item}</td>";
    }
    echo '</tr>';
  }
?>
      </tbody>
    </table>

Watching variables in SSIS during debug

I know this is very old and possibly talking about an older version of Visual studio and so this might not have been an option before but anyway, my way would be when at a breakpoint use the locals window to see all current variable values ( Debug >> Windows >> Locals )

Matplotlib transparent line plots

After I plotted all the lines, I was able to set the transparency of all of them as follows:

for l in fig_field.gca().lines:
    l.set_alpha(.7)

EDIT: please see Joe's answer in the comments.

java.io.FileNotFoundException: /storage/emulated/0/New file.txt: open failed: EACCES (Permission denied)

Implement runtime permission for running your app on Android 6.0 Marshmallow (API 23) or later.

or you can manually enable the storage permission-

goto settings>apps> "your_app_name" >click on it >then click permissions> then enable the storage. Thats it.

But i suggest go the for first one which is, Implement runtime permissions in your code.

How do you connect localhost in the Android emulator?

Instead of giving localhost give the IP.

How to download fetch response in react as file

I needed to just download a file onClick but I needed to run some logic to either fetch or compute the actual url where the file existed. I also did not want to use any anti-react imperative patterns like setting a ref and manually clicking it when I had the resource url. The declarative pattern I used was

onClick = () => {
  // do something to compute or go fetch
  // the url we need from the server
  const url = goComputeOrFetchURL();

  // window.location forces the browser to prompt the user if they want to download it
  window.location = url
}

render() {
  return (
    <Button onClick={ this.onClick } />
  );
}

Downgrade npm to an older version

Just replace @latest with the version number you want to downgrade to. I wanted to downgrade to version 3.10.10, so I used this command:

npm install -g [email protected]

If you're not sure which version you should use, look at the version history. For example, you can see that 3.10.10 is the latest version of npm 3.

Should I use past or present tense in git commit messages?

Your project should almost always use the past tense. In any case, the project should always use the same tense for consistency and clarity.

I understand some of the other arguments arguing to use the present tense, but they usually don't apply. The following bullet points are common arguments for writing in the present tense, and my response.

  • Writing in the present tense tells someone what applying the commit will do, rather than what you did.

This is the most correct reason one would want to use the present tense, but only with the right style of project. This manner of thinking considers all commits as optional improvements or features, and you are free to decide which commits to keep and which to reject in your particular repository.

This argument works if you are dealing with a truly distributed project. If you are dealing with a distributed project, you are probably working on an open source project. And it is probably a very large project if it is really distributed. In fact, it's probably either the Linux kernel or Git. Since Linux is likely what caused Git to spread and gain in popularity, it's easy to understand why people would consider its style the authority. Yes, the style makes sense with those two projects. Or, in general, it works with large, open source, distributed projects.

That being said, most projects in source control do not work like this. It is usually incorrect for most repositories. It's a modern way of thinking about a commits: Subversion (SVN) and CVS repositories could barely support this style of repository check-ins. Usually an integration branch handled filtering bad check-ins, but those generally weren't considered "optional" or "nice-to-have features".

In most scenarios, when you are making commits to a source repository, you are writing a journal entry which describes what changed with this update, to make it easier for others in the future to understand why a change was made. It generally isn't an optional change - other people in the project are required to either merge or rebase on it. You don't write a diary entry such as "Dear diary, today I meet a boy and he says hello to me.", but instead you write "I met a boy and he said hello to me."

Finally, for such non-distributed projects, 99.99% of the time a person will be reading a commit message is for reading history - history is read in the past tense. 0.01% of the time it will be deciding whether or not they should apply this commit or integrate it into their branch/repository.

  • Consistency. That's how it is in many projects (including git itself). Also git tools that generate commits (like git merge or git revert) do it.

No, I guarantee you that the majority of projects ever logged in a version control system have had their history in the past tense (I don't have references, but it's probably right, considering the present tense argument is new since Git). "Revision" messages or commit messages in the present tense only started making sense in truly distributed projects - see the first point above.

  • People not only read history to know "what happened to this codebase", but also to answer questions like "what happens when I cherry-pick this commit", or "what kind of new things will happen to my code base because of these commits I may or may not merge in the future".

See the first point. 99.99% of the time a person will be reading a commit message is for reading history - history is read in the past tense. 0.01% of the time it will be deciding whether or not they should apply this commit or integrate it into their branch/repository. 99.99% beats 0.01%.

  • It's usually shorter

I've never seen a good argument that says use improper tense/grammar because it's shorter. You'll probably only save 3 characters on average for a standard 50 character message. That being said, the present tense on average will probably be a few characters shorter.

  • You can name commits more consistently with titles of tickets in your issue/feature tracker (which don't use past tense, although sometimes future)

Tickets are written as either something that is currently happening (e.g. the app is showing the wrong behavior when I click this button), or something that needs to be done in the future (e.g. the text will need a review by the editor).

History (i.e. commit messages) is written as something that was done in the past (e.g. the problem was fixed).

How to uninstall with msiexec using product id guid without .msi file present

"Reference-Style" Answer: This is an alternative answer to the one below with several different options shown. Uninstalling an MSI file from the command line without using msiexec.


The command you specify is correct: msiexec /x {A4BFF20C-A21E-4720-88E5-79D5A5AEB2E8}

If you get "This action is only valid for products that are currently installed" you have used an unrecognized product or package code, and you must find the right one. Often this can be caused by using an erroneous package code instead of a product code to uninstall - a package code changes with every rebuild of an MSI file, and is the only guid you see when you view an msi file's property page. It should work for uninstall, provided you use the right one. No room for error. If you want to find the product code instead, you need to open the MSI. The product code is found in the Property table.


UPDATE, Jan 2018:

With all the registry redirects going on, I am not sure the below registry-based approach is a viable option anymore. I haven't checked properly because I now rely on the following approach using PowerShell: How can I find the product GUID of an installed MSI setup?

Also check this reference-style answer describing different ways to uninstall an MSI package and ways to determine what product version you have installed: Uninstalling an MSI file from the command line without using msiexec


Legacy, registry option:

You can also find the product code by perusing the registry from this base key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall . Press F3 and search for your product name. (If it's a 32-bit installer on a 64-bit machine, it might be under HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall instead).

Legacy, PowerShell option: (largely similar to the new, linked answer above)

Finally, you can find the product code by using PowerShell:

get-wmiobject Win32_Product | Format-Table IdentifyingNumber, Name

enter image description here

Similar post: WiX - Doing a major upgrade on a multi instance install (screenshot of how to find the product code in the MSI).

How to put space character into a string name in XML?

If you are trying to give Space Between 2 string OR In String file of android then do this in your string file . Implement this before your "String name" that you want to show. \u0020\u0020 For E.g.. \u0020\u0020\u0020\u0020\u0020\u0020Payment

get one item from an array of name,value JSON

I don't know anything about jquery so can't help you with that, but as far as Javascript is concerned you have an array of objects, so what you will only be able to access the names & values through each array element. E.g arr[0].name will give you 'k1', arr[1].value will give you 'hi'.

Maybe you want to do something like:

var obj = {};

obj.k1 = "abc";
obj.k2 = "hi";
obj.k3 = "oa";

alert ("obj.k2:" + obj.k2);

How can I check if character in a string is a letter? (Python)

This works:

word = str(input("Enter string:"))
notChar = 0
isChar = 0
for char in word:
    if not char.isalpha():
        notChar += 1
    else:
        isChar += 1
print(isChar, " were letters; ", notChar, " were not letters.")

Firebase TIMESTAMP to date and Time

Solution for newer versions of Firebase (after Jan 2016)

The proper way to attach a timestamp to a database update is to attach a placeholder value in your request. In the example below Firebase will replace the createdAt property with a timestamp:

firebaseRef = firebase.database().ref();
firebaseRef.set({
  foo: "bar", 
  createdAt: firebase.database.ServerValue.TIMESTAMP
});

According to the documentation, the value firebase.database.ServerValue.TIMESTAMP is: "A placeholder value for auto-populating the current timestamp (time since the Unix epoch, in milliseconds) by the Firebase Database servers."

Get all variables sent with POST?

Why not this, it's easy:

extract($_POST);

Splitting a Java String by the pipe symbol using split("|")

the split() method takes a regular expression as an argument

How do you clear Apache Maven's cache?

Have you checked/changed the updatePolicy settings for your repositories in your settings.xml.

This element specifies how often updates should attempt to occur. Maven will compare the local POM's timestamp (stored in a repository's maven-metadata file) to the remote. The choices are: always, daily (default), interval:X (where X is an integer in minutes) or never.

Try to set it to always.

Phonegap + jQuery Mobile, real world sample or tutorial

you may check this website: Phonegap RSS feeds, Javascript, this is an example about rss reader which uses the phonegap and jquery-mobile techniques

Passing parameters to a Bash function

Drop the parentheses and commas:

 myBackupFunction ".." "..." "xx"

And the function should look like this:

function myBackupFunction() {
    # Here $1 is the first parameter, $2 the second, etc.
}

Showing all session data at once?

here is code:

<?php echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>'; ?>

What's is the difference between include and extend in use case diagram?

Use cases are used to document behavior, e.g. answer this question.

answer the question use case

A behavior extends another if it is in addition to but not necessarily part of the behavior, e.g. research the answer.

Also note that researching the answer doesn't make much sense if you are not trying to answer the question.

research the answer extend

A behavior is included in another if it is part of the including behavior, e.g. login to stack exchange.

login to stack exchange include

To clarify, the illustration is only true if you want to answer here in stack overflow :).

These are the technical definitions from UML 2.5 pages 671-672.

I highlighted what I think are important points.

Extends

An Extend is a relationship from an extending UseCase (the extension) to an extended UseCase (the extendedCase) that specifies how and when the behavior defined in the extending UseCase can be inserted into the behavior defined in the extended UseCase. The extension takes place at one or more specific extension points defined in the extended UseCase.

Extend is intended to be used when there is some additional behavior that should be added, possibly conditionally, to the behavior defined in one or more UseCases.

The extended UseCase is defined independently of the extending UseCase and is meaningful independently of the extending UseCase. On the other hand, the extending UseCase typically defines behavior that may not necessarily be meaningful by itself. Instead, the extending UseCase defines a set of modular behavior increments that augment an execution of the extended UseCase under specific conditions.

...

Includes

Include is a DirectedRelationship between two UseCases, indicating that the behavior of the included UseCase (the addition) is inserted into the behavior of the including UseCase (the includingCase). It is also a kind of NamedElement so that it can have a name in the context of its owning UseCase (the includingCase). The including UseCase may depend on the changes produced by executing the included UseCase. The included UseCase must be available for the behavior of the including UseCase to be completely described.

The Include relationship is intended to be used when there are common parts of the behavior of two or more UseCases. This common part is then extracted to a separate UseCase, to be included by all the base UseCases having this part in common. As the primary use of the Include relationship is for reuse of common parts, what is left in a base UseCase is usually not complete in itself but dependent on the included parts to be meaningful. This is reflected in the direction of the relationship, indicating that the base UseCase depends on the addition but not vice versa.

...

Joining two table entities in Spring Data JPA

This has been an old question but solution is very simple to that. If you are ever unsure about how to write criterias, joins etc in hibernate then best way is using native queries. This doesn't slow the performance and very useful. Eq. below

    @Query(nativeQuery = true, value = "your sql query")
returnTypeOfMethod methodName(arg1, arg2);

How to debug apk signed for release?

Besides Manuel's way, you can still use the Manifest.

In Android Studio stable, you have to add the following 2 lines to application in the AndroidManifest file:

    android:debuggable="true"
    tools:ignore="HardcodedDebugMode"

The first one will enable debugging of signed APK, and the second one will prevent compile-time error.

After this, you can attach to the process via "Attach debugger to Android process" button.

Angular - "has no exported member 'Observable'"

You are using RxJS 6. Just replace

import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

by

import { Observable, of } from 'rxjs';

Browser Timeouts

It's browser dependent. "By default, Internet Explorer has a KeepAliveTimeout value of one minute and an additional limiting factor (ServerInfoTimeout) of two minutes. Either setting can cause Internet Explorer to reset the socket." - from IE support http://support.microsoft.com/kb/813827

Firefox is around the same value I think as well.

Usually though server timeout are set lower than browser timeouts, but at least you can control that and set it higher.

You'd rather handle the timeout though, so that way you can act upon such an event. See this thread: How to detect timeout on an AJAX (XmlHttpRequest) call in the browser?

How to iterate over a column vector in Matlab?

If you just want to apply a function to each element and put the results in an output array, you can use arrayfun.

As others have pointed out, for most operations, it's best to avoid loops in MATLAB and vectorise your code instead.