Programs & Examples On #Application server

An application server is a software framework dedicated to the efficient execution of procedures (programs, routines, scripts) for supporting the construction of applications. Normally the term refers to Java application servers. When this is the case, the application server behaves like an extended virtual machine for the running applications, handling transparently connections to the database at one side, and connections to the web client at the other.

Difference between web server, web container and application server

Web Server: It provides HTTP Request and HTTP response. It handles request from client only through HTTP protocol. It contains Web Container. Web Application mostly deployed on web Server. EX: Servlet JSP

Web Container: it maintains the life cycle for Servlet Object. Calls the service method for that servlet object. pass the HttpServletRequest and HttpServletResponse Object

Application Server: It holds big Enterprise application having big business logic. It is Heavy Weight or it holds Heavy weight Applications. Ex: EJB

What is the difference between application server and web server?

Basic understanding :

In client server architecture

Server :> Which serves the requests.

Client :> Which consumes service.

Web server & Application server are both software applications which act as servers to their clients.

They got their names based on their place of utilization.

Web server :> serve web content
           :> Like Html components
           :> Like Javascript components
           :> Other web components like images,resource files
           :> Supports mainly web protocols like http,https.
           :> Supports web Request & Response formats.

Usage --

      we require low processing rates,

      regular processing practices involves.

Eg: All flat servers generally available ready-made which serves only web based content.

Application server :> Serve application content/component data(Business data).
                   :> These are special kind which are custom written 
                      designed/engineered for specific
                      purpose.some times fully unique in 
                      their way and stands out of the crowd. 

                   :> As these serves different types of data/response contents
                   :> So we can utilize these services for mobile client,web 
                      clients,intranet clients. 
                   :> Usually application servers are services offered on different 
                      protocols.    
                   :> Supports different Request& Response formats.

Usage --

      we require multi point processing,

      specialized processing techniques involves like for AI.

Eg: Google maps servers, Google search servers,Google docs servers,Microsoft 365 servers,Microsoft computer vision servers for AI.

We can assume them as tiers/Hierarchies in 4-tier/n-tier architecture.

 So they can provide 
                    load balancing,
                    multiple security levels,
                    multiple active points,
                    even they can provide different request processing environments.

Please follow this link for standard architecture analogies:

https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ee658120(v%3dpandp.10)

Tomcat is web server or application server?

Tomcat is an application container that is also a web server. An application container can run web-applications (have "application" scope). It is not considered Some people do not consider it a full application server as it is lacking in some aspects such as user management and the like, but getting better all the time..

Python: PIP install path, what is the correct location for this and other addons?

Since pip is an executable and which returns path of executables or filenames in environment. It is correct. Pip module is installed in site-packages but the executable is installed in bin.

Sending a JSON HTTP POST request from Android

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

Should I initialize variable within constructor or outside constructor

I find the second style (declaration + initialization in one go) superior. Reasons:

  • It makes it clear at a glance how the variable is initialized. Typically, when reading a program and coming across a variable, you'll first go to its declaration (often automatic in IDEs). With style 2, you see the default value right away. With style 1, you need to look at the constructor as well.
  • If you have more than one constructor, you don't have to repeat the initializations (and you cannot forget them).

Of course, if the initialization value is different in different constructors (or even calculated in the constructor), you must do it in the constructor.

Loop timer in JavaScript

Here the Automatic loop function with html code. I hope this may be useful for someone.

<!DOCTYPE html>
<html>
<head>
<style>
div {
position: relative;
background-color: #abc;
width: 40px;
height: 40px;
float: left;
margin: 5px;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p><button id="go">Run »</button></p>
<div class="block"></div>
<script>

function test() {
$(".block").animate({left: "+=50", opacity: 1}, 500 );
   setTimeout(mycode, 2000);
};
$( "#go" ).click(function(){
test();
});
</script>
</body>
</html>

Fiddle: DEMO

jQuery - Create hidden form element on the fly

$('#myformelement').append('<input type="hidden" name="myfieldname" value="myvalue" />');

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

You can replace

document.getElementById(this.state.baction).addPrecent(10);

with

this.refs[this.state.baction].addPrecent(10);


  <Progressbar completed={25} ref="Progress1" id="Progress1"/>

Delete from two tables in one query

You can also use like this, to delete particular value when both the columns having 2 or many of same column name.

DELETE project , create_test  FROM project INNER JOIN create_test
WHERE project.project_name='Trail' and  create_test.project_name ='Trail' and project.uid= create_test.uid = '1';

Failed to serialize the response in Web API with Json

Just put following lines in global.asax:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;  
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

Import

using System.Data.Entity;

How to call javascript function from asp.net button click event

You're already prepending the hash sign in your showDialog() function, and you're missing single quotes in your second code snippet. You should also return false from the handler to prevent a postback from occurring. Try:

<asp:Button ID="ButtonAdd" runat="server" Text="Add"
    OnClientClick="showDialog('<%=addPerson.ClientID %>'); return false;" />

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

Why not negate the padding added by container-fluid by marking left and right padding as 0?

<div class="container-fluid pl-0 pr-0">

even better way? no padding at all at the container level (cleaner)

<div class="container-fluid pl-0 pr-0">

How can I change the default width of a Twitter Bootstrap modal box?

Less-based solution (no js) for Bootstrap 2:

.modal-width(@modalWidth) {
    width: @modalWidth;
    margin-left: -@modalWidth/2;

    @media (max-width: @modalWidth) {
        position: fixed;
        top:   20px;
        left:  20px;
        right: 20px;
        width: auto;
        margin: 0;
        &.fade  { top: -100px; }
        &.fade.in { top: 20px; }
    }
}

Then wherever you want to specify a modal width:

#myModal {
    .modal-width(700px);
}

How to insert a line break <br> in markdown

Try adding 2 spaces (or a backslash \) after the first line:

[Name of link](url)
My line of text\

Visually:

[Name of link](url)<space><space>
My line of text\

Output:

<p><a href="url">Name of link</a><br>
My line of text<br></p>

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

The NSDictionary and NSMutableDictionary docs are probably your best bet. They even have some great examples on how to do various things, like...

...create an NSDictionary

NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects 
                                                       forKeys:keys];

...iterate over it

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

...make it mutable

NSMutableDictionary *mutableDict = [dictionary mutableCopy];

Note: historic version before 2010: [[dictionary mutableCopy] autorelease]

...and alter it

[mutableDict setObject:@"value3" forKey:@"key3"];

...then store it to a file

[mutableDict writeToFile:@"path/to/file" atomically:YES];

...and read it back again

NSMutableDictionary *anotherDict = [NSMutableDictionary dictionaryWithContentsOfFile:@"path/to/file"];

...read a value

NSString *x = [anotherDict objectForKey:@"key1"];

...check if a key exists

if ( [anotherDict objectForKey:@"key999"] == nil ) NSLog(@"that key is not there");

...use scary futuristic syntax

From 2014 you can actually just type dict[@"key"] rather than [dict objectForKey:@"key"]

Cannot open include file 'afxres.h' in VC2010 Express

a similar issue is for Visual studio 2015 RC. Sometimes it loses the ability to open RC: you double click but editor do not one menus and dialogs.

Right click on the file *.rc, it will open:

enter image description here

And change as following:

enter image description here

How do I remove blank elements from an array?

Plain Ruby:

values = [1,2,3, " ", "", "", nil] - ["", " ", nil]
puts values # [1,2,3]

Understanding Bootstrap's clearfix class

.clearfix is defined in less/mixins.less. Right above its definition is a comment with a link to this article:

A new micro clearfix hack

The article explains how it all works.

UPDATE: Yes, link-only answers are bad. I knew this even at the time that I posted this answer, but I didn't feel like copying and pasting was OK due to copyright, plagiarism, and what have you. However, I now feel like it's OK since I have linked to the original article. I should also mention the author's name, though, for credit: Nicolas Gallagher. Here is the meat of the article (note that "Thierry’s method" is referring to Thierry Koblentz’s “clearfix reloaded”):

This “micro clearfix” generates pseudo-elements and sets their display to table. This creates an anonymous table-cell and a new block formatting context that means the :before pseudo-element prevents top-margin collapse. The :after pseudo-element is used to clear the floats. As a result, there is no need to hide any generated content and the total amount of code needed is reduced.

Including the :before selector is not necessary to clear the floats, but it prevents top-margins from collapsing in modern browsers. This has two benefits:

  • It ensures visual consistency with other float containment techniques that create a new block formatting context, e.g., overflow:hidden

  • It ensures visual consistency with IE 6/7 when zoom:1 is applied.

N.B.: There are circumstances in which IE 6/7 will not contain the bottom margins of floats within a new block formatting context. Further details can be found here: Better float containment in IE using CSS expressions.

The use of content:" " (note the space in the content string) avoids an Opera bug that creates space around clearfixed elements if the contenteditable attribute is also present somewhere in the HTML. Thanks to Sergio Cerrutti for spotting this fix. An alternative fix is to use font:0/0 a.

Legacy Firefox

Firefox < 3.5 will benefit from using Thierry’s method with the addition of visibility:hidden to hide the inserted character. This is because legacy versions of Firefox need content:"." to avoid extra space appearing between the body and its first child element, in certain circumstances (e.g., jsfiddle.net/necolas/K538S/.)

Alternative float-containment methods that create a new block formatting context, such as applying overflow:hidden or display:inline-block to the container element, will also avoid this behaviour in legacy versions of Firefox.

Strip out HTML and Special Characters

to allow periods and any other character just add them like so:

change: '#[^a-zA-Z ]#' to:'#[^a-zA-Z .()!]#'

Calling class staticmethod within the class body?

staticmethod objects apparently have a __func__ attribute storing the original raw function (makes sense that they had to). So this will work:

class Klass(object):

    @staticmethod  # use as decorator
    def stat_func():
        return 42

    _ANS = stat_func.__func__()  # call the staticmethod

    def method(self):
        ret = Klass.stat_func()
        return ret

As an aside, though I suspected that a staticmethod object had some sort of attribute storing the original function, I had no idea of the specifics. In the spirit of teaching someone to fish rather than giving them a fish, this is what I did to investigate and find that out (a C&P from my Python session):

>>> class Foo(object):
...     @staticmethod
...     def foo():
...         return 3
...     global z
...     z = foo

>>> z
<staticmethod object at 0x0000000002E40558>
>>> Foo.foo
<function foo at 0x0000000002E3CBA8>
>>> dir(z)
['__class__', '__delattr__', '__doc__', '__format__', '__func__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> z.__func__
<function foo at 0x0000000002E3CBA8>

Similar sorts of digging in an interactive session (dir is very helpful) can often solve these sorts of question very quickly.

How To Convert A Number To an ASCII Character?

C# represents a character in UTF-16 coding rather than ASCII. Therefore converting a integer to character do not make any difference for A-Z and a-z. But I was working with ASCII Codes besides alphabets and number which did not work for me as system uses UTF-16 code. Therefore I browsed UTF-16 code for all UTF-16 character. Here is the module :

void utfchars()
{
 int i, a, b, x;
 ConsoleKeyInfo z;
  do
  {
   a = 0; b = 0; Console.Clear();
    for (i = 1; i <= 10000; i++)
    {
     if (b == 20)
     {
      b = 0;
      a = a + 1;
     }
    Console.SetCursorPosition((a * 15) + 1, b + 1);
    Console.Write("{0} == {1}", i, (char)i);
   b = b+1;
   if (i % 100 == 0)
  {
 Console.Write("\n\t\t\tPress any key to continue {0}", b);
 a = 0; b = 0;
 Console.ReadKey(true); Console.Clear();
 }
}
Console.Write("\n\n\n\n\n\n\n\t\t\tPress any key to Repeat and E to exit");
z = Console.ReadKey();
if (z.KeyChar == 'e' || z.KeyChar == 'E') Environment.Exit(0);
} while (1 == 1);
}

How to split a string, but also keep the delimiters?

Tweaked Pattern.split() to include matched pattern to the list

Added

// add match to the list
        matchList.add(input.subSequence(start, end).toString());

Full source

public static String[] inclusiveSplit(String input, String re, int limit) {
    int index = 0;
    boolean matchLimited = limit > 0;
    ArrayList<String> matchList = new ArrayList<String>();

    Pattern pattern = Pattern.compile(re);
    Matcher m = pattern.matcher(input);

    // Add segments before each match found
    while (m.find()) {
        int end = m.end();
        if (!matchLimited || matchList.size() < limit - 1) {
            int start = m.start();
            String match = input.subSequence(index, start).toString();
            matchList.add(match);
            // add match to the list
            matchList.add(input.subSequence(start, end).toString());
            index = end;
        } else if (matchList.size() == limit - 1) { // last one
            String match = input.subSequence(index, input.length())
                    .toString();
            matchList.add(match);
            index = end;
        }
    }

    // If no match was found, return this
    if (index == 0)
        return new String[] { input.toString() };

    // Add remaining segment
    if (!matchLimited || matchList.size() < limit)
        matchList.add(input.subSequence(index, input.length()).toString());

    // Construct result
    int resultSize = matchList.size();
    if (limit == 0)
        while (resultSize > 0 && matchList.get(resultSize - 1).equals(""))
            resultSize--;
    String[] result = new String[resultSize];
    return matchList.subList(0, resultSize).toArray(result);
}

Current Subversion revision command

svn info, I believe, is what you want.

If you just wanted the revision, maybe you could do something like:

svn info | grep "Revision:"

Android Studio : How to uninstall APK (or execute adb command) automatically before Run or Debug?

If you want to uninstall when connected to single device/emulator then use below command

adb uninstall <package name>

else with multiple devices then use below command

adb -s <device ID> uninstall <package name>

How to locate the php.ini file (xampp)

step1 :open xampp control panel

step 2: then click apache module config button.

step 3. after that you able to see some config file list.

step 4: then click the php.ini file.it will be open into default editor.

image was given blow for refernce. enter image description here

foreach with index

This is your collection

var values = new[] {6, 2, 8, 45, 9, 3, 0};

Make a range of indexes for this collection

var indexes = Enumerable.Range(0, values.Length).ToList();

Use the range to iterate with index

indexes.ForEach(i => values[i] += i);
indexes.ForEach(i => Console.Write("[{0}] = {1}", i, values[i]));

Unable to run Java GUI programs with Ubuntu

I stopped getting this exception when I installed default-jdk using apt. I'm running Ubuntu 14.04 (Trusty Tahr), and the problem appears to have been the result of having a "headless" Java installed. All I did was:

sudo apt-get install default-jdk

How can I return the sum and average of an int array?

Though the answers above all are different flavors of correct, I'd like to offer the following solution, which includes a null check:

decimal sum = (customerssalary == null) ? 0 : customerssalary.Sum();
decimal avg = (customerssalary == null) ? 0 : customerssalary.Average();

Importing a GitHub project into Eclipse

I encountered the same problem, and finally found a way:

  1. Add or create git repository in git view.
  2. Click new java project menu, uncheck "use default location", select the git repo location, click finish.

Ecplise Version: Mars.2 Release (4.5.2)

How to convert an ArrayList containing Integers to primitive int array?

using Dollar should be quite simple:

List<Integer> list = $(5).toList(); // the list 0, 1, 2, 3, 4  
int[] array = $($(list).toArray()).toIntArray();

I'm planning to improve the DSL in order to remove the intermediate toArray() call

IsNullOrEmpty with Object

Why would you need any other way? Comparing an Object reference with null is the least-verbose way to check if it's null.

Visualizing decision tree in scikit-learn

Simple way founded here with pydotplus (graphviz must be installed):

from IPython.display import Image  
from sklearn import tree
import pydotplus # installing pyparsing maybe needed

...

dot_data = tree.export_graphviz(best_model, out_file=None, feature_names = X.columns)
graph = pydotplus.graph_from_dot_data(dot_data)
Image(graph.create_png())

Mock MVC - Add Request Parameter to test

@ModelAttribute is a Spring mapping of request parameters to a particular object type. so your parameters might look like userClient.username and userClient.firstName, etc. as MockMvc imitates a request from a browser, you'll need to pass in the parameters that Spring would use from a form to actually build the UserClient object.

(i think of ModelAttribute is kind of helper to construct an object from a bunch of fields that are going to come in from a form, but you may want to do some reading to get a better definition)

rails generate model

You need to create new rails application first. Run

rails new mebay
cd mebay
bundle install
rails generate model ...

And try to find Rails 3 tutorial, there are a lot of changes since 2.1 Guides (http://guides.rubyonrails.org/getting_started.html) are good start point.

Why doesn't C++ have a garbage collector?

If you want automatic garbage collection, there are good commercial and public-domain garbage collectors for C++. For applications where garbage collection is suitable, C++ is an excellent garbage collected language with a performance that compares favorably with other garbage collected languages. See The C++ Programming Language (4rd Edition) for a discussion of automatic garbage collection in C++. See also, Hans-J. Boehm's site for C and C++ garbage collection (archive).

Also, C++ supports programming techniques that allow memory management to be safe and implicit without a garbage collector. I consider garbage collection a last choice and an imperfect way of handling for resource management. That does not mean that it is never useful, just that there are better approaches in many situations.

Source: http://www.stroustrup.com/bs_faq.html#garbage-collection

As for why it doesnt have it built in, If I remember correctly it was invented before GC was the thing, and I don't believe the language could have had GC for several reasons(I.E Backwards compatibilty with C)

Hope this helps.

PHP __get and __set magic methods

__get, __set, __call and __callStatic are invoked when the method or property is inaccessible. Your $bar is public and therefor not inaccessible.

See the section on Property Overloading in the manual:

  • __set() is run when writing data to inaccessible properties.
  • __get() is utilized for reading data from inaccessible properties.

The magic methods are not substitutes for getters and setters. They just allow you to handle method calls or property access that would otherwise result in an error. As such, there are much more related to error handling. Also note that they are considerably slower than using proper getter and setter or direct method calls.

Create a HTML table where each TR is a FORM

I second Harmen's div suggestion. Alternatively, you can wrap the table in a form, and use javascript to capture the row focus and adjust the form action via javascript before submit.

Execute combine multiple Linux commands in one line

To run them all at once, you can use the pipe line key "|" like so:

$ cd /my_folder | rm *.jar | svn co path to repo | mvn compile package install

NoClassDefFoundError in Java: com/google/common/base/Function

I had the same problem, and finally I found that I forgot to add the selenium-server-standalone-version.jar. I had only added the client jar, selenium-java-version.jar.

Hope this helps.

Copy multiple files from one directory to another from Linux shell

Use wildcards:

cp /home/ankur/folder/* /home/ankur/dest

If you don't want to copy all the files, you can use braces to select files:

cp /home/ankur/folder/{file{1,2},xyz,abc} /home/ankur/dest

This will copy file1, file2, xyz, and abc.

You should read the sections of the bash man page on Brace Expansion and Pathname Expansion for all the ways you can simplify this.

Another thing you can do is cd /home/ankur/folder. Then you can type just the filenames rather than the full pathnames, and you can use filename completion by typing Tab.

Why is __dirname not defined in node REPL?

I was running a script from batch file as SYSTEM user and all variables like process.cwd() , path.resolve() and all other methods would give me path to C:\Windows\System32 folder instead of actual path. During experiments I noticed that when an error is thrown the stack contains a true path to the node file.

Here's a very hacky way to get true path by triggering an error and extracting path from e.stack. Do not use.

// this should be the name of currently executed file
const currentFilename = 'index.js';

function veryHackyGetFolder() {
  try {
    throw new Error();
  } catch(e) {
    const fullMsg = e.stack.toString();
    const beginning = fullMsg.indexOf('file:///') + 8;
    const end = fullMsg.indexOf('\/' + currentFilename);
    const dir = fullMsg.substr(beginning, end - beginning).replace(/\//g, '\\');
    return dir;
  }
}

Usage

const dir = veryHackyGetFolder();

Python subprocess/Popen with a modified environment

I know this has been answered for some time, but there are some points that some may want to know about using PYTHONPATH instead of PATH in their environment variable. I have outlined an explanation of running python scripts with cronjobs that deals with the modified environment in a different way (found here). Thought it would be of some good for those who, like me, needed just a bit more than this answer provided.

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

Using global variables in a function

If I'm understanding your situation correctly, what you're seeing is the result of how Python handles local (function) and global (module) namespaces.

Say you've got a module like this:

# sample.py
myGlobal = 5

def func1():
    myGlobal = 42

def func2():
    print myGlobal

func1()
func2()

You might expecting this to print 42, but instead it prints 5. As has already been mentioned, if you add a 'global' declaration to func1(), then func2() will print 42.

def func1():
    global myGlobal
    myGlobal = 42

What's going on here is that Python assumes that any name that is assigned to, anywhere within a function, is local to that function unless explicitly told otherwise. If it is only reading from a name, and the name doesn't exist locally, it will try to look up the name in any containing scopes (e.g. the module's global scope).

When you assign 42 to the name myGlobal, therefore, Python creates a local variable that shadows the global variable of the same name. That local goes out of scope and is garbage-collected when func1() returns; meanwhile, func2() can never see anything other than the (unmodified) global name. Note that this namespace decision happens at compile time, not at runtime -- if you were to read the value of myGlobal inside func1() before you assign to it, you'd get an UnboundLocalError, because Python has already decided that it must be a local variable but it has not had any value associated with it yet. But by using the 'global' statement, you tell Python that it should look elsewhere for the name instead of assigning to it locally.

(I believe that this behavior originated largely through an optimization of local namespaces -- without this behavior, Python's VM would need to perform at least three name lookups each time a new name is assigned to inside a function (to ensure that the name didn't already exist at module/builtin level), which would significantly slow down a very common operation.)

Better naming in Tuple classes than "Item1", "Item2"

Just to add to @MichaelMocko answer. Tuples have couple of gotchas at the moment:

You can't use them in EF expression trees

Example:

public static (string name, string surname) GetPersonName(this PersonContext ctx, int id)
{
    return ctx.Persons
        .Where(person => person.Id == id)
        // Selecting as Tuple
        .Select(person => (person.Name, person.Surname))
        .First();
}

This will fail to compile with "An expression tree may not contain a tuple literal" error. Unfortunately, the expression trees API wasn't expanded with support for tuples when these were added to the language.

Track (and upvote) this issue for the updates: https://github.com/dotnet/roslyn/issues/12897

To get around the problem, you can cast it to anonymous type first and then convert the value to tuple:

// Will work
public static (string name, string surname) GetPersonName(this PersonContext ctx, int id)
{
    return ctx.Persons
        .Where(person => person.Id == id)
        .Select(person => new { person.Name, person.Surname })
        .ToList()
        .Select(person => (person.Name, person.Surname))
        .First();
}

Another option is to use ValueTuple.Create:

// Will work
public static (string name, string surname) GetPersonName(this PersonContext ctx, int id)
{
    return ctx.Persons
        .Where(person => person.Id == id)
        .Select(person => ValueTuple.Create(person.Name, person.Surname))
        .First();
}

References:

You can't deconstruct them in lambdas

There's a proposal to add the support: https://github.com/dotnet/csharplang/issues/258

Example:

public static IQueryable<(string name, string surname)> GetPersonName(this PersonContext ctx, int id)
{
    return ctx.Persons
        .Where(person => person.Id == id)
        .Select(person => ValueTuple.Create(person.Name, person.Surname));
}

// This won't work
ctx.GetPersonName(id).Select((name, surname) => { return name + surname; })

// But this will
ctx.GetPersonName(id).Select(t => { return t.name + t.surname; })

References:

They won't serialize nicely

using System;
using Newtonsoft.Json;

public class Program
{
    public static void Main() {
        var me = (age: 21, favoriteFood: "Custard");
        string json = JsonConvert.SerializeObject(me);

        // Will output {"Item1":21,"Item2":"Custard"}
        Console.WriteLine(json); 
    }
}

Tuple field names are only available at compile time and are completely wiped out at runtime.

References:

How can I run a html file from terminal?

we could open html file from linux/unix by using firefox .html

GCC fatal error: stdio.h: No such file or directory

I know my case is rare, but I'll still add it here for someone who troubleshoots it later. I had a Linux Kernel module target in my Makefile and I tried to compile my user space program together with the kernel module that doesn't have stdio. Making it a separate target solved the problem.

Php multiple delimiters in explode

How about using strtr() to substitute all of your other delimiters with the first one?

private function multiExplode($delimiters,$string) {
    return explode(
        $delimiters[0],
        strtr(
            $string,
            array_combine(
                array_slice(    $delimiters, 1  ),
                array_fill(
                    0,
                    count($delimiters)-1,
                    array_shift($delimiters)
                )
            )
        )
    );
}

It's sort of unreadable, I guess, but I tested it as working over here.

One-liners ftw!

Can I apply multiple background colors with CSS3?

In case someone needs a CSS background with different color repeating horizontal stripes, here is how I managed to achieve this:

_x000D_
_x000D_
body {_x000D_
  font-family: 'Lucida Grande', 'Helvetica Neue', Helvetica, Arial, sans-serif;_x000D_
  font-size: 13px;_x000D_
}_x000D_
_x000D_
.css-stripes {_x000D_
  margin: 0 auto;_x000D_
  width: 200px;_x000D_
  padding: 100px;_x000D_
  text-align: center;_x000D_
  /* For browsers that do not support gradients */_x000D_
  background-color: #F691FF;_x000D_
  /* Safari 5.1 to 6.0 */_x000D_
  background: -webkit-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
  /* Opera 11.1 to 12.0 */_x000D_
  background: -o-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
  /* Firefox 3.6 to 15 */_x000D_
  background: -moz-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
  /* Standard syntax */_x000D_
  background-image: repeating-linear-gradient(to top, #F691FF, #EC72A8);_x000D_
  background-size: 1px 2px;_x000D_
}
_x000D_
<div class="css-stripes">Hello World!</div>
_x000D_
_x000D_
_x000D_

JSfiddle

Calculate age based on date of birth

 $dob = $this->dateOfBirth; //Datetime 
        $currentDate = new \DateTime();
        $dateDiff = $dob->diff($currentDate);
        $years = $dateDiff->y;
        $months = $dateDiff->m;
        $days = $dateDiff->d;
        $age = $years .' Year(s)';

        if($years === 0) {
            $age = $months .' Month(s)';
            if($months === 0) {
                $age = $days .' Day(s)';
            }
        }
        return $age;

php search array key and get value

array_search('20120504', array_keys($your_array));

python - find index position in list based of partial string

indices = [i for i, s in enumerate(mylist) if 'aa' in s]

Save Javascript objects in sessionStorage

This is a dynamic solution which works with all value types including objects :

class Session extends Map {
  set(id, value) {
    if (typeof value === 'object') value = JSON.stringify(value);
    sessionStorage.setItem(id, value);
  }

  get(id) {
    const value = sessionStorage.getItem(id);
    try {
      return JSON.parse(value);
    } catch (e) {
      return value;
    }
  }
}

Then :

const session = new Session();

session.set('name', {first: 'Ahmed', last : 'Toumi'});
session.get('name');

How to make cross domain request

You can make cross domain requests using the XMLHttpRequest object. This is done using something called "Cross Origin Resource Sharing". See: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Very simply put, when the request is made to the server the server can respond with a Access-Control-Allow-Origin header which will either allow or deny the request. The browser needs to check this header and if it is allowed then it will continue with the request process. If not the browser will cancel the request.

You can find some more information and a working example here: http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html

JSONP is an alternative solution, but you could argue it's a bit of a hack.

Blur effect on a div element

I got blur working with SVG blur filter:

CSS

-webkit-filter: url(#svg-blur);
        filter: url(#svg-blur);

SVG

<svg id="svg-filter">
    <filter id="svg-blur">
        <feGaussianBlur in="SourceGraphic" stdDeviation="4"></feGaussianBlur>
    </filter>
</svg>

Working example:

https://jsfiddle.net/1k5x6dgm/

Please note - this will not work in IE versions

Make DateTimePicker work as TimePicker only in WinForms

Add below event to DateTimePicker

Private Sub DateTimePicker1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles DateTimePicker1.KeyPress
    e.Handled = True
End Sub

Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return k1.zip(k2, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];
       }
     }).all();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...

Change the Arrow buttons in Slick slider

<div class="prev">Prev</div>

<div class="next">Next</div>

$('.your_class').slick({
        infinite: true,
        speed: 300,
        slidesToShow: 5,
        slidesToScroll: 5,
        arrows: true,
        prevArrow: $('.prev'),
        nextArrow: $('.next')
});

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

The normal usage of static is to access the function directly with out any object creation. Same as in java main we could not create any object for that class to invoke the main method. It will execute automatically. If we want to execute manually we can call by using main() inside the class and ClassName.main from outside the class.

EF Migrations: Rollback last applied migration?

I'm using EntityFrameworkCore and I use the answer by @MaciejLisCK. If you have multiple DB contexts you will also need to specify the context by adding the context parameter e.g. :

Update-Database 201207211340509_MyMigration -context myDBcontext

(where 201207211340509_MyMigration is the migration you want to roll back to, and myDBcontext is the name of your DB context)

Does WhatsApp offer an open API?

  1. is the correct answer. WhatsApp is intentionally a closed system without an API for external access.

There were several projects available that reverse engineered the WhatsApp webservice interfaces. However, to my knowledge all of them are now discontinued/defunct due to legal action against them from WhatsApp.

For mobile phone applications there is a limited URL-Scheme-API available on IPhone and Android (Android-intent possible as well).

Pandas DataFrame: replace all values in a column, based on condition

for single condition, ie. ( 'employrate'] > 70 )

       country        employrate alcconsumption
0  Afghanistan  55.7000007629394            .03
1      Albania  51.4000015258789           7.29
2      Algeria              50.5            .69
3      Andorra                            10.17
4       Angola  75.6999969482422           5.57

use this:

df.loc[df['employrate'] > 70, 'employrate'] = 7

       country  employrate alcconsumption
0  Afghanistan   55.700001            .03
1      Albania   51.400002           7.29
2      Algeria   50.500000            .69
3      Andorra         nan          10.17
4       Angola    7.000000           5.57

therefore syntax here is:

df.loc[<mask>(here mask is generating the labels to index) , <optional column(s)> ]

For multiple conditions ie. (df['employrate'] <=55) & (df['employrate'] > 50)

use this:

df['employrate'] = np.where(
   (df['employrate'] <=55) & (df['employrate'] > 50) , 11, df['employrate']
   )

out[108]:
       country  employrate alcconsumption
0  Afghanistan   55.700001            .03
1      Albania   11.000000           7.29
2      Algeria   11.000000            .69
3      Andorra         nan          10.17
4       Angola   75.699997           5.57

therefore syntax here is:

 df['<column_name>'] = np.where((<filter 1> ) & (<filter 2>) , <new value>, df['column_name'])

Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window

The problem is that there is an in-browser print dialogue within the popup window. If you call window.close() immediately then the dialogue is not seen by the user. The user needs to click "Print" within the dialogue. This is not the same as on other browsers where the print dialogue is part of the OS, and blocks the window.close() until dismissed - on Chrome, it's part of Chrome, not the OS.

This is the code I used, in a little popup window that is created by the parent window:

var is_chrome = function () { return Boolean(window.chrome); }
window.onload = function() {
    if(is_chrome){
        /*
         * These 2 lines are here because as usual, for other browsers,
         * the window is a tiny 100x100 box that the user will barely see.
         * On Chrome, it needs to be big enough for the dialogue to be read
         * (NB, it also includes a page preview).
        */
        window.moveTo(0,0);
        window.resizeTo(640, 480);

        // This line causes the print dialogue to appear, as usual:
        window.print();

        /*
         * This setTimeout isn't fired until after .print() has finished
         * or the dialogue is closed/cancelled.
         * It doesn't need to be a big pause, 500ms seems OK.
        */
        setTimeout(function(){
            window.close();
        }, 500);
    } else {
        // For other browsers we can do things more briefly:
        window.print();
        window.close();
    }
}

File.Move Does Not Work - File Already Exists

Try Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(Source, Destination, True). The last parameter is Overwrite switch, which System.IO.File.Move doesn't have.

Disable XML validation in Eclipse

You have two options:

  1. Configure Workspace Settings (disable the validation for the current workspace): Go to Window > Preferences > Validation and uncheck the manual and build for: XML Schema Validator, XML Validator

  2. Check enable project specific settings (disable the validation for this project): Right-click on the project, select Properties > Validation and uncheck the manual and build for: XML Schema Validator, XML Validator

Right-click on the project and select Validate to make the errors disappear.

How do I sort a two-dimensional (rectangular) array in C#?

I like the DataTable approach proposed by MusiGenesis above. The nice thing about it is that you can sort by any valid SQL 'order by' string that uses column names, e.g. "x, y desc, z" for 'order by x, y desc, z'. (FWIW, I could not get it to work using column ordinals, e.g. "3,2,1 " for 'order by 3,2,1') I used only integers, but clearly you could add mixed type data into the DataTable and sort it any which way.

In the example below, I first loaded some unsorted integer data into a tblToBeSorted in Sandbox (not shown). With the table and its data already existing, I load it (unsorted) into a 2D integer array, then to a DataTable. The array of DataRows is the sorted version of DataTable. The example is a little odd in that I load my array from the DB and could have sorted it then, but I just wanted to get an unsorted array into C# to use with the DataTable object.

static void Main(string[] args)
{
    SqlConnection cnnX = new SqlConnection("Data Source=r90jroughgarden\\;Initial Catalog=Sandbox;Integrated Security=True");
    SqlCommand cmdX = new SqlCommand("select * from tblToBeSorted", cnnX);
    cmdX.CommandType = CommandType.Text;
    SqlDataReader rdrX = null;
    if (cnnX.State == ConnectionState.Closed) cnnX.Open();

    int[,] aintSortingArray = new int[100, 4];     //i, elementid, planid, timeid

    try
    {
        //Load unsorted table data from DB to array
        rdrX = cmdX.ExecuteReader();
        if (!rdrX.HasRows) return;

        int i = -1;
        while (rdrX.Read() && i < 100)
        {
            i++;
            aintSortingArray[i, 0] = rdrX.GetInt32(0);
            aintSortingArray[i, 1] = rdrX.GetInt32(1);
            aintSortingArray[i, 2] = rdrX.GetInt32(2);
            aintSortingArray[i, 3] = rdrX.GetInt32(3);
        }
        rdrX.Close();

        DataTable dtblX = new DataTable();
        dtblX.Columns.Add("ChangeID");
        dtblX.Columns.Add("ElementID");
        dtblX.Columns.Add("PlanID");
        dtblX.Columns.Add("TimeID");
        for (int j = 0; j < i; j++)
        {
            DataRow drowX = dtblX.NewRow();
            for (int k = 0; k < 4; k++)
            {
                drowX[k] = aintSortingArray[j, k];
            }
            dtblX.Rows.Add(drowX);
        }

        DataRow[] adrowX = dtblX.Select("", "ElementID, PlanID, TimeID");
        adrowX = dtblX.Select("", "ElementID desc, PlanID asc, TimeID desc");

    }
    catch (Exception ex)
    {
        string strErrMsg = ex.Message;
    }
    finally
    {
        if (cnnX.State == ConnectionState.Open) cnnX.Close();
    }
}

open() in Python does not create a file if it doesn't exist

Use:

import os

f_loc = r"C:\Users\Russell\Desktop\myfile.dat"

# Create the file if it does not exist
if not os.path.exists(f_loc):
    open(f_loc, 'w').close()

# Open the file for appending and reading
with open(f_loc, 'a+') as f:
    #Do stuff

Note: Files have to be closed after you open them, and the with context manager is a nice way of letting Python take care of this for you.

python 2 instead of python 3 as the (temporary) default python?

You can use virtualenv

# Use this to create your temporary python "install"
# (Assuming that is the correct path to the python interpreter you want to use.)
virtualenv -p /usr/bin/python2.7 --distribute temp-python

# Type this command when you want to use your temporary python.
# While you are using your temporary python you will also have access to a temporary pip,
# which will keep all packages installed with it separate from your main python install.
# A shorter version of this command would be ". temp-python/bin/activate"
source temp-python/bin/activate

# When you no longer wish to use you temporary python type
deactivate

Enjoy!

Right way to write JSON deserializer in Spring or extend it

I was trying to @Autowire a Spring-managed service into my Deserializer. Somebody tipped me off to Jackson using the new operator when invoking the serializers/deserializers. This meant no auto-wiring of Jackson's instance of my Deserializer. Here's how I was able to @Autowire my service class into my Deserializer:

context.xml

<mvc:annotation-driven>
  <mvc:message-converters>
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
      <property name="objectMapper" ref="objectMapper" />
    </bean>
  </mvc:message-converters>
</mvc>
<bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
    <!-- Add deserializers that require autowiring -->
    <property name="deserializersByType">
        <map key-type="java.lang.Class">
            <entry key="com.acme.Anchor">
                <bean class="com.acme.AnchorDeserializer" />
            </entry>
        </map>
    </property>
</bean>

Now that my Deserializer is a Spring-managed bean, auto-wiring works!

AnchorDeserializer.java

public class AnchorDeserializer extends JsonDeserializer<Anchor> {
    @Autowired
    private AnchorService anchorService;
    public Anchor deserialize(JsonParser parser, DeserializationContext context)
             throws IOException, JsonProcessingException {
        // Do stuff
    }
}

AnchorService.java

@Service
public class AnchorService {}

Update: While my original answer worked for me back when I wrote this, @xi.lin's response is exactly what is needed. Nice find!

Double precision floating values in Python?

Here is my solution. I first create random numbers with random.uniform, format them in to string with double precision and then convert them back to float. You can adjust the precision by changing '.2f' to '.3f' etc..

import random
from decimal import Decimal

GndSpeedHigh = float(format(Decimal(random.uniform(5, 25)), '.2f'))
GndSpeedLow = float(format(Decimal(random.uniform(2, GndSpeedHigh)), '.2f'))
GndSpeedMean = float(Decimal(format(GndSpeedHigh + GndSpeedLow) / 2, '.2f')))
print(GndSpeedMean)

remove all variables except functions

Here's a pretty convenient function I picked up somewhere and adjusted a little. Might be nice to keep in the directory.

list.objects <- function(env = .GlobalEnv) 
{
    if(!is.environment(env)){
        env <- deparse(substitute(env))
        stop(sprintf('"%s" must be an environment', env))
    }
    obj.type <- function(x) class(get(x, envir = env))
    foo <- sapply(ls(envir = env), obj.type)
    object.name <- names(foo)
    names(foo) <- seq(length(foo))
    dd <- data.frame(CLASS = foo, OBJECT = object.name, 
                     stringsAsFactors = FALSE)
    dd[order(dd$CLASS),]
}

> x <- 1:5
> d <- data.frame(x)
> list.objects()
#        CLASS       OBJECT
# 1 data.frame            d
# 2   function list.objects
# 3    integer            x 
> list.objects(env = x)
# Error in list.objects(env = x) : "x" must be an environment

How to get a complete list of ticker symbols from Yahoo Finance?

I managed to do something similar by using this URL:

http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.industry%20where%20id%20in%20(select%20industry.id%20from%20yahoo.finance.sectors)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys

It downloads a complete list of stock symbols using the Yahoo YQL API, including the stock name, stock symbol, and industry ID. What it doesn't seem to have is any sort of stock symbol modifiers. E.g. for Rogers Communications Inc, it only downloads RCI, not RCI-A.TO, RCI-B.TO, etc. I haven't found a source for that information yet - if anyone knows of a way to automate downloading that, I'd like to hear it. Also, it'd be nice to find a way to download some sort of relation between the stock symbol and the exchange it's traded on, since some are traded on multiple exchanges, or maybe I only want to look at stuff on the TSX or something.

Cannot open output file, permission denied

I just had the same issue. And i experienced that it always happens when i run the programm and change some code without finishing the programm still running. After that the "cannot open ..." message appears.

However i got rid of it by clicking the "Terminate" button at the very top-right side of the console window (red button) and after that "remove all terminated launches" (two x'es right next to the terminate button). This seems to close the running programm and everything works fine after :) hope this may help anyone

What is makeinfo, and how do I get it?

In (at least) Ubuntu when using bash, it tells you what package you need to install if you type in a command and its not found in your path. My terminal says you need to install 'texinfo' package.

sudo apt-get install texinfo

scroll image with continuous scrolling using marquee tag

Marquee (<marquee>) is a deprecated and not a valid HTML tag. You can use many jQuery plugins to do. One of it, is jQuery News Ticker. There are many more!

Getting full JS autocompletion under Sublime Text

I developed a new plugin called JavaScript Enhancements, that you can find on Package Control. It uses Flow (javascript static type checker from Facebook) under the hood.

Furthermore, it offers smart javascript autocomplete (compared to my other plugin JavaScript Completions), real-time errors, code refactoring and also a lot of features about creating, developing and managing javascript projects.

See the Wiki to know all the features that it offers!

An introduction to this plugin could be found in this css-tricks.com article: Turn Sublime Text 3 into a JavaScript IDE

Just some quick screenshots:

Splitting a string into chunks of a certain size

Using regular expressions and Linq:

List<string> groups = (from Match m in Regex.Matches(str, @"\d{4}")
                       select m.Value).ToList();

I find this to be more readable, but it's just a personal opinion. It can also be a one-liner : ).

Why does Eclipse automatically add appcompat v7 library support whenever I create a new project?

Why my eclipse automatically adds appcompat v7 library support whenever i create a new project

Because your target SDK is set to 15, in which the Action Bar is on by default and your minimum supported SDK is set to 10. Action Bar come out in 11, so you need a support library, Eclipse adds it for you. Reference.

You can configure project libraries in the build path of project properties.

XSS filtering function in PHP

I'm was collect most of issues by the web and combine stepping filter for all of them.

After some testing seems it works perfect:


/*
* Total XSS preventer class by Full-R
*
*/

final class xCleaner {

    public static function clean( string $html ): string {

        return self::cleanXSS(

            preg_replace(

                [

                    '/\s?<iframe[^>]*?>.*?<\/iframe>\s?/si',
                    '/\s?<style[^>]*?>.*?<\/style>\s?/si',
                    '/\s?<script[^>]*?>.*?<\/script>\s?/si',
                    '#\son\w*="[^"]+"#',

                ],

                [
                    '',
                    '',
                    ''
                ],

                $html

            )

        );

    }

    protected static function hexToSymbols( string $s ): string {

        return html_entity_decode($s, ENT_XML1, 'UTF-8');

    }

    protected static function escape( string $s, string $m = 'attr' ): string {

        preg_match_all('/data:\w+\/([a-zA-Z]*);base64,(?!_#_#_)([^)\'"]*)/mi', $s, $b64, PREG_OFFSET_CAPTURE);

        if( count( array_filter( $b64 ) ) > 0 ) {

            switch( $m ) {

                case 'attr':

                    $xclean = self::cleanXSS(

                                        urldecode(

                                            base64_decode(

                                                $b64[ 2 ][ 0 ][ 0 ]

                                            )

                                        )

                                );

                    break;

                case 'tag':

                    $xclean = self::cleanTagInnerXSS(

                                        urldecode(

                                            base64_decode(

                                                $b64[ 2 ][ 0 ][ 0 ]

                                            )

                                        )

                                );

                    break;

            }

            return substr_replace(

                $s,

                '_#_#_'. base64_encode( $xclean ),

                $b64[ 2 ][ 0 ][ 1 ],

                strlen( $b64[ 2 ][ 0 ][ 0 ] )

            );

        }
        else {

            return $s;

        }

    }

    protected static function cleanXSS( string $s ): string {

        // base64 injection prevention
        $st = self::escape( $s, 'attr' );

        return preg_replace([

                // JSON unicode
                '/\\\\u?{?([a-f0-9]{4,}?)}?/mi',                                                                    // [1] unicode JSON clean

                // Data b64 safe
                '/\*\w*\*/mi',                                                                                            // [2] unicode simple clean

                // Malware payloads
                '/:?e[\s]*x[\s]*p[\s]*r[\s]*e[\s]*s[\s]*s[\s]*i[\s]*o[\s]*n[\s]*(:|;|,)?\w*/mi',    // [3]  (:expression) evalution
                '/l[\s]*i[\s]*v[\s]*e[\s]*s[\s]*c[\s]*r[\s]*i[\s]*p[\s]*t[\s]*(:|;|,)?\w*/mi',         // [4]  (livescript:) evalution
                '/j[\s]*s[\s]*c[\s]*r[\s]*i[\s]*p[\s]*t[\s]*(:|;|,)?\w*/mi',                                 // [5]  (jscript:) evalution
                '/j[\s]*a[\s]*v[\s]*a[\s]*s[\s]*c[\s]*r[\s]*i[\s]*p[\s]*t[\s]*(:|;|,)?\w*/mi',       // [6]  (javascript:) evalution
                '/b[\s]*e[\s]*h[\s]*a[\s]*v[\s]*i[\s]*o[\s]*r[\s]*(:|;|,)?\w*/mi',                     // [7]  (behavior:) evalution
                '/v[\s]*b[\s]*s[\s]*c[\s]*r[\s]*i[\s]*p[\s]*t[\s]*(:|;|,)?\w*/mi',                      // [8]  (vsbscript:) evalution
                '/v[\s]*b[\s]*s[\s]*(:|;|,)?\w*/mi',                                                              // [9]  (vbs:) evalution
                '/e[\s]*c[\s]*m[\s]*a[\s]*s[\s]*c[\s]*r[\s]*i[\s]*p[\s]*t*(:|;|,)?\w*/mi',        // [10] (ecmascript:) possible ES evalution
                '/b[\s]*i[\s]*n[\s]*d[\s]*i[\s]*n[\s]*g*(:|;|,)?\w*/mi',                                 // [11] (-binding) payload
                '/\+\/v(8|9|\+|\/)?/mi',                                                                          // [12] (UTF-7 mutation)

                // Some entities
                '/&{\w*}\w*/mi',                                                                                   // [13] html entites clenup
                '/&#\d+;?/m',                                                                                      // [14] html entites clenup

                // Script tag encoding mutation issue
                '/\¼\/?\w*\¾\w*/mi',                                                                         // [21] mutation KOI-8
                '/\+ADw-\/?\w*\+AD4-\w*/mi',                                                         // [22] mutation old encodings

                '/\/*?%00*?\//m',

                // base64 escaped
                '/_#_#_/mi',                                                                                       // [23] base64 escaped marker cleanup
             
            ],

            // Replacements steps :: 23
            ['&#x$1;', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],

            str_ireplace(

                ['\u0', '&colon;', '&tab;', '&newline;'],
                ['\0', ':', '', ''],

            // U-HEX prepare step
            self::hexToSymbols( $st ))

        );

    }

}

Also you can add Tidy markup correction to make HTML valid.

Create list of single item repeated N times

As others have pointed out, using the * operator for a mutable object duplicates references, so if you change one you change them all. If you want to create independent instances of a mutable object, your xrange syntax is the most Pythonic way to do this. If you are bothered by having a named variable that is never used, you can use the anonymous underscore variable.

[e for _ in xrange(n)]

Bash mkdir and subfolders

To create multiple sub-folders

mkdir -p parentfolder/{subfolder1,subfolder2,subfolder3}

List append() in for loop

No need to re-assign.

a=[]
for i in range(5):    
    a.append(i)
a

Ruby 2.0.0p0 IRB warning: "DL is deprecated, please use Fiddle"

The message "DL is deprecated, please use Fiddle" is not an error; it's only a warning.
Solution:
You can ignore this in 3 simple steps.
Step 1. Goto C:\RailsInstaller\Ruby2.1.0\lib\ruby\2.1.0
Step 2. Then find dl.rb and open the file with any online editors like Aptana,sublime text etc
Step 3. Comment the line 8 with '#' ie # warn "DL is deprecated, please use Fiddle" .
That's it, Thank you.

File path for project files?

I was facing a similar issue, I had a file on my project, and wanted to test a class which had to deal with loading files from the FS and process them some way. What I did was:

  • added the file test.txt to my test project
  • on the solution explorer hit alt-enter (file properties)
  • there I set BuildAction to Content and Copy to Output Directory to Copy if newer, I guess Copy always would have done it as well

then on my tests I just had to Path.Combine(Environment.CurrentDirectory, "test.txt") and that's it. Whenever the project is compiled it will copy the file (and all it's parent path, in case it was in, say, a folder) to the bin\Debug (or whatever configuration you are using) folder.

Hopes this helps someone

ImportError: No module named 'Queue'

You need install Queuelib either via the Python Package Index (PyPI) or from source.

To install using pip:-

$ pip install queuelib

To install using easy_install:-

$ easy_install queuelib

If you have downloaded a source tarball you can install it by running the following (as root):-

python setup.py install

What are the differences between Mustache.js and Handlebars.js?

—In addition to using "this" for handlebars, and the nested variable within variable block for mustache, you can also use the nested dot in a block for mustache:

    {{#variable}}<span class="text">{{.}}</span>{{/variable}}

How to convert Double to int directly?

try casting the value

double d = 1.2345;
long l = (long) d;

Linux find and grep command together

Now that the question is clearer, you can just do this in one

grep -R --include "*bills*" "put" .

With relevant flags

   -R, -r, --recursive
          Read  all  files  under  each  directory,  recursively;  this is
          equivalent to the -d recurse option.
   --include=GLOB
          Search only files whose base name matches GLOB  (using  wildcard
          matching as described under --exclude).

Cannot find module '@angular/compiler'

Try to delete that "angular/cli": "1.0.0-beta.28.3", in the devDependencies it is useless , and add instead of it "@angular/compiler-cli": "^2.3.1", (since it is the current version, else add it by npm i --save-dev @angular/compiler-cli ), then in your root app folder run those commands:

  1. rm -r node_modules (or delete your node_modules folder manually)
  2. npm cache clean (npm > v5 add --force so: npm cache clean --force)
  3. npm install

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

Variables have a type and a value.

  • $var = "test" is a string that contain "test"
  • $var2 = 24 is an integer vhose value is 24.

When you use these variables (in PHP), sometimes you don't have the good type. For example, if you do

if ($var == 1) {... do something ...}

PHP have to convert ("to cast") $var to integer. In this case, "$var == 1" is true because any non-empty string is casted to 1.

When using ===, you check that the value AND THE TYPE are equal, so "$var === 1" is false.

This is useful, for example, when you have a function that can return false (on error) and 0 (result) :

if(myFunction() == false) { ... error on myFunction ... }

This code is wrong as if myFunction() returns 0, it is casted to false and you seem to have an error. The correct code is :

if(myFunction() === false) { ... error on myFunction ... }

because the test is that the return value "is a boolean and is false" and not "can be casted to false".

What primitive data type is time_t?

You can use the function difftime. It returns the difference between two given time_t values, the output value is double (see difftime documentation).

time_t actual_time;
double actual_time_sec;
actual_time = time(0);
actual_time_sec = difftime(actual_time,0); 
printf("%g",actual_time_sec);

CentOS 7 and Puppet unable to install nc

yum install nmap-ncat.x86_64

resolved my problem

How to see indexes for a database or table in MySQL?

If you want to see all indexes across all databases all at once:

use information_schema;
SELECT * FROM statistics;

How to run a command as a specific user in an init script?

For systemd style init scripts it's really easy. You just add a User= in the [Service] section.

Here is an init script I use for qbittorrent-nox on CentOS 7:

[Unit]
Description=qbittorrent torrent server

[Service]
User=<username>
ExecStart=/usr/bin/qbittorrent-nox
Restart=on-abort

[Install]
WantedBy=multi-user.target

Send HTTP POST message in ASP.NET Core using HttpClient PostAsJsonAsync

You should add reference to "Microsoft.AspNet.WebApi.Client" package (read this article for samples).

Without any additional extension, you may use standard PostAsync method:

client.PostAsync(uri, new StringContent(jsonInString, Encoding.UTF8, "application/json"));

where jsonInString value you can get by calling JsonConvert.SerializeObject(<your object>);

How to solve Notice: Undefined index: id in C:\xampp\htdocs\invmgt\manufactured_goods\change.php on line 21

if you are getting id from url try

$id = (isset($_GET['id']) ? $_GET['id'] : '');

if getting from form you need to use POST method cause your form has method="post"

 $id = (isset($_POST['id']) ? $_POST['id'] : '');

For php notices use isset() or empty() to check values exist or not or initialize variable first with blank or a value

$id= '';

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

changing implementation 'com.android.support:appcompat-v7:27+' to implementation 'com.android.support:appcompat-v7:+' worked for me

I am using Intellij 2019 CE, with Kotlin

How do I find the last column with data?

Here's something which might be useful. Selecting the entire column based on a row containing data, in this case i am using 5th row:

Dim lColumn As Long

lColumn = ActiveSheet.Cells(5, Columns.Count).End(xlToLeft).Column
MsgBox ("The last used column is: " & lColumn)

Making an API call in Python with an API that requires a bearer token

If you are using requests module, an alternative option is to write an auth class, as discussed in "New Forms of Authentication":

import requests

class BearerAuth(requests.auth.AuthBase):
    def __init__(self, token):
        self.token = token
    def __call__(self, r):
        r.headers["authorization"] = "Bearer " + self.token
        return r

and then can you send requests like this

response = requests.get('https://www.example.com/', auth=BearerAuth('3pVzwec1Gs1m'))

which allows you to use the same auth argument just like basic auth, and may help you in certain situations.

SQL Server Configuration Manager not found

This path worked for me. on a 32 bit machine.

C:\Windows\System32\mmc.exe /32 C:\Windows\system32\SQLServerManager10.msc

How to make sure that string is valid JSON using JSON.NET

Just to add something to @Habib's answer, you can also check if given JSON is from a valid type:

public static bool IsValidJson<T>(this string strInput)
{
    if(string.IsNullOrWhiteSpace(strInput)) return false;

    strInput = strInput.Trim();
    if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
        (strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
    {
        try
        {
            var obj = JsonConvert.DeserializeObject<T>(strInput);
            return true;
        }
        catch // not valid
        {             
            return false;
        }
    }
    else
    {
        return false;
    }
}

How to convert a JSON string to a Map<String, String> with Jackson JSON

Using Google's Gson

Why not use Google's Gson as mentioned in here?

Very straight forward and did the job for me:

HashMap<String,String> map = new Gson().fromJson( yourJsonString, new TypeToken<HashMap<String, String>>(){}.getType());

finished with non zero exit value

just solved this issues with moving the project to a shorter path. It can happen if you exceed the Windows max path length

How can I link a photo in a Facebook album to a URL

Unfortunately, no. This feature is not available for facebook albums.

Is there a way to programmatically scroll a scroll view to a specific edit text?

My EditText was nested several layers inside my ScrollView, which itself isn't the layout's root view. Because getTop() and getBottom() were seeming to report the coordinates within it's containing view, I had it compute the distance from the top of the ScrollView to the top of the EditText by iterating through the parents of the EditText.

// Scroll the view so that the touched editText is near the top of the scroll view
new Thread(new Runnable()
{
    @Override
    public
    void run ()
    {
        // Make it feel like a two step process
        Utils.sleep(333);

        // Determine where to set the scroll-to to by measuring the distance from the top of the scroll view
        // to the control to focus on by summing the "top" position of each view in the hierarchy.
        int yDistanceToControlsView = 0;
        View parentView = (View) m_editTextControl.getParent();
        while (true)
        {
            if (parentView.equals(scrollView))
            {
                break;
            }
            yDistanceToControlsView += parentView.getTop();
            parentView = (View) parentView.getParent();
        }

        // Compute the final position value for the top and bottom of the control in the scroll view.
        final int topInScrollView = yDistanceToControlsView + m_editTextControl.getTop();
        final int bottomInScrollView = yDistanceToControlsView + m_editTextControl.getBottom();

        // Post the scroll action to happen on the scrollView with the UI thread.
        scrollView.post(new Runnable()
        {
            @Override
            public void run()
            {
                int height =m_editTextControl.getHeight();
                scrollView.smoothScrollTo(0, ((topInScrollView + bottomInScrollView) / 2) - height);
                m_editTextControl.requestFocus();
            }
        });
    }
}).start();

pip install - locale.Error: unsupported locale setting

I had the same problem, and "export LC_ALL=c" didn't work for me.

Try export LC_ALL="en_US.UTF-8" (it will work).

Add SUM of values of two LISTS into new LIST

one-liner solution

list(map(lambda x,y: x+y, a,b))

Sort an array in Java

You may use Arrays.sort() function.

sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)

Retrieving values from nested JSON Object

JSONArray jsonChildArray = (JSONArray) jsonChildArray.get("LanguageLevels");
    JSONObject secObject = (JSONObject) jsonChildArray.get(1);

I think this should work, but i do not have the possibility to test it at the moment..

Git fast forward VS no fast forward merge

The --no-ff option is useful when you want to have a clear notion of your feature branch. So even if in the meantime no commits were made, FF is possible - you still want sometimes to have each commit in the mainline correspond to one feature. So you treat a feature branch with a bunch of commits as a single unit, and merge them as a single unit. It is clear from your history when you do feature branch merging with --no-ff.

If you do not care about such thing - you could probably get away with FF whenever it is possible. Thus you will have more svn-like feeling of workflow.

For example, the author of this article thinks that --no-ff option should be default and his reasoning is close to that I outlined above:

Consider the situation where a series of minor commits on the "feature" branch collectively make up one new feature: If you just do "git merge feature_branch" without --no-ff, "it is impossible to see from the Git history which of the commit objects together have implemented a feature—you would have to manually read all the log messages. Reverting a whole feature (i.e. a group of commits), is a true headache [if --no-ff is not used], whereas it is easily done if the --no-ff flag was used [because it's just one commit]."

Graphic showing how --no-ff groups together all commits from feature branch into one commit on master branch

How to calculate the median of an array?

Check out the Arrays.sort methods:

http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html

You should also really abstract finding the median into its own method, and just return the value to the calling method. This will make testing your code much easier.

JPA OneToMany not deleting child

You can try this:

@OneToOne(orphanRemoval=true) or @OneToMany(orphanRemoval=true).

awk without printing newline

If Perl is an option, here is a solution using fedorqui's example:

seq 5 | perl -ne 'chomp; print "$_ "; END{print "\n"}'

Explanation:
chomp removes the newline
print "$_ " prints each line, appending a space
the END{} block is used to print a newline

output: 1 2 3 4 5

How to replace a hash key with another key

you can do

hash.inject({}){|option, (k,v) | option["id"] = v if k == "_id"; option}

This should work for your case!

Add button to navigationbar programmatically

To add search button on navigation bar use this code:

 UIBarButtonItem *searchButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(toggleSearch:)];
self.navigationController.navigationBar.topItem.rightBarButtonItem = searchButton;

and implement following method:

- (IBAction)toggleSearch:(id)sender
{
    // do something or handle Search Button Action.
}

How can I compare two lists in python and return matches

another a bit more functional way to check list equality for list 1 (lst1) and list 2 (lst2) where objects have depth one and which keeps the order is:

all(i == j for i, j in zip(lst1, lst2))   

Call child component method from parent class - Angular

I think most easy way is using Subject. In bellow example code the child will be notified each time 'tellChild' is called.

Parent.component.ts

import {Subject} from 'rxjs/Subject';
...
export class ParentComp {
    changingValue: Subject<boolean> = new Subject();
    tellChild(){
    this.changingValue.next(true);
  }
}

Parent.component.html

<my-comp [changing]="changingValue"></my-comp>

Child.component.ts

...
export class ChildComp implements OnInit{
@Input() changing: Subject<boolean>;
ngOnInit(){
  this.changing.subscribe(v => { 
     console.log('value is changing', v);
  });
}

Working sample on Stackblitz

Installing jdk8 on ubuntu- "unable to locate package" update doesn't fix

For those who had trouble with the apt-get, or with the long instruction. I solved it in a relatively painless way.

  1. Download the installer from here, or direct download link
  2. $ sudo dpkg -i oracle-java8-installer_8u51+8u51arm-1-webupd8-0_all.deb

Oracle: How to filter by date and time in a where clause

Try:

To_Date (SESSION_START_DATE_TIME, 'MM/DD/YYYY hh24:mi') > 
To_Date ('12-Jan-2012 16:00', 'DD-MON-YYYY hh24:mi' )

How to get box-shadow on left & right sides only

clip-path is now (2020) the best way I have found to achieve box-shadows on specific sides of elements, especially when the required effect is a "clean cut" shadow at particular edges, like this:

_x000D_
_x000D_
.shadow-element {
    width: 100px;
    height: 100px;
    background-color: #FFC300;
    box-shadow: 0 0 10px 5px rgba(0,0,0,0.75);
    clip-path: inset(0px -15px 0px -15px);

    /* position and left properties required to bring element out from edge of parent
    so that shadow can be seen; margin-left would also achieve the same thing */
    position: relative;
    left: 15px;
}
_x000D_
<div class="shadow-element"></div>
_x000D_
_x000D_
_x000D_

...as opposed to an attenuated/reduced/thinning shadow like this:

_x000D_
_x000D_
.shadow-element {
    width: 100px;
    height: 100px;
    background-color: #FFC300;
    box-shadow: 15px 0 15px -10px rgba(0,0,0,0.75), -15px 0 15px -10px rgba(0,0,0,0.75);

    /* position and left properties required to bring element out from edge of parent
    so that shadow can be seen; margin-left would also achieve the same thing */
    position: relative;
    left: 15px;
}
_x000D_
<div class="shadow-element"></div>
_x000D_
_x000D_
_x000D_


Simply apply the following CSS to the element in question:

box-shadow: 0 0 Xpx Ypx [hex/rgba]; /* note 0 offset values */
clip-path: inset(Apx Bpx Cpx Dpx);

Where:

  • Apx sets the shadow visibility for the top edge
  • Bpx right
  • Cpx bottom
  • Dpx left

Enter a value of 0 for any edges where the shadow should be hidden and a negative value (the same as the combined result of the blur radius + spread values - Xpx + Ypx) to any edges where the shadow should be displayed.

Angular 2 - Redirect to an external URL and open in a new tab

I want to share with you one more solution if you have absolute part in the URL

SharePoint solution with ${_spPageContextInfo.webAbsoluteUrl}

HTML:

<button (click)="onNavigate()">Google</button>

TypeScript:

onNavigate()
{
    let link = `${_spPageContextInfo.webAbsoluteUrl}/SiteAssets/Pages/help.aspx#/help`;
    window.open(link, "_blank");
}

and url will be opened in new tab.

Convert object to JSON in Android

public class Producto {

int idProducto;
String nombre;
Double precio;



public Producto(int idProducto, String nombre, Double precio) {

    this.idProducto = idProducto;
    this.nombre = nombre;
    this.precio = precio;

}
public int getIdProducto() {
    return idProducto;
}
public void setIdProducto(int idProducto) {
    this.idProducto = idProducto;
}
public String getNombre() {
    return nombre;
}
public void setNombre(String nombre) {
    this.nombre = nombre;
}
public Double getPrecio() {
    return precio;
}
public void setPrecio(Double precio) {
    this.precio = precio;
}

public String toJSON(){

    JSONObject jsonObject= new JSONObject();
    try {
        jsonObject.put("id", getIdProducto());
        jsonObject.put("nombre", getNombre());
        jsonObject.put("precio", getPrecio());

        return jsonObject.toString();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "";
    }

}

2 column div layout: right column with fixed width, left fluid

I have simplified it : I have edited jackjoe's answer. The height auto etc not required I think.

CSS:

#container {
position: relative;
margin:0 auto;
width: 1000px;
background: #C63;
padding: 10px;
}

#leftCol {
background: #e8f6fe;
width: auto;
}

#rightCol {
float:right;
width:30%;
background: #aafed6;
}

.box {
position:relative;
clear:both;
background:#F39;
 }
</style>

HTML:

<div id="container">

  <div id="rightCol"> 
   <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>

  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
 </div>

 <div id="leftCol">

   <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>

  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

</div>

</div>

<div class="box">
  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>

  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
</div>

Google Maps V3 - How to calculate the zoom level for a given bounds

Thanks, that helped me a lot in finding the most suitable zoom factor to correctly display a polyline. I find the maximum and minimum coordinates among the points I have to track and, in case the path is very "vertical", I just added few lines of code:

var GLOBE_WIDTH = 256; // a constant in Google's map projection
var west = <?php echo $minLng; ?>;
var east = <?php echo $maxLng; ?>;
*var north = <?php echo $maxLat; ?>;*
*var south = <?php echo $minLat; ?>;*
var angle = east - west;
if (angle < 0) {
    angle += 360;
}
*var angle2 = north - south;*
*if (angle2 > angle) angle = angle2;*
var zoomfactor = Math.round(Math.log(960 * 360 / angle / GLOBE_WIDTH) / Math.LN2);

Actually, the ideal zoom factor is zoomfactor-1.

What does `set -x` do?

set -x enables a mode of the shell where all executed commands are printed to the terminal. In your case it's clearly used for debugging, which is a typical use case for set -x: printing every command as it is executed may help you to visualize the control flow of the script if it is not functioning as expected.

set +x disables it.

Java random numbers using a seed

Problem is that you seed the random generator again. Every time you seed it the initial state of the random number generator gets reset and the first random number you generate will be the first random number after the initial state

Declare global variables in Visual Studio 2010 and VB.NET

Public variables are a code smell - try to redesign your application so these are not needed. Most of the reasoning here and here are as applicable to VB.NET.

The simplest way to have global variables in VB.NET is to create public static variables on a class (declare a variable as Public Shared).

How to change line width in ggplot?

If you want to modify the line width flexibly you can use "scale_size_manual," this is the same procedure for picking the color, fill, alpha, etc.

library(ggplot2)
library(tidyr)

x = seq(0,10,0.05)

df <- data.frame(A = 2 * x + 10,
                 B = x**2 - x*6,
                 C = 30 - x**1.5,
                 X = x)


df = gather(df,A,B,C,key="Model",value="Y")


ggplot( df, aes (x=X, y=Y, size=Model, colour=Model ))+
  geom_line()+
  scale_size_manual( values = c(4,2,1) ) +
  scale_color_manual( values = c("orange","red","navy") ) 

Visual Studio Code open tab in new window

You can also hit Win+Shift+[n]. N being the position the app is in the taskbar. Eg if its pinned as the first app hit WIn+Shift+1 and windows will open a new instance. This works for all applications.

I agree tho all of these workarounds shouldn't be necessary. Pretty much every other app can drag tabs out as a window I can't think of anything I used that doesn't and VSCode should be implementing ubiquitous functions we expect to be there.

Mongoose delete array element in document and save

Answers above are shown how to remove an array and here is how to pull an object from an array.

Reference: https://docs.mongodb.com/manual/reference/operator/update/pull/

db.survey.update( // select your doc in moongo
    { }, // your query, usually match by _id
    { $pull: { results: { $elemMatch: { score: 8 , item: "B" } } } }, // item(s) to match from array you want to pull/remove
    { multi: true } // set this to true if you want to remove multiple elements.
)

How to center an iframe horizontally?

According to http://www.w3schools.com/css/css_align.asp, setting the left and right margins to auto specifies that they should split the available margin equally. The result is a centered element:

margin-left: auto;margin-right: auto;

How to write a confusion matrix in Python?

A Dependency Free Multiclass Confusion Matrix

# A Simple Confusion Matrix Implementation
def confusionmatrix(actual, predicted, normalize = False):
    """
    Generate a confusion matrix for multiple classification
    @params:
        actual      - a list of integers or strings for known classes
        predicted   - a list of integers or strings for predicted classes
        normalize   - optional boolean for matrix normalization
    @return:
        matrix      - a 2-dimensional list of pairwise counts
    """
    unique = sorted(set(actual))
    matrix = [[0 for _ in unique] for _ in unique]
    imap   = {key: i for i, key in enumerate(unique)}
    # Generate Confusion Matrix
    for p, a in zip(predicted, actual):
        matrix[imap[p]][imap[a]] += 1
    # Matrix Normalization
    if normalize:
        sigma = sum([sum(matrix[imap[i]]) for i in unique])
        matrix = [row for row in map(lambda i: list(map(lambda j: j / sigma, i)), matrix)]
    return matrix

The approach here is to pair up the unique classes found in the actual vector into a 2-dimensional list. From there, we simply iterate through the zipped actual and predicted vectors and populate the counts using the indices to access the matrix positions.

Usage

cm = confusionmatrix(
    [1, 1, 2, 0, 1, 1, 2, 0, 0, 1], # actual
    [0, 1, 1, 0, 2, 1, 2, 2, 0, 2]  # predicted
)

# And The Output
print(cm)
[[2, 1, 0], [0, 2, 1], [1, 2, 1]]

Note: the actual classes are along the columns and the predicted classes are along the rows.

# Actual
# 0  1  2
  #  #  #   
[[2, 1, 0], # 0
 [0, 2, 1], # 1  Predicted
 [1, 2, 1]] # 2

Class Names Can be Strings or Integers

cm = confusionmatrix(
    ["B", "B", "C", "A", "B", "B", "C", "A", "A", "B"], # actual
    ["A", "B", "B", "A", "C", "B", "C", "C", "A", "C"]  # predicted
)

# And The Output
print(cm)
[[2, 1, 0], [0, 2, 1], [1, 2, 1]]

You Can Also Return The Matrix With Proportions (Normalization)

cm = confusionmatrix(
    ["B", "B", "C", "A", "B", "B", "C", "A", "A", "B"], # actual
    ["A", "B", "B", "A", "C", "B", "C", "C", "A", "C"], # predicted
    normalize = True
)

# And The Output
print(cm)
[[0.2, 0.1, 0.0], [0.0, 0.2, 0.1], [0.1, 0.2, 0.1]]

A More Robust Solution

Since writing this post, I've updated my library implementation to be a class that uses a confusion matrix representation internally to compute statistics, in addition to pretty printing the confusion matrix itself. See this Gist.

Example Usage

# Actual & Predicted Classes
actual      = ["A", "B", "C", "C", "B", "C", "C", "B", "A", "A", "B", "A", "B", "C", "A", "B", "C"]
predicted   = ["A", "B", "B", "C", "A", "C", "A", "B", "C", "A", "B", "B", "B", "C", "A", "A", "C"]

# Initialize Performance Class
performance = Performance(actual, predicted)

# Print Confusion Matrix
performance.tabulate()

With the output:

===================================
        A?      B?      C?

A?      3       2       1

B?      1       4       1

C?      1       0       4

Note: class? = Predicted, class? = Actual
===================================

And for the normalized matrix:

# Print Normalized Confusion Matrix
performance.tabulate(normalized = True)

With the normalized output:

===================================
        A?      B?      C?

A?      17.65%  11.76%  5.88%

B?      5.88%   23.53%  5.88%

C?      5.88%   0.00%   23.53%

Note: class? = Predicted, class? = Actual
===================================

Read a text file line by line in Qt

Use this code:

QFile inputFile(fileName);
if (inputFile.open(QIODevice::ReadOnly))
{
   QTextStream in(&inputFile);
   while (!in.atEnd())
   {
      QString line = in.readLine();
      ...
   }
   inputFile.close();
}

Node.js version on the command line? (not the REPL)

If you're referring to the shell command line, either of the following will work:

node -v

node --version

Just typing node version will cause node.js to attempt loading a module named version, which doesn't exist unless you like working with confusing module names.

What is the difference between HTTP 1.1 and HTTP 2.0?

HTTP 2.0 is a binary protocol that multiplexes numerous streams going over a single (normally TLS-encrypted) TCP connection.

The contents of each stream are HTTP 1.1 requests and responses, just encoded and packed up differently. HTTP2 adds a number of features to manage the streams, but leaves old semantics untouched.

Passing properties by reference in C#

Another trick not yet mentioned is to have the class which implements a property (e.g. Foo of type Bar) also define a delegate delegate void ActByRef<T1,T2>(ref T1 p1, ref T2 p2); and implement a method ActOnFoo<TX1>(ref Bar it, ActByRef<Bar,TX1> proc, ref TX1 extraParam1) (and possibly versions for two and three "extra parameters" as well) which will pass its internal representation of Foo to the supplied procedure as a ref parameter. This has a couple of big advantages over other methods of working with the property:

  1. The property is updated "in place"; if the property is of a type that's compatible with `Interlocked` methods, or if it is a struct with exposed fields of such types, the `Interlocked` methods may be used to perform atomic updates to the property.
  2. If the property is an exposed-field structure, the fields of the structure may be modified without having to make any redundant copies of it.
  3. If the `ActByRef` method passes one or more `ref` parameters through from its caller to the supplied delegate, it may be possible to use a singleton or static delegate, thus avoiding the need to create closures or delegates at run-time.
  4. The property knows when it is being "worked with". While it is always necessary to use caution executing external code while holding a lock, if one can trust callers not to do too do anything in their callback that might require another lock, it may be practical to have the method guard the property access with a lock, such that updates which aren't compatible with `CompareExchange` could still be performed quasi-atomically.

Passing things be ref is an excellent pattern; too bad it's not used more.

Is there a Google Keep API?

I have been waiting to see if Google would open a Keep API. When I discovered Google Tasks, and saw that it had an Android app, web app, and API, I converted over to Tasks. This may not directly answer your question, but it is my solution to the Keep API problem.

Tasks doesn't have a reminder alarm exactly like Keep. I can live without that if I also connect with the Calendar API.

https://developers.google.com/google-apps/tasks/

How to select data of a table from another database in SQL Server?

In SQL Server 2012 and above, you don't need to create a link. You can execute directly

SELECT * FROM [TARGET_DATABASE].dbo.[TABLE] AS _TARGET

I don't know whether previous versions of SQL Server work as well

Mercurial — revert back to old version and continue from there

I'd install Tortoise Hg (a free GUI for Mercurial) and use that. You can then just right-click on a revision you might want to return to - with all the commit messages there in front of your eyes - and 'Revert all files'. Makes it intuitive and easy to roll backwards and forwards between versions of a fileset, which can be really useful if you are looking to establish when a problem first appeared.

calling another method from the main method in java

You can only call instance method like do() (which is an illegal method name, incidentally) against an instance of the class:

public static void main(String[] args){
  new Foo().doSomething();
}

public void doSomething(){}

Alternatively, make doSomething() static as well, if that works for your design.

C++ alignment when printing cout <<

At the time you emit the very first line,

Artist  Title   Price   Genre   Disc    Sale    Tax Cash

to achieve "alignment", you have to know "in advance" how wide each column will need to be (otherwise, alignment is impossible). Once you do know the needed width for each column (there are several possible ways to achieve that depending on where your data's coming from), then the setw function mentioned in the other answer will help, or (more brutally;-) you could emit carefully computed number of extra spaces (clunky, to be sure), etc. I don't recommend tabs anyway as you have no real control on how the final output device will render those, in general.

Back to the core issue, if you have each column's value in a vector<T> of some sort, for example, you can do a first formatting pass to determine the maximum width of the column, for example (be sure to take into account the width of the header for the column, too, of course).

If your rows are coming "one by one", and alignment is crucial, you'll have to cache or buffer the rows as they come in (in memory if they fit, otherwise on a disk file that you'll later "rewind" and re-read from the start), taking care to keep updated the vector of "maximum widths of each column" as the rows do come. You can't output anything (not even the headers!), if keeping alignment is crucial, until you've seen the very last row (unless you somehow magically have previous knowledge of the columns' widths, of course;-).

How to Round to the nearest whole number in C#

Use Math.Round:

double roundedValue = Math.Round(value, 0)

internal/modules/cjs/loader.js:582 throw err

try following command

remove node_modules and package-lock.json

rm -rf node_modules package-lock.json

then run following command to install dependencies

npm install

finally, run your package by following command.

npm start

Set a DateTime database field to "Now"

An alternative to GETDATE() is CURRENT_TIMESTAMP. Does the exact same thing.

This page didn't load Google Maps correctly. See the JavaScript console for technical details

Google recently changed the terms of use of its Google Maps APIs; if you were already using them on a website (different from localhost) prior to June 22nd, 2016, nothing will change for you; otherwise, you will get the aforementioned issue and need an API key in order to fix your error. The free API key is valid up to 25,000 map loads per day.

In this article you will find everything you may need to know regarding the topic, including a tutorial to fix your error:

Google Maps API error: MissingKeyMapError [SOLVED]

Also, remember to replace YOUR_API_KEY with your actual API key!

Python Requests and persistent sessions

snippet to retrieve json data, password protected

import requests

username = "my_user_name"
password = "my_super_secret"
url = "https://www.my_base_url.com"
the_page_i_want = "/my_json_data_page"

session = requests.Session()
# retrieve cookie value
resp = session.get(url+'/login')
csrf_token = resp.cookies['csrftoken']
# login, add referer
resp = session.post(url+"/login",
                  data={
                      'username': username,
                      'password': password,
                      'csrfmiddlewaretoken': csrf_token,
                      'next': the_page_i_want,
                  },
                  headers=dict(Referer=url+"/login"))
print(resp.json())

How to convert a String to Bytearray

You don't need underscore, just use built-in map:

_x000D_
_x000D_
var string = 'Hello World!';_x000D_
_x000D_
document.write(string.split('').map(function(c) { return c.charCodeAt(); }));
_x000D_
_x000D_
_x000D_

Setup a Git server with msysgit on Windows

There may simply not be such a guide. If so, you may not have much luck convincing anybody to write one, because it would be a lot of work.

I would recommend either of two things. The easier one is to follow the guide you have slavishly, which means forgetting about msysgit.

The harder one is to put up a Linux server - perhaps as a guest under Windows using VirtualBox (free) or VMWare or Parallels (pay), and then follow one of the many sets of instructions Google will lead you to. But you will probably find those instructions are insufficient - they usually assume you've already set up an ssh server, for example, so you have to get that info elsewhere. I've done that twice, and can say that unless you're already something of a Linux guru, it will be a struggle.

Registry Key '...' has value '1.7', but '1.6' is required. Java 1.7 is Installed and the Registry is Pointing to it

Change to directory with correct java.exe i.e. go to the required JDK version java.exe

cd C:/Program Files/Java/jdk1.7.0_25/bin

Run the java.exe from this directory, it has precedence over registry and $PATH settings.

java -jar C:/installed/selenium-server-standalone-2.53.0.jar 

How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?

If you want 8 bit representation of characters that used in many encoding, this may help you.

You must change variable targetEncoding to whatever encoding you want.

Encoding targetEncoding = Encoding.GetEncoding(874); // Your target encoding
Encoding utf8 = Encoding.UTF8;

var stringBytes = utf8.GetBytes(Name);
var stringTargetBytes = Encoding.Convert(utf8, targetEncoding, stringBytes);
var ascii8BitRepresentAsCsString = Encoding.GetEncoding("Latin1").GetString(stringTargetBytes);

Setting default value in select drop-down using Angularjs

I could help you out with the html:

<option value="">abc</option>

instead of

<option value="4">abc</option>

to set abc as the default value.

How to drop all tables from the database with manage.py CLI in Django?

If you are using psql and have django-more 2.0.0 installed, you can do

manage.py reset_schema

C# Creating and using Functions

Note: in C# the term "function" is often replaced by the term "method". For the sake of this question there is no difference, so I'll just use the term "function".

Thats not true. you may read about (func type+ Lambda expressions),( anonymous function"using delegates type"),(action type +Lambda expressions ),(Predicate type+Lambda expressions). etc...etc... this will work.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

           int a;
           int b;
           int c;

           Console.WriteLine("Enter value of 'a':");
           a = Convert.ToInt32(Console.ReadLine());

           Console.WriteLine("Enter value of 'b':");
           b = Convert.ToInt32(Console.ReadLine());

           Func<int, int, int> funcAdd = (x, y) => x + y;
           c=funcAdd.Invoke(a, b);
           Console.WriteLine(Convert.ToString(c));

        }

     }
}

Docker how to change repository name or rename image?

As a shorthand you can run:

docker tag d58 myname/server:latest

Where d58 represents the first 3 characters of the IMAGE ID,in this case, that's all you need.

Finally, you can remove the old image as follows:

docker rmi server

How can I do SELECT UNIQUE with LINQ?

var uniqueColors = (from dbo in database.MainTable 
                    where dbo.Property == true
                    select dbo.Color.Name).Distinct();

How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable

I had same issue with primefaces 5.3 and I went through all the points described by BalusC with no result. I followed his advice of debugging FileUploadRenderer#decode() and I discovered that my web.xml was unproperly set

<context-param>
  <param-name>primefaces.UPLOADER</param-name>
  <param-value>auto|native|commons</param-value>
</context-param>

The param-value must be 1 of these 3 values but not all of them!! The whole context-param section can be removed and the default will be auto

'ssh' is not recognized as an internal or external command

For Windows, first install the git base from here: https://git-scm.com/downloads

Next, set the environment variable:

  1. Press Windows+R and type sysdm.cpl
  2. Select advance -> Environment variable
  3. Select path-> edit the path and paste the below line:
C:\Program Files\Git\git-bash.exe

To test it, open the command window: press Windows+R, type cmd and then type ssh.

Convert list of ASCII codes to string (byte array) in Python

Shorter version of previous using map() function (works for python 2.7):

"".join(map(chr, myList))

error: unknown type name ‘bool’

C90 does not support the boolean data type.

C99 does include it with this include:

#include <stdbool.h>

How can you get the build/version number of your Android application?

Using Gradle and BuildConfig

Getting the VERSION_NAME from BuildConfig

BuildConfig.VERSION_NAME

Yep, it's that easy now.

Is it returning an empty string for VERSION_NAME?

If you're getting an empty string for BuildConfig.VERSION_NAME then read on.

I kept getting an empty string for BuildConfig.VERSION_NAME, because I wasn't setting the versionName in my Grade build file (I migrated from Ant to Gradle). So, here are instructions for ensuring you're setting your VERSION_NAME via Gradle.

File build.gradle

def versionMajor = 3
def versionMinor = 0
def versionPatch = 0
def versionBuild = 0 // Bump for dogfood builds, public betas, etc.

android {

  defaultConfig {
    versionCode versionMajor * 10000 + versionMinor * 1000 + versionPatch * 100 + versionBuild

    versionName "${versionMajor}.${versionMinor}.${versionPatch}"
  }

}

Note: This is from the masterful Jake Wharton.

Removing versionName and versionCode from AndroidManifest.xml

And since you've set the versionName and versionCode in the build.gradle file now, you can also remove them from your AndroidManifest.xml file, if they are there.

What is the difference between match_parent and fill_parent?

match_parent, which means that the view wants to be as big as its parent (minus padding).

wrap_content, which means that the view wants to be just big enough to enclose its content (plus padding)

For sake of better illustration, I have created a sample layout that demonstrate this concept. To see it's effect, I added a border of each textView content.

In "Match parent" textView content, we can see it's layout width spread out of it's parent whole length.

But we can see in "Wrap Content" textView content, it's layout width wrapped in of it's content(Wrap Content) length.

Android Layout

How do I change the default schema in sql developer?

After you granted the permissions to the specified user you have to do this at filtering:

First step:

First Step to change default Tables

Second step:

Second Step to change default Tables

Now you will be able to display the tables after you changed the default load Alter session to the desire schema (using a Trigger after LOG ON).

Equivalent of Oracle's RowID in SQL Server

If you want to uniquely identify a row within the table rather than your result set, then you need to look at using something like an IDENTITY column. See "IDENTITY property" in the SQL Server help. SQL Server does not auto-generate an ID for each row in the table as Oracle does, so you have to go to the trouble of creating your own ID column and explicitly fetch it in your query.

EDIT: for dynamic numbering of result set rows see below, but that would probably an equivalent for Oracle's ROWNUM and I assume from all the comments on the page that you want the stuff above. For SQL Server 2005 and later you can use the new Ranking Functions function to achieve dynamic numbering of rows.

For example I do this on a query of mine:

select row_number() over (order by rn_execution_date asc) as 'Row Number', rn_execution_date as 'Execution Date', count(*) as 'Count'
from td.run
where rn_execution_date >= '2009-05-19'
group by rn_execution_date
order by rn_execution_date asc

Will give you:

Row Number  Execution Date           Count
----------  -----------------        -----
1          2009-05-19 00:00:00.000  280
2          2009-05-20 00:00:00.000  269
3          2009-05-21 00:00:00.000  279

There's also an article on support.microsoft.com on dynamically numbering rows.

How to check if $? is not equal to zero in unix shell scripting?

I put together some code that may help to see how return value vs returned strings works. There may be a better way, but this is what I found through testing.

#!/bin/sh
#
# ro
#

pass(){
  echo passed
  return 0;   # no errors
}
fail(){
  echo failed
  return 1;   # has an error
}
t(){
  echo true, has error
}
f(){
  echo false, no error
}

dv=$(printf "%60s"); dv=${dv// /-}

echo return code good for one use, not available for echo
echo $dv
pass
[ $? -gt 0 ] && t || f
echo "function pass: \$? $?" ' return value is gone'
echo
fail
[ $? -gt 0 ] && t || f
echo "function fail: \$? $?" ' return value is gone'
echo

echo save return code to var k for continued usage
echo $dv
pass
k=$?
[ $k -gt 0 ] && t || f
echo "function pass: \$k $k"
echo
fail
k=$?
[ $k -gt 0 ] && t || f
echo "function fail: \$k $k"
echo

# direct evaluation of the return value
# note that (...) and $(...) executes in a subshell
# with return value to calling shell
# ((...)) is for math/string evaluation

echo direct evaluations of the return value:
echo '  by if (pass) and if (fail)'
echo $dv
if (pass); then
  echo pass has no errors
else
  echo pass has errors
fi
if (fail); then
  echo fail has no errors
else
  echo fail has errors
fi

# this code results in error because of returned string (stdout)
# but comment out the echo statements in pass/fail functions and this code succeeds
echo
echo '  by if $(pass) and if $(fail) ..this succeeds if no echo to stdout from function'
echo $dv
if $(pass); then
  echo pass has no errors
else
  echo pass has errors
fi
if $(fail); then
  echo fail has no errors
else
  echo fail has errors
fi

echo
echo '  by if ((pass)) and if ((fail)) ..this always fails'
echo $dv
if ((pass)); then
  echo pass has no errors
else
  echo pass has errors
fi
if ((fail)); then
  echo fail has no errors
else
  echo fail has errors
fi

echo 
s=$(pass)
r=$?
echo pass, "s: $s  ,  r: $r"
s=$(fail)
r=$?
echo fail, "s: $s  ,  r: $r"

Custom CSS for <audio> tag?

There is not currently any way to style HTML5 <audio> players using CSS. Instead, you can leave off the control attribute, and implement your own controls using Javascript. If you don't want to implement them all on your own, I'd recommend using an existing themeable HTML5 audio player, such as jPlayer.

Including external jar-files in a new jar-file build with Ant

Two options, either reference the new jars in your classpath or unpack all classes in the enclosing jars and re-jar the whole lot! As far as I know packaging jars within jars is not recommeneded and you'll forever have the class not found exception!

How to check which locks are held on a table

To add to the other responses, sp_lock can also be used to dump full lock information on all running processes. The output can be overwhelming, but if you want to know exactly what is locked, it's a valuable one to run. I usually use it along with sp_who2 to quickly zero in on locking problems.

There are multiple different versions of "friendlier" sp_lock procedures available online, depending on the version of SQL Server in question.

In your case, for SQL Server 2005, sp_lock is still available, but deprecated, so it's now recommended to use the sys.dm_tran_locks view for this kind of thing. You can find an example of how to "roll your own" sp_lock function here.

How to clear Tkinter Canvas?

Items drawn to the canvas are persistent. create_rectangle returns an item id that you need to keep track of. If you don't remove old items your program will eventually slow down.

From Fredrik Lundh's An Introduction to Tkinter:

Note that items added to the canvas are kept until you remove them. If you want to change the drawing, you can either use methods like coords, itemconfig, and move to modify the items, or use delete to remove them.

size of struct in C

The compiler may add padding for alignment requirements. Note that this applies not only to padding between the fields of a struct, but also may apply to the end of the struct (so that arrays of the structure type will have each element properly aligned).

For example:

struct foo_t {
    int x;
    char c;
};

Even though the c field doesn't need padding, the struct will generally have a sizeof(struct foo_t) == 8 (on a 32-bit system - rather a system with a 32-bit int type) because there will need to be 3 bytes of padding after the c field.

Note that the padding might not be required by the system (like x86 or Cortex M3) but compilers might still add it for performance reasons.

Auto margins don't center image in page

put this in the body's css: background:#3D668F; then add: display: block; margin: auto; to the img's css.

Twitter Bootstrap modal on mobile devices

Found a very hacky solution to this problem, but it works. I added a class to the link that is used to open the modal (With the data-target), then using Jquery, added a click event to that class that gets the data-target, finds the modal it is supposed to open, and then opens it via Javascript. Works just fine for me. I also added a mobile check on mine so that it only runs on mobile, but that's not required.

$('.forceOpen').click(function() {
  var id = $(this).attr('data-target');
  $('.modal').modal('hide');
  $(id).modal('show');
});

Core dumped, but core file is not in the current directory?

Writing instructions to get a core dump under Ubuntu 16.04 LTS:

  1. As @jtn has mentioned in his answer, Ubuntu delegates the display of crashes to apport, which in turn refuses to write the dump because the program is not an installed package. Before making changes

  2. To remedy the problem, we need to make sure apport writes core dump files for non-package programs as well. To do so, create a file named ~/.config/apport/settings with the following contents:
    [main] unpackaged=true

  3. Now crash your program again, and see your crash files being generated within folder: /var/crash with names like *.1000.crash. Note that these files cannot be read by gdb directly. After making changes
  4. [Optional] To make the dumps readble by gdb, run the following command:

    apport-unpack <location_of_report> <target_directory>

References: Core_dump – Oracle VM VirtualBox

Change URL parameters

Here I have taken Adil Malik's answer and fixed the 3 issues I identified with it.

/**
 * Adds or updates a URL parameter.
 *
 * @param {string} url  the URL to modify
 * @param {string} param  the name of the parameter
 * @param {string} paramVal  the new value for the parameter
 * @return {string}  the updated URL
 */
self.setParameter = function (url, param, paramVal){
  // http://stackoverflow.com/a/10997390/2391566
  var parts = url.split('?');
  var baseUrl = parts[0];
  var oldQueryString = parts[1];
  var newParameters = [];
  if (oldQueryString) {
    var oldParameters = oldQueryString.split('&');
    for (var i = 0; i < oldParameters.length; i++) {
      if(oldParameters[i].split('=')[0] != param) {
        newParameters.push(oldParameters[i]);
      }
    }
  }
  if (paramVal !== '' && paramVal !== null && typeof paramVal !== 'undefined') {
    newParameters.push(param + '=' + encodeURI(paramVal));
  }
  if (newParameters.length > 0) {
    return baseUrl + '?' + newParameters.join('&');
  } else {
    return baseUrl;
  }
}

MySQL Error: #1142 - SELECT command denied to user

I run into this problem as well, the case with me was incorrect naming . I was migrating from local server to online server. my SQL command had "database.tablename.column" structure. the name of database in online server was different. for example my code was "pet.item.name" while it needed to be "pet_app.item.name" changing database name solved my problem.

C# password TextBox in a ASP.net website

Simply select texbox property 'TextMode' and select password...

<asp:TextBox ID="TextBox1" TextMode="Password" runat="server" />

Select all elements with a "data-xxx" attribute without using jQuery

document.querySelectorAll('data-foo')

to get list of all elements having attribute data-foo

If you want to get element with data attribute which is having some specific value e.g

<div data-foo="1"></div>
<div data-foo="2" ></div>

and I want to get div with data-foo set to "2"

document.querySelector('[data-foo="2"]')

But here comes the twist what if I want to match the data attirubte value with some variable's value like I want to get element if data-foo attribute is set to i

var i=2;

so you can dynamically select the element having specific data element using template literals

document.querySelector(`[data-foo="${i}"]`)

Note even if you don't write value in string it gets converted to string like if I write

<div data-foo=1></div>

and then inspect the element in Chrome developer tool the element will be shown as below

<div data-foo="1"></div>

You can also cross verify by writing below code in console

console.log(typeof document.querySelector(`[data-foo]="${i}"`).dataset('dataFoo'))

why I have written 'dataFoo' though the attribute is data-foo reason dataset properties are converted to camelCase properties

I have referred below links

https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-* https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

This is my first answer on stackoverflow please let me know how can I improve my answer writing way.

How to navigate to a section of a page

Use an call thru section, it works

<div id="content">
     <section id="home">
               ...
     </section>

Call the above the thru

 <a href="#home">page1</a>

Scrolling needs jquery paste this.. on above to ending body closing tag..

<script>
  $(function() {
      $('a[href*=#]:not([href=#])').click(function() {
          if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
              var target = $(this.hash);
              target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
              if (target.length) {
                  $('html,body').animate({
                      scrollTop: target.offset().top
                  }, 1000);
                  return false;
              }
          }
      });
  });
</script>

How to integrate sourcetree for gitlab

There does not seem to be a way to set up a GitLab account within SourceTree, but if you just clone a remote repo it will use your SSH key correctly.

Edit: After SourceTree 3.0 it is possible to add various non-Atlassian git accounts, including GitLab.

TypeError: 'str' object is not callable (Python)

Whenever that happens, just issue the following ( it was also posted above)

>>> del str

That should fix it.

Google maps API V3 - multiple markers on exact same spot

Updated to work with MarkerClustererPlus.

  google.maps.event.trigger(mc, "click", cClusterIcon.cluster_);
  google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name

  // BEGIN MODIFICATION
  var zoom = mc.getMap().getZoom();
  // Trying to pull this dynamically made the more zoomed in clusters not render
  // when then kind of made this useless. -NNC @ BNB
  // var maxZoom = mc.getMaxZoom();
  var maxZoom = 15;
  // if we have reached the maxZoom and there is more than 1 marker in this cluster
  // use our onClick method to popup a list of options
  if (zoom >= maxZoom && cClusterIcon.cluster_.markers_.length > 1) {
    var markers = cClusterIcon.cluster_.markers_;
    var a = 360.0 / markers.length;
    for (var i=0; i < markers.length; i++)
    {
        var pos = markers[i].getPosition();
        var newLat = pos.lat() + -.00004 * Math.cos((+a*i) / 180 * Math.PI);  // x
        var newLng = pos.lng() + -.00004 * Math.sin((+a*i) / 180 * Math.PI);  // Y
        var finalLatLng = new google.maps.LatLng(newLat,newLng);
        markers[i].setPosition(finalLatLng);
        markers[i].setMap(cClusterIcon.cluster_.map_);
    }
    cClusterIcon.hide();
    return ;
  }
  // END MODIFICATION

POST data to a URL in PHP

Your question is not particularly clear, but in case you want to send POST data to a url without using a form, you can use either fsockopen or curl.

Here's a pretty good walkthrough of both

adb not finding my device / phone (MacOS X)

Here is another thing to try, if like me you have tried all of the other answers and have had no luck.

In my case (Android 4.3) I went into the USB settings under the notifications and changed from MTP mode (Media device) to PTP (camera) and as soon as it switched, the device showed up in the ADT device list.

Error installing mysql2: Failed to build gem native extension

On Ubuntu/Debian and other distributions using aptitude:

sudo apt-get install libmysql-ruby libmysqlclient-dev

Package libmysql-ruby has been phased out and replaced by ruby-mysql. This is where I found the solution.

If the above command doesn't work because libmysql-ruby cannot be found, the following should be sufficient:

sudo apt-get install libmysqlclient-dev

On Red Hat/CentOS and other distributions using yum:

sudo yum install mysql-devel

On Mac OS X with Homebrew:

brew install mysql

Is there a reason for C#'s reuse of the variable in a foreach?

Having been bitten by this, I have a habit of including locally defined variables in the innermost scope which I use to transfer to any closure. In your example:

foreach (var s in strings)
    query = query.Where(i => i.Prop == s); // access to modified closure

I do:

foreach (var s in strings)
{
    string search = s;
    query = query.Where(i => i.Prop == search); // New definition ensures unique per iteration.
}        

Once you have that habit, you can avoid it in the very rare case you actually intended to bind to the outer scopes. To be honest, I don't think I have ever done so.

ImportError: No module named requests

To install requests module on Debian/Ubuntu for Python2:

$ sudo apt-get install python-requests

And for Python3 the command is:

$ sudo apt-get install python3-requests

Python Pandas : group by in group by and average?

If you want to first take mean on the combination of ['cluster', 'org'] and then take mean on cluster groups, you can use:

In [59]: (df.groupby(['cluster', 'org'], as_index=False).mean()
            .groupby('cluster')['time'].mean())
Out[59]:
cluster
1          15
2          54
3           6
Name: time, dtype: int64

If you want the mean of cluster groups only, then you can use:

In [58]: df.groupby(['cluster']).mean()
Out[58]:
              time
cluster
1        12.333333
2        54.000000
3         6.000000

You can also use groupby on ['cluster', 'org'] and then use mean():

In [57]: df.groupby(['cluster', 'org']).mean()
Out[57]:
               time
cluster org
1       a    438886
        c        23
2       d      9874
        h        34
3       w         6

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I had similar error: "Expecting value: line 1 column 1 (char 0)"

It helped for me to add "myfile.seek(0)", move the pointer to the 0 character

with open(storage_path, 'r') as myfile:
if len(myfile.readlines()) != 0:
    myfile.seek(0)
    Bank_0 = json.load(myfile)

Display calendar to pick a date in java

The LGoodDatePicker library includes a (swing) DatePicker component, which allows the user to choose dates from a calendar. (By default, the users can also type dates from the keyboard, but keyboard entry can be disabled if desired). The DatePicker has automatic data validation, which means (among other things) that any date that the user enters will always be converted to your desired date format.

Fair disclosure: I'm the primary developer.

Since the DatePicker is a swing component, you can add it to any other swing container including (in your scenario) the cells of a JTable.

The most commonly used date formats are automatically supported, and additional date formats can be added if desired.

To enforce your desired date format, you would most likely want to set your chosen format to be the default "display format" for the DatePicker. Formats can be specified by using the Java 8 DateTimeFormatter Patterns. No matter what the user types (or clicks), the date will always be converted to the specified format as soon as the user is done.

Besides the DatePicker, the library also has the TimePicker and DateTimePicker components. I pasted screenshots of all the components (and the demo program) below.

The library can be installed into your Java project from the project release page.

The project home page is on Github at:
https://github.com/LGoodDatePicker/LGoodDatePicker .


DateTimePicker screenshot


DateTimePicker examples


Demo screenshot

Excel VBA code to copy a specific string to clipboard

The simplest (Non Win32) way is to add a UserForm to your VBA project (if you don't already have one) or alternatively add a reference to Microsoft Forms 2 Object Library, then from a sheet/module you can simply:

With New MSForms.DataObject
    .SetText "http://zombo.com"
    .PutInClipboard
End With

Base64 Java encode and decode a string

You can use following approach:

import org.apache.commons.codec.binary.Base64;

// Encode data on your side using BASE64
byte[] bytesEncoded = Base64.encodeBase64(str.getBytes());
System.out.println("encoded value is " + new String(bytesEncoded));

// Decode data on other side, by processing encoded data
byte[] valueDecoded = Base64.decodeBase64(bytesEncoded);
System.out.println("Decoded value is " + new String(valueDecoded));

Hope this answers your doubt.

Javascript Error Null is not an Object

Any JS code which executes and deals with DOM elements should execute after the DOM elements have been created. JS code is interpreted from top to down as layed out in the HTML. So, if there is a tag before the DOM elements, the JS code within script tag will execute as the browser parses the HTML page.

So, in your case, you can put your DOM interacting code inside a function so that only function is defined but not executed.

Then you can add an event listener for document load to execute the function.

That will give you something like:

<script>
  function init() {
    var myButton = document.getElementById("myButton");
    var myTextfield = document.getElementById("myTextfield");
    myButton.onclick = function() {
      var userName = myTextfield.value;
      greetUser(userName);
    }
  }

  function greetUser(userName) {
    var greeting = "Hello " + userName + "!";
    document.getElementsByTagName ("h2")[0].innerHTML = greeting;
  }

  document.addEventListener('readystatechange', function() {
    if (document.readyState === "complete") {
      init();
    }
  });

</script>
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>

<form>
  <input type="text" id="myTextfield" placeholder="Type your name" />
  <input type="button" id="myButton" value="Go" />
</form>

Fiddle at - http://jsfiddle.net/poonia/qQMEg/4/

Split an NSString to access one particular piece

Either of these 2:

NSString *subString = [dateString subStringWithRange:NSMakeRange(0,2)];
NSString *subString = [[dateString componentsSeparatedByString:@"/"] objectAtIndex:0];

Though keep in mind that sometimes a date string is not formatted properly and a day ( or a month for that matter ) is shown as 8, rather than 08 so the first one might be the worst of the 2 solutions.

The latter should be put into a separate array so you can actually check for the length of the thing returned, so you do not get any exceptions thrown in the case of a corrupt or invalid date string from whatever source you have.

True and False for && logic and || Logic table

I`d like to add to the already good answers:

The symbols '+', '*' and '-' are sometimes used as shorthand in some older textbooks for OR,? and AND,? and NOT,¬ logical operators in Bool`s algebra. In C/C++ of course we use "and","&&" and "or","||" and "not","!".

Watch out: "true + true" evaluates to 2 in C/C++ via internal representation of true and false as 1 and 0, and the implicit cast to int!

int main ()
{
  std::cout <<  "true - true = " << true - true << std::endl;
// This can be used as signum function:
// "(x > 0) - (x < 0)" evaluates to +1 or -1 for numbers.
  std::cout <<  "true - false = " << true - false << std::endl;
  std::cout <<  "false - true = " << false - true << std::endl;
  std::cout <<  "false - false = " << false - false << std::endl << std::endl;

  std::cout <<  "true + true = " << true + true << std::endl;
  std::cout <<  "true + false = " << true + false << std::endl;
  std::cout <<  "false + true = " << false + true << std::endl;
  std::cout <<  "false + false = " << false + false << std::endl << std::endl;

  std::cout <<  "true * true = " << true * true << std::endl;
  std::cout <<  "true * false = " << true * false << std::endl;
  std::cout <<  "false * true = " << false * true << std::endl;
  std::cout <<  "false * false = " << false * false << std::endl << std::endl;

  std::cout <<  "true / true = " << true / true << std::endl;
  //  std::cout <<  true / false << std::endl; ///-Wdiv-by-zero
  std::cout <<  "false / true = " << false / true << std::endl << std::endl;
  //  std::cout <<  false / false << std::endl << std::endl; ///-Wdiv-by-zero

  std::cout <<  "(true || true) = " << (true || true) << std::endl;
  std::cout <<  "(true || false) = " << (true || false) << std::endl;
  std::cout <<  "(false || true) = " << (false || true) << std::endl;
  std::cout <<  "(false || false) = " << (false || false) << std::endl << std::endl;

  std::cout <<  "(true && true) = " << (true && true) << std::endl;
  std::cout <<  "(true && false) = " << (true && false) << std::endl;
  std::cout <<  "(false && true) = " << (false && true) << std::endl;
  std::cout <<  "(false && false) = " << (false && false) << std::endl << std::endl;

}

yields :

true - true = 0
true - false = 1
false - true = -1
false - false = 0

true + true = 2
true + false = 1
false + true = 1
false + false = 0

true * true = 1
true * false = 0
false * true = 0
false * false = 0

true / true = 1
false / true = 0

(true || true) = 1
(true || false) = 1
(false || true) = 1
(false || false) = 0

(true && true) = 1
(true && false) = 0
(false && true) = 0
(false && false) = 0

Difference between private, public, and protected inheritance

Public inheritance models an IS-A relationship. With

class B {};
class D : public B {};

every D is a B.

Private inheritance models an IS-IMPLEMENTED-USING relationship (or whatever that's called). With

class B {};
class D : private B {};

a D is not a B, but every D uses its B in its implementation. Private inheritance can always be eliminated by using containment instead:

class B {};
class D {
  private: 
    B b_;
};

This D, too, can be implemented using B, in this case using its b_. Containment is a less tight coupling between types than inheritance, so in general it should be preferred. Sometimes using containment instead of private inheritance is not as convenient as private inheritance. Often that's a lame excuse for being lazy.

I don't think anyone knows what protected inheritance models. At least I haven't seen any convincing explanation yet.

How do I add a newline using printf?

To write a newline use \n not /n the latter is just a slash and a n

Hexadecimal value 0x00 is a invalid character

In my case, it took some digging, but found it.

My Context

I'm looking at exception/error logs from the website using Elmah. Elmah returns the state of the server at the of time the exception, in the form of a large XML document. For our reporting engine I pretty-print the XML with XmlWriter.

During a website attack, I noticed that some xmls weren't parsing and was receiving this '.', hexadecimal value 0x00, is an invalid character. exception.

NON-RESOLUTION: I converted the document to a byte[] and sanitized it of 0x00, but it found none.

When I scanned the xml document, I found the following:

...
<form>
...
<item name="SomeField">
   <value
     string="C:\boot.ini&#x0;.htm" />
 </item>
...

There was the nul byte encoded as an html entity &#x0; !!!

RESOLUTION: To fix the encoding, I replaced the &#x0; value before loading it into my XmlDocument, because loading it will create the nul byte and it will be difficult to sanitize it from the object. Here's my entire process:

XmlDocument xml = new XmlDocument();
details.Xml = details.Xml.Replace("&#x0;", "[0x00]");  // in my case I want to see it, otherwise just replace with ""
xml.LoadXml(details.Xml);

string formattedXml = null;

// I have this in a helper function, but for this example I have put it in-line
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings {
    OmitXmlDeclaration = true,
    Indent = true,
    IndentChars = "\t",
    NewLineHandling = NewLineHandling.None,
};
using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
    xml.Save(writer);
    formattedXml = sb.ToString();
}

LESSON LEARNED: sanitize for illegal bytes using the associated html entity, if your incoming data is html encoded on entry.

Excel- compare two cell from different sheet, if true copy value from other cell

In your destination field you want to use VLOOKUP like so:

=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)

VLOOKUP Arguments:

  1. The set fields you want to lookup.
  2. The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
  3. This defines what field you want to display upon a match.
  4. FALSE tells VLOOKUP to do an exact match.