Programs & Examples On #Wmp

For issues relating to interfacing with the Windows Media Player (WMP).

Is there a simple JavaScript slider?

Here is a simple slider object for easy to use

pagecolumn_webparts_sliders

Python: How would you save a simple settings/config file?

If you want to use something like an INI file to hold settings, consider using configparser which loads key value pairs from a text file, and can easily write back to the file.

INI file has the format:

[Section]
key = value
key with spaces = somevalue

When does a process get SIGABRT (signal 6)?

A case when process get SIGABRT from itself: Hrvoje mentioned about a buried pure virtual being called from ctor generating an abort, i recreated an example for this. Here when d is to be constructed, it first calls its base class A ctor, and passes inside pointer to itself. the A ctor calls pure virtual method before table was filled with valid pointer, because d is not constructed yet.

#include<iostream>
using namespace std;
class A {
public:
 A(A *pa){pa->f();}
 virtual void f()=0;
};
class D : public A {
public:
 D():A(this){}
 virtual void f() {cout<<"D::f\n";}
};
int main(){
 D d;
 A *pa = &d;
 pa->f();
 return 0;
}

compile: g++ -o aa aa.cpp

ulimit -c unlimited

run: ./aa

pure virtual method called
terminate called without an active exception
Aborted (core dumped)

now lets quickly see the core file, and validate that SIGABRT was indeed called:

gdb aa core

see regs:

i r
rdx            0x6      6
rsi            0x69a    1690
rdi            0x69a    1690
rip            0x7feae3170c37

check code:

disas 0x7feae3170c37

mov    $0xea,%eax  = 234  <- this is the kill syscall, sends signal to process
syscall   <-----

http://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/

234 sys_tgkill pid_t tgid pid_t pid int sig = 6 = SIGABRT

:)

How to compare only date in moment.js

In my case i did following code for compare 2 dates may it will help you ...

_x000D_
_x000D_
var date1 = "2010-10-20";_x000D_
var date2 = "2010-10-20";_x000D_
var time1 = moment(date1).format('YYYY-MM-DD');_x000D_
var time2 = moment(date2).format('YYYY-MM-DD');_x000D_
if(time2 > time1){_x000D_
 console.log('date2 is Greter than date1');_x000D_
}else if(time2 > time1){_x000D_
 console.log('date2 is Less than date1');_x000D_
}else{_x000D_
 console.log('Both date are same');_x000D_
}
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

how do I create an infinite loop in JavaScript

By omitting all parts of the head, the loop can also become infinite:

for (;;) {}

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

so if you need want use this code )

import { useRoutes } from "./routes";

import { BrowserRouter as Router } from "react-router-dom";

export const App = () => {

const routes = useRoutes(true);

  return (

    <Router>

      <div className="container">{routes}</div>

    </Router>

  );

};

// ./routes.js 

import { Switch, Route, Redirect } from "react-router-dom";

export const useRoutes = (isAuthenticated) => {
  if (isAuthenticated) {
    return (
      <Switch>
        <Route path="/links" exact>
          <LinksPage />
        </Route>
        <Route path="/create" exact>
          <CreatePage />
        </Route>
        <Route path="/detail/:id">
          <DetailPage />
        </Route>
        <Redirect path="/create" />
      </Switch>
    );
  }
  return (
    <Switch>
      <Route path={"/"} exact>
        <AuthPage />
      </Route>
      <Redirect path={"/"} />
    </Switch>
  );
};

Android offline documentation and sample codes

Write the following in linux terminal:

$ wget -r http://developer.android.com/reference/packages.html

Passing data from controller to view in Laravel

Try with this code:

return View::make('user/regprofile', array
    (
        'students' => $students
    )
);

Or if you want to pass more variables into view:

return View::make('user/regprofile', array
    (
        'students'    =>  $students,
        'variable_1'  =>  $variable_1,
        'variable_2'  =>  $variable_2
    )
);

How to get JavaScript caller function line number? How to get JavaScript caller source URL?

My contribution to custom errors in JavaScript:

  1. First, I agree with this @B T guy at Inheriting from the Error object - where is the message property?, we have to built it properly (actually you have to use a js object library, my favorite: https://github.com/jiem/my-class):

    window.g3 = window.g3 || {};
    g3.Error = function (message, name, original) {
         this.original = original;
         this.name = name || 'Error.g3';
         this.message = message || 'A g3.Error was thrown!';
         (original)? this.stack = this.original.stack: this.stack = null;
         this.message += '<br>---STACK---<br>' + this.stack;
     };
    
     var ClassEmpty = function() {};
     ClassEmpty.prototype = Error.prototype;
     g3.Error.prototype = new ClassEmpty();
     g3.Error.prototype.constructor = g3.Error;
    
  2. then, we should define a global error handling function (optional) or, they'll end up to the engine:

    window.onerror = printError; 
    function printError(msg, url, line){
        document.getElementById('test').innerHTML = msg+'<br>at: '+url+'<br>line: '+line;
        return true;
    }
    
  3. finally, we should throw our custom errors carefully:

    //hit it!
    //throw new g3.Error('Hey, this is an error message!', 'Error.Factory.g3');
    throw new g3.Error('Hey, this is an error message!', 'Error.Factory.g3', new Error());
    

Only, when passing the third parameter as new Error() we are able to see the stack with function and line numbers!

At 2, the function can also handle error thrown by the engine as well.

Of course, the real question is if we really need it and when; there are cases (99% in my opinion) where a graceful return of false is enough and leave only some critical points to be shown with the thrown of an error.

Example: http://jsfiddle.net/centurianii/m2sQ3/1/

Convert String to System.IO.Stream

Try this:

// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
//byte[] byteArray = Encoding.ASCII.GetBytes(contents);
MemoryStream stream = new MemoryStream(byteArray);

and

// convert stream to string
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();

How do I get 'date-1' formatted as mm-dd-yyyy using PowerShell?

You can use the .tostring() method with datetime format specifiers to format to whatever you need:

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

(Get-Date).AddDays(-1).ToString('MM-dd-yyyy')
11-01-2013

Python: How to convert datetime format?

@Tim's answer only does half the work -- that gets it into a datetime.datetime object.

To get it into the string format you require, you use datetime.strftime:

print(datetime.strftime('%b %d,%Y'))

How to select a range of the second row to the last row

Sub SelectAllCellsInSheet(SheetName As String)
    lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
    Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
    Sheets(SheetName).Range("A2", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub

To use with ActiveSheet:

Call SelectAllCellsInSheet(ActiveSheet.Name)

expected assignment or function call: no-unused-expressions ReactJS

If You're using JSX inside a function with curly braces you need to modify it to parenthesis.

Wrong Code

return this.props.todos.map((todo) => {
            <h3> {todo.author} </h3>;
        });

Correct Code

//Change Curly Brace To Paranthesis   change {} to => ()
return this.props.todos.map((todo) => (
            <h3> {todo.author} </h3>;
        ));

Return outside function error in Python

You can only return from inside a function and not from a loop.

It seems like your return should be outside the while loop, and your complete code should be inside a function.

def func():
    N = int(input("enter a positive integer:"))
    counter = 1
    while (N > 0):
        counter = counter * N
        N -= 1
    return counter  # de-indent this 4 spaces to the left.

print func()

And if those codes are not inside a function, then you don't need a return at all. Just print the value of counter outside the while loop.

Nested JSON objects - do I have to use arrays for everything?

You don't need to use arrays.

JSON values can be arrays, objects, or primitives (numbers or strings).

You can write JSON like this:

{ 
    "stuff": {
        "onetype": [
            {"id":1,"name":"John Doe"},
            {"id":2,"name":"Don Joeh"}
        ],
        "othertype": {"id":2,"company":"ACME"}
    }, 
    "otherstuff": {
        "thing": [[1,42],[2,2]]
     }
}

You can use it like this:

obj.stuff.onetype[0].id
obj.stuff.othertype.id
obj.otherstuff.thing[0][1]  //thing is a nested array or a 2-by-2 matrix.
                            //I'm not sure whether you intended to do that.

What is the best way to concatenate two vectors?

Depends on whether you really need to physically concatenate the two vectors or you want to give the appearance of concatenation of the sake of iteration. The boost::join function

http://www.boost.org/doc/libs/1_43_0/libs/range/doc/html/range/reference/utilities/join.html

will give you this.

std::vector<int> v0;
v0.push_back(1);
v0.push_back(2);
v0.push_back(3);

std::vector<int> v1;
v1.push_back(4);
v1.push_back(5);
v1.push_back(6);
...

BOOST_FOREACH(const int & i, boost::join(v0, v1)){
    cout << i << endl;
}

should give you

1
2
3
4
5
6

Note boost::join does not copy the two vectors into a new container but generates a pair of iterators (range) that cover the span of both containers. There will be some performance overhead but maybe less that copying all the data to a new container first.

Accessing Websites through a Different Port?

If your question is about IIS(or other server) configuration - yes, it's possible. All you need is to create ports mapping under your Default Site or Virtual Directory and assign specific ports to the site you need. For example it is sometimes very useful for web services, when default port is assigned to some UI front-end and you want to assign service to the same address but with different port.

What is the height of Navigation Bar in iOS 7?

I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics

If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.

UIBarPositionTopAttached

Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

C# Remove object from list of objects

Firstly, you are using Capacity instead of Count.

Secondly, if you only need to delete one item, then you can happily use a loop. You just need to ensure that you break out of the loop after deleting an item, like so:

int target = 4;

for (int i = 0; i < list.Count; ++i)
{
    if (list[i].UniqueID == target)
    {
        list.RemoveAt(i);
        break;
    }
}

If you want to remove all items from the list that match an ID, it becomes even easier because you can use List<T>.RemoveAll(Predicate<T> match)

int target = 4;

list.RemoveAll(element => element.UniqueID == target);

How to make the web page height to fit screen height

As another guy described here, all you need to do is add

height: 100vh;

to the style of whatever you need to fill the screen

JAVA Unsupported major.minor version 51.0

This is because of a higher JDK during compile time and lower JDK during runtime. So you just need to update your JDK version, possible to JDK 7

You may also check Unsupported major.minor version 51.0

Select count(*) from result query

You can wrap your query in another SELECT:

select count(*)
from
(
  select count(SID) tot  -- add alias
  from Test 
  where Date = '2012-12-10' 
  group by SID
) src;  -- add alias

See SQL Fiddle with Demo

In order for it to work, the count(SID) need a column alias and you have to provide an alias to the subquery itself.

Interactive shell using Docker Compose

The canonical way to get an interactive shell with docker-compose is to use:

docker-compose run --rm myapp

You can set stdin_open: true, tty: true, however that won't actually give you a proper shell with up, because logs are being streamed from all the containers.

You can also use

docker exec -ti <container name> /bin/bash

to get a shell on a running container.

How to get response status code from jQuery.ajax?

You can check your respone content, just console.log it and you will see whitch property have a status code. If you do not understand jsons, please refer to the video: https://www.youtube.com/watch?v=Bv_5Zv5c-Ts

It explains very basic knowledge that let you feel more comfortable with javascript.

You can do it with shorter version of ajax request, please see code above:

$.get("example.url.com", function(data) {
                console.log(data);
            }).done(function() {
               // TO DO ON DONE
            }).fail(function(data, textStatus, xhr) {
                 //This shows status code eg. 403
                 console.log("error", data.status);
                 //This shows status message eg. Forbidden
                 console.log("STATUS: "+xhr);
            }).always(function() {
                 //TO-DO after fail/done request.
                 console.log("ended");
            });

Example console output:

error 403 
STATUS: Forbidden 
ended

How to make a phone call using intent in Android?

Just the simple oneliner without any additional permissions needed:

private void dialContactPhone(final String phoneNumber) {
    startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phoneNumber, null)));
}

Is there a way to detach matplotlib plots so that the computation can continue?

In my case, I wanted to have several windows pop up as they are being computed. For reference, this is the way:

from matplotlib.pyplot import draw, figure, show
f1, f2 = figure(), figure()
af1 = f1.add_subplot(111)
af2 = f2.add_subplot(111)
af1.plot([1,2,3])
af2.plot([6,5,4])
draw() 
print 'continuing computation'
show()

PS. A quite useful guide to matplotlib's OO interface.

Delete entire row if cell contains the string X

Ok I know this for VBA but if you need to do this for a once off bulk delete you can use the following Excel functionality: http://blog.contextures.com/archives/2010/06/21/fast-way-to-find-and-delete-excel-rows/ Hope this helps anyone

Example looking for the string "paper":

  1. In the Find and Replace dialog box, type "paper" in the Find What box.
  2. Click Find All, to see a list of cells with "paper"
  3. Select an item in the list, and press Ctrl+A, to select the entire list, and to select all the "paper" cells on the worksheet.
  4. On the Ribbon's Home tab, click Delete, and then click Delete Sheet Rows.

correct way to define class variables in Python

Neither way is necessarily correct or incorrect, they are just two different kinds of class elements:

  • Elements outside the __init__ method are static elements; they belong to the class.
  • Elements inside the __init__ method are elements of the object (self); they don't belong to the class.

You'll see it more clearly with some code:

class MyClass:
    static_elem = 123

    def __init__(self):
        self.object_elem = 456

c1 = MyClass()
c2 = MyClass()

# Initial values of both elements
>>> print c1.static_elem, c1.object_elem 
123 456
>>> print c2.static_elem, c2.object_elem
123 456

# Nothing new so far ...

# Let's try changing the static element
MyClass.static_elem = 999

>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456

# Now, let's try changing the object element
c1.object_elem = 888

>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456

As you can see, when we changed the class element, it changed for both objects. But, when we changed the object element, the other object remained unchanged.

Pick a random value from an enum?

The only thing I would suggest is caching the result of values() because each call copies an array. Also, don't create a Random every time. Keep one. Other than that what you're doing is fine. So:

public enum Letter {
  A,
  B,
  C,
  //...

  private static final List<Letter> VALUES =
    Collections.unmodifiableList(Arrays.asList(values()));
  private static final int SIZE = VALUES.size();
  private static final Random RANDOM = new Random();

  public static Letter randomLetter()  {
    return VALUES.get(RANDOM.nextInt(SIZE));
  }
}

What are DDL and DML?

In simple words.

DDL(Data definition language): will work on structure of data. define the data structures.

DML (data manipulation language): will work on data. manipulates the data itself

MySQL: #126 - Incorrect key file for table

Now of the other answers solved it for me. Turns out that renaming a column and an index in the same query caused the error.

Not working:

-- rename column and rename index
ALTER TABLE `client_types`
    CHANGE `template_path` `path` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
    DROP INDEX client_types_template_path_unique,
    ADD UNIQUE INDEX `client_types_path_unique` (`path` ASC);

Works (2 statements):

-- rename column
ALTER TABLE `client_types`
    CHANGE `template_path` `path` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;
-- rename index
ALTER TABLE `client_types`
    DROP INDEX client_types_template_path_unique,
    ADD UNIQUE INDEX `client_types_path_unique` (`path` ASC);

This was on MariaDB 10.0.20. There were no errors with the same query on MySQL 5.5.48.

Returning string from C function

char word[length];
char *rtnPtr = word;
...
return rtnPtr;

This is not good. You are returning a pointer to an automatic (scoped) variable, which will be destroyed when the function returns. The pointer will be left pointing at a destroyed variable, which will almost certainly produce "strange" results (undefined behaviour).

You should be allocating the string with malloc (e.g. char *rtnPtr = malloc(length)), then freeing it later in main.

Use LINQ to get items in one List<>, that are not in another List<>

Bit late to the party but a good solution which is also Linq to SQL compatible is:

List<string> list1 = new List<string>() { "1", "2", "3" };
List<string> list2 = new List<string>() { "2", "4" };

List<string> inList1ButNotList2 = (from o in list1
                                   join p in list2 on o equals p into t
                                   from od in t.DefaultIfEmpty()
                                   where od == null
                                   select o).ToList<string>();

List<string> inList2ButNotList1 = (from o in list2
                                   join p in list1 on o equals p into t
                                   from od in t.DefaultIfEmpty()
                                   where od == null
                                   select o).ToList<string>();

List<string> inBoth = (from o in list1
                       join p in list2 on o equals p into t
                       from od in t.DefaultIfEmpty()
                       where od != null
                       select od).ToList<string>();

Kudos to http://www.dotnet-tricks.com/Tutorial/linq/UXPF181012-SQL-Joins-with-C

C# ListView Column Width Auto

I believe the author was looking for an equivalent method via the IDE that would generate the code behind and make sure all parameters were in place, etc. Found this from MS:

Creating Event Handlers on the Windows Forms Designer

Coming from a VB background myself, this is what I was looking for, here is the brief version for the click adverse:

  1. Click the form or control that you want to create an event handler for.
  2. In the Properties window, click the Events button
  3. In the list of available events, click the event that you want to create an event handler for.
  4. In the box to the right of the event name, type the name of the handler and press ENTER

Find which rows have different values for a given column in Teradata SQL

This works for PL/SQL:

select count(*), id,address from table group by id,address having count(*)<2

Removing duplicates from a String in Java

Hope this will help.

public void RemoveDuplicates() {
    String s = "Hello World!";
    int l = s.length();
    char ch;
    String result = "";
    for (int i = 0; i < l; i++) {
        ch = s.charAt(i);
        if (ch != ' ') {
            result = result + ch;
        }
        // Replacing space in all occurrence of the current character
        s = s.replace(ch, ' ');
    }
    System.out.println("After removing duplicate characters : " + result);
}

How to escape the equals sign in properties files

You can look here Can the key in a Java property include a blank character?

for escape equal '=' \u003d

table.whereclause=where id=100

key:[table.whereclause] value:[where id=100]

table.whereclause\u003dwhere id=100

key:[table.whereclause=where] value:[id=100]

table.whereclause\u003dwhere\u0020id\u003d100

key:[table.whereclause=where id=100] value:[]

Combine hover and click functions (jQuery)?

You could also use bind:

$('#myelement').bind('click hover', function yourCommonHandler (e) {
   // Your handler here
});

Store query result in a variable using in PL/pgSQL

As long as you are assigning a single variable, you can also use plain assignment in a plpgsql function:

name := (SELECT t.name from test_table t where t.id = x);

Or use SELECT INTO like @mu already provided.

This works, too:

name := t.name from test_table t where t.id = x;

But better use one of the first two, clearer methods, as @Pavel commented.

I shortened the syntax with a table alias additionally.
Update: I removed my code example and suggest to use IF EXISTS() instead like provided by @Pavel.

Python/BeautifulSoup - how to remove all tags from an element?

With BeautifulStoneSoup gone in bs4, it's even simpler in Python3

from bs4 import BeautifulSoup

soup = BeautifulSoup(html)
text = soup.get_text()
print(text)

ES6 modules implementation, how to load a json file

json-loader doesn't load json file if it's array, in this case you need to make sure it has a key, for example

{
    "items": [
    {
      "url": "https://api.github.com/repos/vmg/redcarpet/issues/598",
      "repository_url": "https://api.github.com/repos/vmg/redcarpet",
      "labels_url": "https://api.github.com/repos/vmg/redcarpet/issues/598/labels{/name}",
      "comments_url": "https://api.github.com/repos/vmg/redcarpet/issues/598/comments",
      "events_url": "https://api.github.com/repos/vmg/redcarpet/issues/598/events",
      "html_url": "https://github.com/vmg/redcarpet/issues/598",
      "id": 199425790,
      "number": 598,
      "title": "Just a heads up (LINE SEPARATOR character issue)",
    },
    ..... other items in array .....
]}

Accessing MVC's model property from Javascript

Wrapping the model property around parens worked for me. You still get the same issue with Visual Studio complaining about the semi-colon, but it works.

var closedStatusId = @(Model.ClosedStatusId);

Multiple simultaneous downloads using Wget?

use xargs to make wget working in multiple file in parallel

#!/bin/bash

mywget()
{
    wget "$1"
}

export -f mywget

# run wget in parallel using 8 thread/connection
xargs -P 8 -n 1 -I {} bash -c "mywget '{}'" < list_urls.txt

Aria2 options, The right way working with file smaller than 20mb

aria2c -k 2M -x 10 -s 10 [url]

-k 2M split file into 2mb chunk

-k or --min-split-size has default value of 20mb, if you not set this option and file under 20mb it will only run in single connection no matter what value of -x or -s

What is the difference between private and protected members of C++ classes?

The reason that MFC favors protected, is because it is a framework. You probably want to subclass the MFC classes and in that case a protected interface is needed to access methods that are not visible to general use of the class.

Server Client send/receive simple text

   public partial class Form1 : Form
    {
        private Thread n_server;
        private Thread n_client;
        private Thread n_send_server;
        private TcpClient client;
        private TcpListener listener;
        private int port = 2222;
        private string IP = " ";
        private Socket socket;
        byte[] bufferReceive = new byte[4096];
        byte[] bufferSend = new byte[4096];
        public Form1()
        {
            InitializeComponent();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        public void Server()
        {
            listener = new TcpListener(IPAddress.Any, port);
            listener.Start();
            try
            {
                socket = listener.AcceptSocket();
                if (socket.Connected)
                {
                    textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Client        : " + socket.RemoteEndPoint.ToString(); });
                }
                while (true)
                {
                    int length = socket.Receive(bufferReceive);
                    if (length > 0)
                    {
                        label2.Invoke((MethodInvoker)delegate { label2.Text = Encoding.Unicode.GetString(bufferReceive); });
                    }
                }
            }
            catch
            {
            }
        }

        public void Client()
        {
            IP = "localhost";
            client = new TcpClient();
            try
            {
                client.Connect(IP, port);
                while (true)
                {
                    NetworkStream nts = client.GetStream();
                    int length;
                    while ((length = nts.Read(bufferReceive, 0, bufferReceive.Length)) != 0)
                    {
                       label3.Invoke((MethodInvoker)delegate { label3.Text = Encoding.Unicode.GetString(bufferReceive); });
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

            if (client.Connected)
            {
                textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Connected..."; });

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            n_server = new Thread(new ThreadStart(Server));
            n_server.IsBackground = true;
            n_server.Start();
            textBox1.Text = "Server up";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            n_client = new Thread(new ThreadStart(Client));
            n_client.IsBackground = true;
            n_client.Start();
        }

        private void send()
        {
            if (socket!=null)
            {
                bufferSend = Encoding.Unicode.GetBytes(textBox2.Text);
                socket.Send(bufferSend);
            }
            else
            {
                if (client.Connected)
                {
                    bufferSend = Encoding.Unicode.GetBytes(textBox3.Text);
                    NetworkStream nts = client.GetStream();
                    if (nts.CanWrite)
                    {
                        nts.Write(bufferSend,0,bufferSend.Length);
                    }

                }
            }
        }



        private void button3_Click(object sender, EventArgs e)
        {
            n_send_server = new Thread(new ThreadStart(send));
            n_send_server.IsBackground = true;
            n_send_server.Start();
        }
    }

scrollbars in JTextArea

I just wanted to say thank you to the topmost first post by a user whom I think is named "coobird". I am new to this stackoverflow.com web site, but I cant believe how useful and helpful this community is...so thanks to all of you for posting some great tips and advise to others. Thats what a community is all about.

Now coobird correctly said:

As Fredrik mentions in his answer, the simple way to achieve this is to place the JTextArea in a JScrollPane. This will allow scrolling of the view area of the JTextArea.

I would like to say:

The above statement is absolutely true. In fact, I had been struggling with this in Eclipse using the WindowBuilder Pro plugin because I could not figure out what combination of widgets would help me achieve that. However, thanks to the post by coobird, I was able to resolve this frustration which took me days.

I would also like to add that I am relatively new to Java even though I have a solid foundation in the principles. The code snippets and advise you guys give here are tremendously useful.

I just want to add one other tid-bit that may help others. I noticed that Coobird put some code as follows (in order to show how to create a Scrollable text area). He wrote:

JTextArea ta = new JTextArea();
JScrollPane sp = new JScrollPane(ta);   

I would like to say thanks to the above code snippet from coobird. I have not tried it directly like that but I am sure it would work just fine. However, it may be useful to some to let you know that when I did this using the WindowBuilder Pro tool, I got something more like the following (which I think is just a slightly longer more "indirect" way for WindowBuilder to achieve what you see in the two lines above. My code kinda reads like this:

JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(23, 40, 394, 191);
frame.getContentPane().add(scrollPane);

JTextArea textArea_1 = new JTextArea();
scrollPane.setViewportView(textArea_1);`

Notice that WindowBuilder basically creates a JScrollPane called scrollpane (in the first three lines of code)...then it sets the viewportview by the following line: scrollPane.setViewportView(textArea_1). So in essence, this line is adding the textArea_1 in my code (which is obviously a JTextArea) to be added to my JScrollPane **which is precisely what coobird was talking about).

Hope this is helpful because I did not want the WindowBuilder Pro developers to get confused thinking that Coobird's advise was not correct or something.

Best Wishes to all and happy coding :)

Python: Finding differences between elements of a list

I would suggest using

v = np.diff(t)

this is simple and easy to read.

But if you want v to have the same length as t then

v = np.diff([t[0]] + t) # for python 3.x

or

v = np.diff(t + [t[-1]])

FYI: this will only work for lists.

for numpy arrays

v = np.diff(np.append(t[0], t))

Tomcat 7: How to set initial heap size correctly?

After spending good time time on this . I found this is the what the setenv.bat must look like . No " characters are accepted in batch file.

set CATALINA_OPTS=-Xms512m -Xmx1024m -XX:PermSize=128m -XX:MaxPermSize=768m

echo hello "%CATALINA_OPTS%"

Deep cloning objects

The best is to implement an extension method like

public static T DeepClone<T>(this T originalObject)
{ /* the cloning code */ }

and then use it anywhere in the solution by

var copy = anyObject.DeepClone();

We can have the following three implementations:

  1. By Serialization (the shortest code)
  2. By Reflection - 5x faster
  3. By Expression Trees - 20x faster

All linked methods are well working and were deeply tested.

Convert Month Number to Month Name Function in SQL

i think this is enough to get month name when u have date.

SELECT DATENAME(month ,GETDATE())

How to replace all spaces in a string

Pure Javascript, without regular expression:

var result = replaceSpacesText.split(" ").join("");

How to calculate moving average without keeping the count and data-total?

Here's yet another answer offering commentary on how Muis, Abdullah Al-Ageel and Flip's answer are all mathematically the same thing except written differently.

Sure, we have José Manuel Ramos's analysis explaining how rounding errors affect each slightly differently, but that's implementation dependent and would change based on how each answer were applied to code.

There is however a rather big difference

It's in Muis's N, Flip's k, and Abdullah Al-Ageel's n. Abdullah Al-Ageel doesn't quite explain what n should be, but N and k differ in that N is "the number of samples where you want to average over" while k is the count of values sampled. (Although I have doubts to whether calling N the number of samples is accurate.)

And here we come to the answer below. It's essentially the same old exponential weighted moving average as the others, so if you were looking for an alternative, stop right here.

Exponential weighted moving average

Initially:

average = 0
counter = 0

For each value:

counter += 1
average = average + (value - average) / min(counter, FACTOR)

The difference is the min(counter, FACTOR) part. This is the same as saying min(Flip's k, Muis's N).

FACTOR is a constant that affects how quickly the average "catches up" to the latest trend. Smaller the number the faster. (At 1 it's no longer an average and just becomes the latest value.)

This answer requires the running counter counter. If problematic, the min(counter, FACTOR) can be replaced with just FACTOR, turning it into Muis's answer. The problem with doing this is the moving average is affected by whatever average is initiallized to. If it was initialized to 0, that zero can take a long time to work its way out of the average.

How it ends up looking

Exponential moving average

I'm getting Key error in python

I fully agree with the Key error comments. You could also use the dictionary's get() method as well to avoid the exceptions. This could also be used to give a default path rather than None as shown below.

>>> d = {"a":1, "b":2}
>>> x = d.get("A",None)
>>> print x
None

Create a Maven project in Eclipse complains "Could not resolve archetype"

Adding the following inside "mirrors" section in the user setting.xml file worked for me.

<mirror>
  <id>ibiblio.org</id>
  <url>http://mirrors.ibiblio.org/maven2</url>
  <mirrorOf>central</mirrorOf>
</mirror>

Convert an int to ASCII character

My way to do this job is:

char to int
char var;
cout<<(int)var-48;
    
int to char
int var;
cout<<(char)(var|48);

And I write these functions for conversions:

int char2int(char *szBroj){
    int counter=0;
    int results=0;
    while(1){
        if(szBroj[counter]=='\0'){
            break;
        }else{
            results*=10;
            results+=(int)szBroj[counter]-48;
            counter++;
        }
    }
    return results;
}

char * int2char(int iNumber){
    int iNumbersCount=0;
    int iTmpNum=iNumber;
    while(iTmpNum){
        iTmpNum/=10;
        iNumbersCount++;
    }
    char *buffer=new char[iNumbersCount+1];
    for(int i=iNumbersCount-1;i>=0;i--){
        buffer[i]=(char)((iNumber%10)|48);
        iNumber/=10;
    }
    buffer[iNumbersCount]='\0';
    return buffer;
}

JavaScript - cannot set property of undefined

The object stored at d[a] has not been set to anything. Thus, d[a] evaluates to undefined. You can't assign a property to undefined :). You need to assign an object or array to d[a]:

d[a] = [];
d[a]["greeting"] = b;

console.debug(d);

Best way to check that element is not present using Selenium WebDriver with java

WebElement element = driver.findElement(locator);
Assert.assertNull(element);

The above assertion will pass if element is not present.

Any way to limit border length?

This is a CSS trick, not a formal solution. I leave the code with the period black because it helps me position the element. Afterward, color your content (color:white) and (margin-top:-5px or so) to make it as though the period is not there.

div.yourdivname:after {
content: ".";
  border-bottom:1px solid grey;
  width:60%;
  display:block;
  margin:0 auto;
}

Dockerfile if else condition with external arguments

It might not look that clean but you can have your Dockerfile (conditional) as follow:

FROM centos:7
ARG arg
RUN if [[ -z "$arg" ]] ; then echo Argument not provided ; else echo Argument is $arg ; fi

and then build the image as:

docker build -t my_docker . --build-arg arg=45

or

docker build -t my_docker .

How to solve Object reference not set to an instance of an object.?

I think you just need;

List<string> list = new List<string>();
list.Add("hai");

There is a difference between

List<string> list; 

and

List<string> list = new List<string>();

When you didn't use new keyword in this case, your list didn't initialized. And when you try to add it hai, obviously you get an error.

Visual Studio: ContextSwitchDeadlock

In Visual Studio 2017, unchecked the ContextSwitchDeadlock option by:

Debug > Windows > Exception Settings

enter image description here

In Exception Setting Windows: Uncheck the ContextSwitchDeadlock option

enter image description here

Open local folder from link

URL Specifies the URL of the document to embed in the iframe. Possible values:

An absolute URL - points to another web site (like src="http://www.example.com/default.htm") A relative URL - points to a file within a web site (like src="default.htm")

C# refresh DataGridView when updating or inserted on another form

DataGridView.Refresh and And DataGridView.Update are methods that are inherited from Control. They have to do with redrawing the control which is why new rows don't appear.

My guess is the data retrieval is on the Form_Load. If you want your Button on Form B to retrieve the latest data from the database then that's what you have to do whatever Form_Load is doing.

A nice way to do that is to separate your data retrieval calls into a separate function and call it from both the From Load and Button Click events.

SQL Server Script to create a new user

If you want to create a generic script you can do it with an Execute statement with a Replace with your username and database name

Declare @userName as varchar(50); 
Declare @defaultDataBaseName as varchar(50);
Declare @LoginCreationScript as varchar(max);
Declare @UserCreationScript as varchar(max);
Declare @TempUserCreationScript as varchar(max);
set @defaultDataBaseName = 'data1';
set @userName = 'domain\userName';
set @LoginCreationScript ='CREATE LOGIN [{userName}]
FROM WINDOWS 
WITH DEFAULT_DATABASE ={dataBaseName}'

set @UserCreationScript ='
USE {dataBaseName}
CREATE User [{userName}] for LOGIN [{userName}];
EXEC sp_addrolemember ''db_datareader'', ''{userName}'';
EXEC sp_addrolemember ''db_datawriter'', ''{userName}'';
Grant Execute on Schema :: dbo TO [{userName}];'
/*Login creation*/
set @LoginCreationScript=Replace(Replace(@LoginCreationScript, '{userName}', @userName), '{dataBaseName}', @defaultDataBaseName)
set @UserCreationScript =Replace(@UserCreationScript, '{userName}', @userName)
Execute(@LoginCreationScript)

/*User creation and role assignment*/
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', @defaultDataBaseName)
Execute(@TempUserCreationScript)
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', 'db2')
Execute(@TempUserCreationScript)
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', 'db3')
Execute(@TempUserCreationScript)

Select DISTINCT individual columns in django?

User order by with that field, and then do distinct.

ProductOrder.objects.order_by('category').values_list('category', flat=True).distinct()

On Duplicate Key Update same as insert

You may want to consider using REPLACE INTO syntax, but be warned, upon duplicate PRIMARY / UNIQUE key, it DELETES the row and INSERTS a new one.

You won't need to re-specify all the fields. However, you should consider the possible performance reduction (depends on your table design).

Caveats:

  • If you have AUTO_INCREMENT primary key, it will be given a new one
  • Indexes will probably need to be updated

Notification not showing in Oreo

I was having the same issue on Oreo and discovered that if you first create your Channel with NotificationManager.IMPORTANCE_NONE, then update it later, the channel will retain the original importance level.

This is backed up by the Google Notification training documentation which states:

After you create a notification channel, you cannot change the notification behaviors—the user has complete control at that point.

Removing and re-installing the app will allow you to reset the channel behaviors.

Best to avoid using IMPORTANCE_NONE unless you want to suppress the notifications for that Channel, ie, to make use of silent notifications.

JavaScript string encryption and decryption?

Simple functions,


function Encrypt(value) 
{
  var result="";
  for(i=0;i<value.length;i++)
  {
    if(i<value.length-1)
    {
        result+=value.charCodeAt(i)+10;
        result+="-";
    }
    else
    {
        result+=value.charCodeAt(i)+10;
    }
  }
  return result;
}
function Decrypt(value)
{
  var result="";
  var array = value.split("-");

  for(i=0;i<array.length;i++)
  {
    result+=String.fromCharCode(array[i]-10);
  }
  return result;
} 

WPF TabItem Header Styling

While searching for a way to round tabs, I found Carlo's answer and it did help but I needed a bit more. Here is what I put together, based on his work. This was done with MS Visual Studio 2015.

The Code:

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MealNinja"
        mc:Ignorable="d"
        Title="Rounded Tabs Example" Height="550" Width="700" WindowStartupLocation="CenterScreen" FontFamily="DokChampa" FontSize="13.333" ResizeMode="CanMinimize" BorderThickness="0">
    <Window.Effect>
        <DropShadowEffect Opacity="0.5"/>
    </Window.Effect>
    <Grid Background="#FF423C3C">
        <TabControl x:Name="tabControl" TabStripPlacement="Left" Margin="6,10,10,10" BorderThickness="3">
            <TabControl.Resources>
                <Style TargetType="{x:Type TabItem}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type TabItem}">
                                <Grid>
                                    <Border Name="Border" Background="#FF6E6C67" Margin="2,2,-8,0" BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="10">
                                        <ContentPresenter x:Name="ContentSite" ContentSource="Header" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="2,2,12,2" RecognizesAccessKey="True"/>
                                    </Border>
                                    <Rectangle Height="100" Width="10" Margin="0,0,-10,0" Stroke="Black" VerticalAlignment="Bottom" HorizontalAlignment="Right" StrokeThickness="0" Fill="#FFD4D0C8"/>
                                </Grid>
                                <ControlTemplate.Triggers>
                                    <Trigger Property="IsSelected" Value="True">
                                        <Setter Property="FontWeight" Value="Bold" />
                                        <Setter TargetName="ContentSite" Property="Width" Value="30" />
                                        <Setter TargetName="Border" Property="Background" Value="#FFD4D0C8" />
                                    </Trigger>
                                    <Trigger Property="IsEnabled" Value="False">
                                        <Setter TargetName="Border" Property="Background" Value="#FF6E6C67" />
                                    </Trigger>
                                    <Trigger Property="IsMouseOver" Value="true">
                                        <Setter Property="FontWeight" Value="Bold" />
                                    </Trigger>
                                </ControlTemplate.Triggers>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="HeaderTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <ContentPresenter Content="{TemplateBinding Content}">
                                    <ContentPresenter.LayoutTransform>
                                        <RotateTransform Angle="270" />
                                    </ContentPresenter.LayoutTransform>
                                </ContentPresenter>
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="Background" Value="#FF6E6C67" />
                    <Setter Property="Height" Value="90" />
                    <Setter Property="Margin" Value="0" />
                    <Setter Property="Padding" Value="0" />
                    <Setter Property="FontFamily" Value="DokChampa" />
                    <Setter Property="FontSize" Value="16" />
                    <Setter Property="VerticalAlignment" Value="Top" />
                    <Setter Property="HorizontalAlignment" Value="Right" />
                    <Setter Property="UseLayoutRounding" Value="False" />
                </Style>
                <Style x:Key="tabGrids">
                    <Setter Property="Grid.Background" Value="#FFE5E5E5" />
                    <Setter Property="Grid.Margin" Value="6,10,10,10" />
                </Style>
            </TabControl.Resources>
            <TabItem Header="Planner">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section 2">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section III">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section 04">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Tools">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
        </TabControl>
    </Grid>
</Window>

Screenshot:

enter image description here

Possible to iterate backwards through a foreach?

If you use a List<T>, you can also use this code:

List<string> list = new List<string>();
list.Add("1");
list.Add("2");
list.Add("3");
list.Reverse();

This is a method that write the list reverse in itself.

Now the foreach:

foreach(string s in list)
{
    Console.WriteLine(s);
}

The output is:

3
2
1

Get content of a DIV using JavaScript

simply you can use jquery plugin to get/set the content of the div.

var divContent = $('#'DIV1).html(); $('#'DIV2).html(divContent );

for this you need to include jquery library.

Watch multiple $scope attributes

Why not simply wrap it in a forEach?

angular.forEach(['a', 'b', 'c'], function (key) {
  scope.$watch(key, function (v) {
    changed();
  });
});

It's about the same overhead as providing a function for the combined value, without actually having to worry about the value composition.

How to use confirm using sweet alert?

I have been having this issue with SweetAlert2 as well. SA2 differs from 1 and puts everything inside the result object. The following above can be accomplished with the following code.

Swal.fire({
    title: 'A cool title',
    icon: 'info',
    confirmButtonText: 'Log in'
  }).then((result) => {
    if (result['isConfirmed']){
      // Put your function here
    }
  })

Everything placed inside the then result will run. Result holds a couple of parameters which can be used to do the trick. Pretty simple technique. Not sure if it works the same on SweetAlert1 but I really wouldn't know why you would choose that one above the newer version.

Where's my JSON data in my incoming Django request?

I had the same problem. I had been posting a complex JSON response, and I couldn't read my data using the request.POST dictionary.

My JSON POST data was:

//JavaScript code:
//Requires json2.js and jQuery.
var response = {data:[{"a":1, "b":2},{"a":2, "b":2}]}
json_response = JSON.stringify(response); // proper serialization method, read 
                                          // http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
$.post('url',json_response);

In this case you need to use method provided by aurealus. Read the request.body and deserialize it with the json stdlib.

#Django code:
import json
def save_data(request):
  if request.method == 'POST':
    json_data = json.loads(request.body) # request.raw_post_data w/ Django < 1.4
    try:
      data = json_data['data']
    except KeyError:
      HttpResponseServerError("Malformed data!")
    HttpResponse("Got json data")

How to retrieve an element from a set without removing it?

I use a utility function I wrote. Its name is somewhat misleading because it kind of implies it might be a random item or something like that.

def anyitem(iterable):
    try:
        return iter(iterable).next()
    except StopIteration:
        return None

Getting index value on razor foreach

You could also use deconstruction and tuples and try something like this:

@foreach (var (index, member) in @Model.Members.Select((member, i) => (i, member)))
{
  <div>@index - @member.anyProperty</div>

  if(index > 0 && index % 4 == 0) { // display clear div every 4 elements
      @: <div class="clear"></div>
  }
}

For more info you can have a look at this link

Download file of any type in Asp.Net MVC using FileResult?

if (string.IsNullOrWhiteSpace(fileName)) return Content("filename not present");

        var path = Path.Combine(your path, your filename);

        var stream = new FileStream(path, FileMode.Open);

        return File(stream, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);

Finding the max value of an attribute in an array of objects

Comparison of three ONELINERS which handle minus numbers case (input in a array):

var maxA = a.reduce((a,b)=>a.y>b.y?a:b).y; // 30 chars time complexity:  O(n)

var maxB = a.sort((a,b)=>b.y-a.y)[0].y;    // 27 chars time complexity:  O(nlogn)
           
var maxC = Math.max(...a.map(o=>o.y));     // 26 chars time complexity: >O(2n)

editable example here. Ideas from: maxA, maxB and maxC (side effect of maxB is that array a is changed because sort is in-place).

_x000D_
_x000D_
var a = [
  {"x":"8/11/2009","y":0.026572007},{"x":"8/12/2009","y":0.025057454},    
  {"x":"8/14/2009","y":0.031004457},{"x":"8/13/2009","y":0.024530916}
]

var maxA = a.reduce((a,b)=>a.y>b.y?a:b).y;
var maxC = Math.max(...a.map(o=>o.y));
var maxB = a.sort((a,b)=>b.y-a.y)[0].y;

document.body.innerHTML=`<pre>maxA: ${maxA}\nmaxB: ${maxB}\nmaxC: ${maxC}</pre>`;
_x000D_
_x000D_
_x000D_

For bigger arrays the Math.max... will throw exception: Maximum call stack size exceeded (Chrome 76.0.3809, Safari 12.1.2, date 2019-09-13)

_x000D_
_x000D_
let a = Array(400*400).fill({"x": "8/11/2009", "y": 0.026572007 }); 

// Exception: Maximum call stack size exceeded

try {
  let max1= Math.max.apply(Math, a.map(o => o.y));
} catch(e) { console.error('Math.max.apply:', e.message) }

try {
  let max2= Math.max(...a.map(o=>o.y));
} catch(e) { console.error('Math.max-map:', e.message) }
_x000D_
_x000D_
_x000D_

Benchmark for the 4 element array

Quantile-Quantile Plot using SciPy

I came up with this. Maybe you can improve it. Especially the method of generating the quantiles of the distribution seems cumbersome to me.

You could replace np.random.normal with any other distribution from np.random to compare data against other distributions.

#!/bin/python

import numpy as np

measurements = np.random.normal(loc = 20, scale = 5, size=100000)

def qq_plot(data, sample_size):
    qq = np.ones([sample_size, 2])
    np.random.shuffle(data)
    qq[:, 0] = np.sort(data[0:sample_size])
    qq[:, 1] = np.sort(np.random.normal(size = sample_size))
    return qq

print qq_plot(measurements, 1000)

:last-child not working as expected?

The last-child selector is used to select the last child element of a parent. It cannot be used to select the last child element with a specific class under a given parent element.

The other part of the compound selector (which is attached before the :last-child) specifies extra conditions which the last child element must satisfy in-order for it to be selected. In the below snippet, you would see how the selected elements differ depending on the rest of the compound selector.

_x000D_
_x000D_
.parent :last-child{ /* this will select all elements which are last child of .parent */_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.parent div:last-child{ /* this will select the last child of .parent only if it is a div*/_x000D_
  background: crimson;_x000D_
}_x000D_
_x000D_
.parent div.child-2:last-child{ /* this will select the last child of .parent only if it is a div and has the class child-2*/_x000D_
  color: beige;_x000D_
}
_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child-2'>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <p>Child w/o class</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_


To answer your question, the below would style the last child li element with background color as red.

li:last-child{
    background-color: red;
}

But the following selector would not work for your markup because the last-child does not have the class='complete' even though it is an li.

li.complete:last-child{
    background-color: green;
}

It would have worked if (and only if) the last li in your markup also had class='complete'.


To address your query in the comments:

@Harry I find it rather odd that: .complete:last-of-type does not work, yet .complete:first-of-type does work, regardless of it's position it's parents element. Thanks for your help.

The selector .complete:first-of-type works in the fiddle because it (that is, the element with class='complete') is still the first element of type li within the parent. Try to add <li>0</li> as the first element under the ul and you will find that first-of-type also flops. This is because the first-of-type and last-of-type selectors select the first/last element of each type under the parent.

Refer to the answer posted by BoltClock, in this thread for more details about how the selector works. That is as comprehensive as it gets :)

What is a good Hash Function?

There are two major purposes of hashing functions:

  • to disperse data points uniformly into n bits.
  • to securely identify the input data.

It's impossible to recommend a hash without knowing what you're using it for.

If you're just making a hash table in a program, then you don't need to worry about how reversible or hackable the algorithm is... SHA-1 or AES is completely unnecessary for this, you'd be better off using a variation of FNV. FNV achieves better dispersion (and thus fewer collisions) than a simple prime mod like you mentioned, and it's more adaptable to varying input sizes.

If you're using the hashes to hide and authenticate public information (such as hashing a password, or a document), then you should use one of the major hashing algorithms vetted by public scrutiny. The Hash Function Lounge is a good place to start.

How to insert a newline in front of a pattern?

echo one,two,three | sed 's/,/\
/g'

How do I display the value of a Django form field in a template?

If you've populated the form with an instance and not with POST data (as the suggested answer requires), you can access the data using {{ form.instance.my_field_name }}.

How to re-enable right click so that I can inspect HTML elements in Chrome?

The easiest way I found is to open the webpage in Read mode (browser that supports read mode like Safari, Firefox etc) and then copy as usual

Google Chrome forcing download of "f.txt" file

Seems related to https://groups.google.com/forum/#!msg/google-caja-discuss/ite6K5c8mqs/Ayqw72XJ9G8J.

The so-called "Rosetta Flash" vulnerability is that allowing arbitrary yet identifier-like text at the beginning of a JSONP response is sufficient for it to be interpreted as a Flash file executing in that origin. See for more information: http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/

JSONP responses from the proxy servlet now: * are prefixed with "/**/", which still allows them to execute as JSONP but removes requester control over the first bytes of the response. * have the response header Content-Disposition: attachment.

Share data between AngularJS controllers

There are many ways you can share the data between controllers

  1. using services
  2. using $state.go services
  3. using stateparams
  4. using rootscope

Explanation of each method:

  1. I am not going to explain as its already explained by someone

  2. using $state.go

      $state.go('book.name', {Name: 'XYZ'}); 
    
      // then get parameter out of URL
      $state.params.Name;
    
  3. $stateparam works in a similar way to $state.go, you pass it as object from sender controller and collect in receiver controller using stateparam

  4. using $rootscope

    (a) sending data from child to parent controller

      $scope.Save(Obj,function(data) {
          $scope.$emit('savedata',data); 
          //pass the data as the second parameter
      });
    
      $scope.$on('savedata',function(event,data) {
          //receive the data as second parameter
      }); 
    

    (b) sending data from parent to child controller

      $scope.SaveDB(Obj,function(data){
          $scope.$broadcast('savedata',data);
      });
    
      $scope.SaveDB(Obj,function(data){`enter code here`
          $rootScope.$broadcast('saveCallback',data);
      });
    

How can I add a string to the end of each line in Vim?

...and to prepend (add the beginning of) each line with *,

%s/^/*/g

Android Emulator Error Message: "PANIC: Missing emulator engine program for 'x86' CPUS."

In my case by doing which emulator it returned $ANDROID_HOME/tools/emulator but it should be $ANDROID_HOME/emulator/emulator

So I just added $ANDROID_HOME/emulator before $ANDROID_HOME/tools in the PATH variable and it works fine now

How to delete Certain Characters in a excel 2010 cell

If [John Smith] is in cell A1, then use this formula to do what you want:

=SUBSTITUTE(SUBSTITUTE(A1, "[", ""), "]", "")

The inner SUBSTITUTE replaces all instances of "[" with "" and returns a new string, then the other SUBSTITUTE replaces all instances of "]" with "" and returns the final result.

Cause of a process being a deadlock victim

Q1:Could the time it takes for a transaction to execute make the associated process more likely to be flagged as a deadlock victim.

No. The SELECT is the victim because it had only read data, therefore the transaction has a lower cost associated with it so is chosen as the victim:

By default, the Database Engine chooses as the deadlock victim the session running the transaction that is least expensive to roll back. Alternatively, a user can specify the priority of sessions in a deadlock situation using the SET DEADLOCK_PRIORITY statement. DEADLOCK_PRIORITY can be set to LOW, NORMAL, or HIGH, or alternatively can be set to any integer value in the range (-10 to 10).

Q2. If I execute the select with a NOLOCK hint, will this remove the problem?

No. For several reasons:

Q3. I suspect that a datetime field that is checked as part of the WHERE clause in the select statement is causing the slow lookup time. Can I create an index based on this field? Is it advisable?

Probably. The cause of the deadlock is almost very likely to be a poorly indexed database.10 minutes queries are acceptable in such narrow conditions, that I'm 100% certain in your case is not acceptable.

With 99% confidence I declare that your deadlock is cased by a large table scan conflicting with updates. Start by capturing the deadlock graph to analyze the cause. You will very likely have to optimize the schema of your database. Before you do any modification, read this topic Designing Indexes and the sub-articles.

Programmatically get the version number of a DLL

var versionAttrib = new AssemblyName(Assembly.GetExecutingAssembly().FullName);

how to do "press enter to exit" in batch

Oops... Misunderstood the question...

Pause is the way to go

Old answer:

you can pipe commands into your patch file...

try

build.bat < responsefile.txt

What's the "average" requests per second for a production web application?

When I go to the control panel of my webhost, open up phpMyAdmin, and click on "Show MySQL runtime information", I get:

This MySQL server has been running for 53 days, 15 hours, 28 minutes and 53 seconds. It started up on Oct 24, 2008 at 04:03 AM.

Query statistics: Since its startup, 3,444,378,344 queries have been sent to the server.

Total 3,444 M
per hour 2.68 M
per minute 44.59 k
per second 743.13

That's an average of 743 mySQL queries every single second for the past 53 days!

I don't know about you, but to me that's fast! Very fast!!

How can I get an int from stdio in C?

I'm not fully sure that this is what you're looking for, but if your question is how to read an integer using <stdio.h>, then the proper syntax is

int myInt;
scanf("%d", &myInt);

You'll need to do a lot of error-handling to ensure that this works correctly, of course, but this should be a good start. In particular, you'll need to handle the cases where

  1. The stdin file is closed or broken, so you get nothing at all.
  2. The user enters something invalid.

To check for this, you can capture the return code from scanf like this:

int result = scanf("%d", &myInt);

If stdin encounters an error while reading, result will be EOF, and you can check for errors like this:

int myInt;
int result = scanf("%d", &myInt);

if (result == EOF) {
    /* ... you're not going to get any input ... */
}

If, on the other hand, the user enters something invalid, like a garbage text string, then you need to read characters out of stdin until you consume all the offending input. You can do this as follows, using the fact that scanf returns 0 if nothing was read:

int myInt;
int result = scanf("%d", &myInt);

if (result == EOF) {
    /* ... you're not going to get any input ... */
}
if (result == 0) {
    while (fgetc(stdin) != '\n') // Read until a newline is found
        ;
}

Hope this helps!

EDIT: In response to the more detailed question, here's a more appropriate answer. :-)

The problem with this code is that when you write

printf("got the number: %d", scanf("%d", &x));

This is printing the return code from scanf, which is EOF on a stream error, 0 if nothing was read, and 1 otherwise. This means that, in particular, if you enter an integer, this will always print 1 because you're printing the status code from scanf, not the number you read.

To fix this, change this to

int x;
scanf("%d", &x);
/* ... error checking as above ... */
printf("got the number: %d", x);

Hope this helps!

What is the best method to merge two PHP objects?

To merge any number of raw objects

function merge_obj(){
    foreach(func_get_args() as $a){
        $objects[]=(array)$a;
    }
    return (object)call_user_func_array('array_merge', $objects);
}

how to get the cookies from a php curl into a variable

This does it without regexps, but requires the PECL HTTP extension.

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
curl_close($ch);

$headers = http_parse_headers($result);
$cookobjs = Array();
foreach($headers AS $k => $v){
    if (strtolower($k)=="set-cookie"){
        foreach($v AS $k2 => $v2){
            $cookobjs[] = http_parse_cookie($v2);
        }
    }
}

$cookies = Array();
foreach($cookobjs AS $row){
    $cookies[] = $row->cookies;
}

$tmp = Array();
// sort k=>v format
foreach($cookies AS $v){
    foreach ($v  AS $k1 => $v1){
        $tmp[$k1]=$v1;
    }
}

$cookies = $tmp;
print_r($cookies);

Align image in center and middle within div

This can also be done using the Flexbox layout:

STATIC SIZE

_x000D_
_x000D_
.parent {_x000D_
    display: flex;_x000D_
    height: 300px; /* Or whatever */_x000D_
    background-color: #000;_x000D_
}_x000D_
_x000D_
.child {_x000D_
    width: 100px;  /* Or whatever */_x000D_
    height: 100px; /* Or whatever */_x000D_
    margin: auto;  /* Magic! */_x000D_
}
_x000D_
<div class="parent">_x000D_
    <img class="child" src="https://i.vimeocdn.com/portrait/58832_300x300"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

DYNAMIC SIZE

_x000D_
_x000D_
html, body {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  display: flex;_x000D_
  background-color: #999;_x000D_
}_x000D_
_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
.parent {_x000D_
  margin: auto;_x000D_
  background-color: #000;_x000D_
  display: flex;_x000D_
  height: 80%;_x000D_
  width: 80%;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  margin: auto;  /* Magic! */_x000D_
  max-width: 100%;_x000D_
  max-height: 100%;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <img class="child" src="https://i.vimeocdn.com/portrait/58832_300x300"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

I found the example in this article, which does a great job explaining the how to use layout.

Get full query string in C# ASP.NET

Request.QueryString returns you a collection of Key/Value pairs representing the Query String. Not a String. Don't think that would cause a Object Reference error though. The reason your getting that is because as Mauro pointed out in the comments. It's QueryString and not Querystring.

Try:

Request.QueryString.ToString();

or

<%                                 
    string URL = Request.Url.AbsoluteUri 
    System.Net.WebClient wc = new System.Net.WebClient();
    string data = wc.DownloadString(URL);
    Response.Output.Write(data);
%>

Same as your code but Request.Url.AbsoluteUri will return the full path, including the query string.

What is better, adjacency lists or adjacency matrices for graph problems in C++?

Okay, I've compiled the Time and Space complexities of basic operations on graphs.
The image below should be self-explanatory.
Notice how Adjacency Matrix is preferable when we expect the graph to be dense, and how Adjacency List is preferable when we expect the graph to be sparse.
I've made some assumptions. Ask me if a complexity (Time or Space) needs clarification. (For example, For a sparse graph, I've taken En to be a small constant, as I've assumed that addition of a new vertex will add only a few edges, because we expect the graph to remain sparse even after adding that vertex.)

Please tell me if there are any mistakes.

enter image description here

Cross Domain Form POSTing

It is possible to build an arbitrary GET or POST request and send it to any server accessible to a victims browser. This includes devices on your local network, such as Printers and Routers.

There are many ways of building a CSRF exploit. A simple POST based CSRF attack can be sent using .submit() method. More complex attacks, such as cross-site file upload CSRF attacks will exploit CORS use of the xhr.withCredentals behavior.

CSRF does not violate the Same-Origin Policy For JavaScript because the SOP is concerned with JavaScript reading the server's response to a clients request. CSRF attacks don't care about the response, they care about a side-effect, or state change produced by the request, such as adding an administrative user or executing arbitrary code on the server.

Make sure your requests are protected using one of the methods described in the OWASP CSRF Prevention Cheat Sheet. For more information about CSRF consult the OWASP page on CSRF.

Global variables in c#.net

You can create a base class in your application that inherits from System.Web.UI.Page. Let all your pages inherit from the newly created base class. Add a property or a variable to your base class with propected access modifier, so that it will be accessed from all your pages in the application.

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

If you are not worried about an unbounded queue of Callable/Runnable tasks, you can use one of them. As suggested by bruno, I too prefer newFixedThreadPool to newCachedThreadPool over these two.

But ThreadPoolExecutor provides more flexible features compared to either newFixedThreadPool or newCachedThreadPool

ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, 
TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
RejectedExecutionHandler handler)

Advantages:

  1. You have full control of BlockingQueue size. It's not un-bounded, unlike the earlier two options. I won't get an out of memory error due to a huge pile-up of pending Callable/Runnable tasks when there is unexpected turbulence in the system.

  2. You can implement custom Rejection handling policy OR use one of the policies:

    1. In the default ThreadPoolExecutor.AbortPolicy, the handler throws a runtime RejectedExecutionException upon rejection.

    2. In ThreadPoolExecutor.CallerRunsPolicy, the thread that invokes execute itself runs the task. This provides a simple feedback control mechanism that will slow down the rate that new tasks are submitted.

    3. In ThreadPoolExecutor.DiscardPolicy, a task that cannot be executed is simply dropped.

    4. In ThreadPoolExecutor.DiscardOldestPolicy, if the executor is not shut down, the task at the head of the work queue is dropped, and then execution is retried (which can fail again, causing this to be repeated.)

  3. You can implement a custom Thread factory for the below use cases:

    1. To set a more descriptive thread name
    2. To set thread daemon status
    3. To set thread priority

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

If you just want to suppress warnings from a function, you can add an @ sign in front:

<?php @function_that_i_dont_want_to_see_errors_from(parameters); ?>

Excel VBA Run Time Error '424' object required

The first code line, Option Explicit means (in simple terms) that all of your variables have to be explicitly declared by Dim statements. They can be any type, including object, integer, string, or even a variant.

This line: Dim envFrmwrkPath As Range is declaring the variable envFrmwrkPath of type Range. This means that you can only set it to a range.

This line: Set envFrmwrkPath = ActiveSheet.Range("D6").Value is attempting to set the Range type variable to a specific Value that is in cell D6. This could be a integer or a string for example (depends on what you have in that cell) but it's not a range.

I'm assuming you want the value stored in a variable. Try something like this:

Dim MyVariableName As Integer
MyVariableName = ActiveSheet.Range("D6").Value

This assumes you have a number (like 5) in cell D6. Now your variable will have the value.

For simplicity sake of learning, you can remove or comment out the Option Explicit line and VBA will try to determine the type of variables at run time.


Try this to get through this part of your code

Dim envFrmwrkPath As String
Dim ApplicationName As String
Dim TestIterationName As String

Enable PHP Apache2

If anyone gets

ERROR: Module phpX.X does not exist!

just install the module for your current php version:

apt-get install libapache2-mod-phpX.X

How to change a string into uppercase

To get upper case version of a string you can use str.upper:

s = 'sdsd'
s.upper()
#=> 'SDSD'

On the other hand string.ascii_uppercase is a string containing all ASCII letters in upper case:

import string
string.ascii_uppercase
#=> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

Compare string with all values in list

I assume you mean list and not array? There is such a thing as an array in Python, but more often than not you want a list instead of an array.

The way to check if a list contains a value is to use in:

if paid[j] in d:
    # ...

What is a Windows Handle?

It's an abstract reference value to a resource, often memory or an open file, or a pipe.

Properly, in Windows, (and generally in computing) a handle is an abstraction which hides a real memory address from the API user, allowing the system to reorganize physical memory transparently to the program. Resolving a handle into a pointer locks the memory, and releasing the handle invalidates the pointer. In this case think of it as an index into a table of pointers... you use the index for the system API calls, and the system can change the pointer in the table at will.

Alternatively a real pointer may be given as the handle when the API writer intends that the user of the API be insulated from the specifics of what the address returned points to; in this case it must be considered that what the handle points to may change at any time (from API version to version or even from call to call of the API that returns the handle) - the handle should therefore be treated as simply an opaque value meaningful only to the API.

I should add that in any modern operating system, even the so-called "real pointers" are still opaque handles into the virtual memory space of the process, which enables the O/S to manage and rearrange memory without invalidating the pointers within the process.

Short description of the scoping rules?

The scoping rules for Python 2.x have been outlined already in other answers. The only thing I would add is that in Python 3.0, there is also the concept of a non-local scope (indicated by the 'nonlocal' keyword). This allows you to access outer scopes directly, and opens up the ability to do some neat tricks, including lexical closures (without ugly hacks involving mutable objects).

EDIT: Here's the PEP with more information on this.

Google Maps shows "For development purposes only"

Watermarked with ?“for development purposes only” is returned when any of the following is true:

  1. The request is missing an API key.
  2. Billing has not been enabled on your account.
  3. The provided billing method is invalid (for example an expired credit card).
  4. A self-imposed daily limit has been exceeded.

Configuring user and password with Git Bash

Try ssh-agent for installing the SSH key for use with Git. It should auto login after use of a passphrase.

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

I was facing this issue because of Firebase Crashlytics. In Targets -> Build Phases -> Run Script

I had Firebase Crashlytics written like

${PODS_ROOT}/FirebaseCrashlytics/run

I changed that and put it in double quotes

"${PODS_ROOT}/FirebaseCrashlytics/run"

Binding a Button's visibility to a bool value in ViewModel

There's a third way that doesn't require a converter or a change to your view model: use a style:

<Style TargetType="Button">
   <Setter Property="Visibility" Value="Collapsed"/>
   <Style.Triggers>
      <DataTrigger Binding="{Binding IsVisible}" Value="True">
         <Setter Property="Visibility" Value="Visible"/>
      </DataTrigger>
   </Style.Triggers>
</Style>

I tend to prefer this technique because I use it in a lot of cases where what I'm binding to is not boolean - e.g. displaying an element only if its DataContext is not null, or implementing multi-state displays where different layouts appear based on the setting of an enum in the view model.

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

jQuery or JavaScript auto click

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

did the trick.

How to maximize a plt.show() window using Python

This makes the window take up the full screen for me, under Ubuntu 12.04 with the TkAgg backend:

    mng = plt.get_current_fig_manager()
    mng.resize(*mng.window.maxsize())

How to detect when a youtube video finishes playing?

What you may want to do is include a script on all pages that does the following ... 1. find the youtube-iframe : searching for it by width and height by title or by finding www.youtube.com in its source. You can do that by ... - looping through the window.frames by a for-in loop and then filter out by the properties

  1. inject jscript in the iframe of the current page adding the onYoutubePlayerReady must-include-function http://shazwazza.com/post/Injecting-JavaScript-into-other-frames.aspx

  2. Add the event listeners etc..

Hope this helps

Data binding to SelectedItem in a WPF Treeview

You might also be able to use TreeViewItem.IsSelected property

Maven – Always download sources and javadocs

Open your settings.xml file ~/.m2/settings.xml (create it if it doesn't exist). Add a section with the properties added. Then make sure the activeProfiles includes the new profile.

<settings>

   <!-- ... other settings here ... -->

    <profiles>
        <profile>
            <id>downloadSources</id>
            <properties>
                <downloadSources>true</downloadSources>
                <downloadJavadocs>true</downloadJavadocs>
            </properties>
        </profile>
    </profiles>

    <activeProfiles>
        <activeProfile>downloadSources</activeProfile>
    </activeProfiles>
</settings>

Makefile If-Then Else and Loops

Here's an example if:

ifeq ($(strip $(OS)),Linux)
        PYTHON = /usr/bin/python
        FIND = /usr/bin/find
endif

Note that this comes with a word of warning that different versions of Make have slightly different syntax, none of which seems to be documented very well.

Singletons vs. Application Context in Android?

Application is not the same as the Singleton.The reasons are:

  1. Application's method(such as onCreate) is called in the ui thread;
  2. singleton's method can be called in any thread;
  3. In the method "onCreate" of Application,you can instantiate Handler;
  4. If the singleton is executed in none-ui thread,you could not instantiate Handler;
  5. Application has the ability to manage the life cycle of the activities in the app.It has the method "registerActivityLifecycleCallbacks".But the singletons has not the ability.

How exactly does binary code get converted into letters?

http://www.roubaixinteractive.com/PlayGround/Binary_Conversion/The_Characters.asp it just looks here... (not HERE but it has a table).

There are 8 bits in a byte. One byte can be one symbol. One bit is either on or off.

ReportViewer Client Print Control "Unable to load client print control"?

Found a Fix:

  1. First ensure that printing is working from Report Manager (open a report in Report Manager and print from there).

  2. If it works go to Step 3, if you received the same error you need to install the following patches on the Report Server.

  3. Download and install the following update:

Selecting multiple columns/fields in MySQL subquery

Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..

FROM TABLE A

The other way is

FROM (SELECT col as name1, col2 as name2 FROM ...) B

Notice that the select clause and the parentheses around it are a table, a virtual table.

So, using your second code example (I am guessing at the columns you are hoping to retrieve here):

SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)

Notice that your real table attribute is the first table in this join, and that this virtual table I've called b is the second table.

This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.

SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
 SELECT count(*) AS langcount,  at.attribute
 FROM attributeTranslation at
 GROUP BY at.attribute
) c ON (a.id = c.attribute)

See how that goes? You've generated a virtual table c containing two columns, joined it to the other two, used one of the columns for the ON clause, and returned the other as a column in your result set.

How to set textColor of UILabel in Swift

solution for swift 3 -

let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
titleLabel.text = "change to red color"
titleLabel.textAlignment = .center
titleLabel.textColor = UIColor.red

Importing PNG files into Numpy?

This can also be done with the Image class of the PIL library:

from PIL import Image
import numpy as np

im_frame = Image.open(path_to_file + 'file.png')
np_frame = np.array(im_frame.getdata())

Note: The .getdata() might not be needed - np.array(im_frame) should also work

PHP reindex array?

This might not be the simplest answer as compared to using array_values().

Try this

$array = array( 0 => 'string1', 2 => 'string2', 4 => 'string3', 5 => 'string4');
$arrays =$array;
print_r($array);
$array=array();
$i=0;
    foreach($arrays as $k => $item)
    {
    $array[$i]=$item;
        unset($arrays[$k]);
        $i++;

    }

print_r($array);

Demo

How to convert numbers to words without using num2word library?

You can make this much simpler by using one dictionary and a try/except clause like this:

num2words = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', \
             6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', \
            11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', \
            15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', \
            19: 'Nineteen', 20: 'Twenty', 30: 'Thirty', 40: 'Forty', \
            50: 'Fifty', 60: 'Sixty', 70: 'Seventy', 80: 'Eighty', \
            90: 'Ninety', 0: 'Zero'}

>>> def n2w(n):
        try:
            print num2words[n]
        except KeyError:
            try:
                print num2words[n-n%10] + num2words[n%10].lower()
            except KeyError:
                print 'Number out of range'

>>> n2w(0)
Zero
>>> n2w(13)
Thirteen        
>>> n2w(91)
Ninetyone
>>> n2w(21)
Twentyone
>>> n2w(33)
Thirtythree

Unable to use Intellij with a generated sources folder

With gradle, the project settings will be cleared whenever you refresh the gradle settings. Instead you need to add the following lines (or similar) in your build.gradle, I'm using kotlin so:

sourceSets {
    main {
        java {
            srcDir "${buildDir.absolutePath}/generated/source/kapt/main"
        }
    }
}

How to tune Tomcat 5.5 JVM Memory settings without using the configuration program

Not sure that it will be applicable solution for you. But the only way for monitoring tomcat memory settings as well as number of connections etc. that actually works for us is Lambda Probe.

It shows most of informations that we need for Tomcat tunning. We tested it with Tomcat 5.5 and 6.0 and it works fine despite beta status and date of last update in end of 2006.

Deserializing JSON data to C# using JSON.NET

You can try checking some of the class generators online for further information. However, I believe some of the answers have been useful. Here's my approach that may be useful.

The following code was made with a dynamic method in mind.

dynObj = (JArray) JsonConvert.DeserializeObject(nvm);

foreach(JObject item in dynObj) {
 foreach(JObject trend in item["trends"]) {
  Console.WriteLine("{0}-{1}-{2}", trend["query"], trend["name"], trend["url"]);
 }
}

This code basically allows you to access members contained in the Json string. Just a different way without the need of the classes. query, trend and url are the objects contained in the Json string.

You can also use this website. Don't trust the classes a 100% but you get the idea.

log4j: Log output of a specific class to a specific appender

Here's an answer regarding the XML configuration, note that if you don't give the file appender a ConversionPattern it will create 0 byte file and not write anything:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <appender name="bdfile" class="org.apache.log4j.RollingFileAppender">
        <param name="append" value="false"/>
        <param name="maxFileSize" value="1GB"/>
        <param name="maxBackupIndex" value="2"/>
        <param name="file" value="/tmp/bd.log"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <logger name="com.example.mypackage" additivity="false">
        <level value="debug"/>
        <appender-ref ref="bdfile"/>
    </logger>

    <root>
        <priority value="info"/>
        <appender-ref ref="bdfile"/>
        <appender-ref ref="console"/>
    </root>

</log4j:configuration>

What is the difference between Document style and RPC style communication?

I think what you are asking is the difference between RPC Literal, Document Literal and Document Wrapped SOAP web services.

Note that Document web services are delineated into literal and wrapped as well and they are different - one of the primary difference is that the latter is BP 1.1 compliant and the former is not.

Also, in Document Literal the operation to be invoked is not specified in terms of its name whereas in Wrapped, it is. This, I think, is a significant difference in terms of easily figuring out the operation name that the request is for.

In terms of RPC literal versus Document Wrapped, the Document Wrapped request can be easily vetted / validated against the schema in the WSDL - one big advantage.

I would suggest using Document Wrapped as the web service type of choice due to its advantages.

SOAP on HTTP is the SOAP protocol bound to HTTP as the carrier. SOAP could be over SMTP or XXX as well. SOAP provides a way of interaction between entities (client and servers, for example) and both entities can marshal operation arguments / return values as per the semantics of the protocol.

If you were using XML over HTTP (and you can), it is simply understood to be XML payload on HTTP request / response. You would need to provide the framework to marshal / unmarshal, error handling and so on.

A detailed tutorial with examples of WSDL and code with emphasis on Java: SOAP and JAX-WS, RPC versus Document Web Services

Python dictionary replace values

If you iterate over a dictionary you get the keys, so assuming your dictionary is in a variable called data and you have some function find_definition() which gets the definition, you can do something like the following:

for word in data:
    data[word] = find_definition(word)

How to display my application's errors in JSF?

Found this while Googling. The second post makes a point about the different phases of JSF, which might be causing your error message to become lost. Also, try null in place of "newPassword" because you do not have any object with the id newPassword.

How to draw a checkmark / tick using CSS?

Try this // html example

<span>&#10003;</span>

// css example

span {
  content: "\2713";
}

How do I use a custom deleter with a std::unique_ptr member?

You just need to create a deleter class:

struct BarDeleter {
  void operator()(Bar* b) { destroy(b); }
};

and provide it as the template argument of unique_ptr. You'll still have to initialize the unique_ptr in your constructors:

class Foo {
  public:
    Foo() : bar(create()), ... { ... }

  private:
    std::unique_ptr<Bar, BarDeleter> bar;
    ...
};

As far as I know, all the popular c++ libraries implement this correctly; since BarDeleter doesn't actually have any state, it does not need to occupy any space in the unique_ptr.

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

The supplied link has a very simply example of the n + 1 problem. If you apply it to Hibernate it's basically talking about the same thing. When you query for an object, the entity is loaded but any associations (unless configured otherwise) will be lazy loaded. Hence one query for the root objects and another query to load the associations for each of these. 100 objects returned means one initial query and then 100 additional queries to get the association for each, n + 1.

http://pramatr.com/2009/02/05/sql-n-1-selects-explained/

:first-child not working as expected

You could wrap your h1 tags in another div and then the first one would be the first-child. That div doesn't even need styles. It's just a way to segregate those children.

<div class="h1-holder">
    <h1>Title 1</h1>
    <h1>Title 2</h1>
</div>

MySQL IF ELSEIF in select query

For your question :

SELECT id, 
   IF(qty_1 <= '23', price,
   IF(('23' > qty_1 && qty_2 <= '23'), price_2,
   IF(('23' > qty_2 && qty_3 <= '23'), price_3,
   IF(('23' > qty_2 && qty_3<='23'), price_3,
   IF('23' > qty_3, price_4, 1))))) as total 
FROM product;

You can use the if - else control structure or the IF function in MySQL.

Reference:
http://easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/

How to get a value from a cell of a dataframe?

Converting it to integer worked for me:

int(sub_df.iloc[0])

New self vs. new static

If the method of this code is not static, you can get a work-around in 5.2 by using get_class($this).

class A {
    public function create1() {
        $class = get_class($this);
        return new $class();
    }
    public function create2() {
        return new static();
    }
}

class B extends A {

}

$b = new B();
var_dump(get_class($b->create1()), get_class($b->create2()));

The results:

string(1) "B"
string(1) "B"

Delete all files of specific type (extension) recursively down a directory using a batch file

I don't have enough reputation to add comment, so I posted this as an answer. But for original issue with this command:

@echo off
FOR %%p IN (C:\Users\vexe\Pictures\sample) DO FOR %%t IN (*.jpg) DO del /s %%p\%%t

The first For is lacking recursive syntax, it should be:

@echo off
FOR /R %%p IN (C:\Users\vexe\Pictures\sample) DO FOR %%t IN (*.jpg) DO del /s %%p\%%t

You can just do:

FOR %%p IN (C:\Users\0300092544\Downloads\Ces_Sce_600) DO @ECHO %%p

to show the actual output.

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

On the xkcd note, the Bobby Tables website has good advice for avoiding the improper interpretation of user data (in this case, the string "Null") in SQL queries in various languages, including ColdFusion.

It is not clear from the question that this is the source of the problem, and given the solution noted in a comment to the first answer (embedding the parameters in a structure) it seems likely that it was something else.

Retrofit 2 - URL Query Parameter

 public interface IService { 

  String BASE_URL = "https://api.demo.com/";

  @GET("Login") //i.e https://api.demo.com/Search? 
  Call<Products> getUserDetails(@Query("email") String emailID, @Query("password") String password)

} 

It will be called this way. Considering you did the rest of the code already.

Call<Results> call = service.getUserDetails("[email protected]", "Password@123");

For example when a query is returned, it will look like this.

https://api.demo.com/[email protected]&password=Password@123

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

I got this error message from using an oracle database in a docker despite the fact i had publish port to host option "-p 1521:1521". I was using jdbc url that was using ip address 127.0.0.1, i changed it to the host machine real ip address and everything worked then.

Remove a marker from a GoogleMap

if marker exist remove last marker. if marker does not exist create current marker

Marker currentMarker = null;
if (currentMarker!=null) {
    currentMarker.remove();
    currentMarker=null;
}

if (currentMarker==null) {
    currentMarker = mMap.addMarker(new MarkerOptions().position(arg0).
    icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
}

Switch statement fallthrough in C#?

They changed the switch statement (from C/Java/C++) behavior for c#. I guess the reasoning was that people forgot about the fall through and errors were caused. One book I read said to use goto to simulate, but this doesn't sound like a good solution to me.

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

Per the developers, this error is not an actual failure, but rather "misleading error reports". This bug is fixed in version 40, which is available on the canary and dev channels as of 25 Oct.

Patch

How to specify a port to run a create-react-app based project?

just run below command

PORT=3001 npm start

SQLite - getting number of rows in a database

In SQL, NULL = NULL is false, you usually have to use IS NULL:

SELECT CASE WHEN MAX(id) IS NULL THEN 0 ELSE (MAX(id) + 1) END FROM words

But, if you want the number of rows, you should just use count(id) since your solution will give 10 if your rows are (0,1,3,5,9) where it should give 5.

If you can guarantee you will always ids from 0 to N, max(id)+1 may be faster depending on the index implementation (it may be faster to traverse the right side of a balanced tree rather than traversing the whole tree, counting.

But that's very implementation-specific and I would advise against relying on it, not least because it locks your performance to a specific DBMS.

\n or \n in php echo not print

Better use PHP_EOL ("End Of Line") instead. It's cross-platform.

E.g.:

$unit1 = 'paragrahp1';
$unit2 = 'paragrahp2';
echo '<p>' . $unit1 . '</p>' . PHP_EOL;
echo '<p>' . $unit2 . '</p>';

Iterating Over Dictionary Key Values Corresponding to List in Python

List comprehension can shorten things...

win_percentages = [m**2.0 / (m**2.0 + n**2.0) * 100 for m, n in [a[i] for i in NL_East]]

Dropdown select with images

I tried several jquery based custom select with images, but none worked in responsive layouts. Finally i came across Bootstrap-Select. After some modifications i was able to produce this code.

github repo link here

github repo link here

Get month name from Date

The easiest and simplest way I figured.

_x000D_
_x000D_
         var now = new Date();_x000D_
//basically converting whole date to string = "Fri Apr 2020'_x000D_
//then splitting by ' ' a space = ['Fri' 'Apr' '2020']_x000D_
//then selecting second element of array = _x000D_
//['Fri' 'Apr' '2020'].[1]_x000D_
var currentMonth = now.toDateString().split(' ')[1];_x000D_
console.log(currentMonth);_x000D_
         
_x000D_
_x000D_
_x000D_

Find an element in DOM based on an attribute value

Use query selectors, examples:

document.querySelectorAll(' input[name], [id|=view], [class~=button] ')

input[name] Inputs elements with name property.

[id|=view] Elements with id that start with view-.

[class~=button] Elements with the button class.

Git undo local branch delete

If you deleted a branch via Source Tree, you could easily find the SHA1 of the deleted branch by going to View -> Show Command History.

It should have the next format:

Deleting branch ...
...
Deleted branch %NAME% (was %SHA1%)
...

Then just follow the original answer.

git branch branchName <sha1>

Send FormData with other field in AngularJS

You're sending JSON-formatted data to a server which isn't expecting that format. You already provided the format that the server needs, so you'll need to format it yourself which is pretty simple.

var data = '"title='+title+'" "text='+text+'" "file='+file+'"';
$http.post(uploadUrl, data)

How to use css style in php

I didn't understood this Im new to php css but as you've defined your CSS at element level, already your styles are applied to your PHP code

Your PHP code is to be used with HTML like this

<!DOCTYPE html>
<html>
  <head>
    <style>
    /* Styles Go Here */
    </style>
  </head>
  <body>
  <?php
   echo 'Whatever'; 
  ?>
  </body>
</html>

Also remember, you did not need to echo HTML using php, simply separate them out like this

<table>
  <tr>
    <td><?php echo 'Blah'; ?></td>
  </tr>
</table>

Directing print output to a .txt file

Give print a file keyword argument, where the value of the argument is a file stream. We can create a file stream using the open function:

print("Hello stackoverflow!", file=open("output.txt", "a"))
print("I have a question.", file=open("output.txt", "a"))

From the Python documentation about print:

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used.

And the documentation for open:

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

The "a" as the second argument of open means "append" - in other words, the existing contents of the file won't be overwritten. If you want the file to be overwritten instead, use "w".


Opening a file with open many times isn't ideal for performance, however. You should ideally open it once and name it, then pass that variable to print's file option. You must remember to close the file afterwards!

f = open("output.txt", "a")
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)
f.close()

There's also a syntactic shortcut for this, which is the with block. This will close your file at the end of the block for you:

with open("output.txt", "a") as f:
    print("Hello stackoverflow!", file=f)
    print("I have a question.", file=f)

Where to change default pdf page width and font size in jspdf.debug.js?

My case was to print horizontal (landscape) summary section - so:

}).then((canvas) => {
  const img = canvas.toDataURL('image/jpg');
  new jsPDF({
        orientation: 'l', // landscape
        unit: 'pt', // points, pixels won't work properly
        format: [canvas.width, canvas.height] // set needed dimensions for any element
  });
  pdf.addImage(img, 'JPEG', 0, 0, canvas.width, canvas.height);
  pdf.save('your-filename.pdf');
});

Best way to do nested case statement logic in SQL Server

We can combine multiple conditions together to reduce the performance overhead.

Let there are three variables a b c on which we want to perform cases. We can do this as below:

CASE WHEN a = 1 AND b = 1 AND c = 1 THEN '1'
     WHEN a = 0 AND b = 0 AND c = 1 THEN '0'
ELSE '0' END,

SQL Server dynamic PIVOT query?

The below code provides the results which replaces NULL to zero in the output.

Table creation and data insertion:

create table test_table
 (
 date nvarchar(10),
 category char(3),
 amount money
 )

 insert into test_table values ('1/1/2012','ABC',1000.00)
 insert into test_table values ('2/1/2012','DEF',500.00)
 insert into test_table values ('2/1/2012','GHI',800.00)
 insert into test_table values ('2/10/2012','DEF',700.00)
 insert into test_table values ('3/1/2012','ABC',1100.00)

Query to generate the exact results which also replaces NULL with zeros:

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX),
@PivotColumnNames AS NVARCHAR(MAX),
@PivotSelectColumnNames AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column
SELECT @PivotColumnNames= ISNULL(@PivotColumnNames + ',','')
+ QUOTENAME(category)
FROM (SELECT DISTINCT category FROM test_table) AS cat

--Get distinct values of the PIVOT Column with isnull
SELECT @PivotSelectColumnNames 
= ISNULL(@PivotSelectColumnNames + ',','')
+ 'ISNULL(' + QUOTENAME(category) + ', 0) AS '
+ QUOTENAME(category)
FROM (SELECT DISTINCT category FROM test_table) AS cat

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
N'SELECT date, ' + @PivotSelectColumnNames + '
FROM test_table
pivot(sum(amount) for category in (' + @PivotColumnNames + ')) as pvt';

--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

OUTPUT :

enter image description here

How to size an Android view based on its parent's dimensions

You can now use PercentRelativeLayout. Boom! Problem solved.

How to set text color to a text view programmatically

Use,..

Color.parseColor("#bdbdbd");

like,

mTextView.setTextColor(Color.parseColor("#bdbdbd"));

Or if you have defined color code in resource's color.xml file than

(From API >= 23)

mTextView.setTextColor(ContextCompat.getColor(context, R.color.<name_of_color>));

(For API < 23)

mTextView.setTextColor(getResources().getColor(R.color.<name_of_color>));

How to display binary data as image - extjs 4

In ExtJs, you can use

xtype: 'image'

to render a image.

Here is a fiddle showing rendering of binary data with extjs.

atob -- > converts ascii to binary

btoa -- > converts binary to ascii

Ext.application({
    name: 'Fiddle',

    launch: function () {
        var srcBase64 = "data:image/jpeg;base64," + btoa(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8H8hYDwAFegHS8+X7mgAAAABJRU5ErkJggg=="));

        Ext.create("Ext.panel.Panel", {
            title: "Test",
            renderTo: Ext.getBody(),
            height: 400,
            items: [{
                xtype: 'image',
                width: 100,
                height: 100,
                src: srcBase64
            }]
        })
    }
});

https://fiddle.sencha.com/#view/editor&fiddle/28h0

java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

According to this SO answer, it occurs due to an AWS SDK bug that appears to be solved in version 2.6.30 of the SDK, so updating the version to a newer, can help you fixing the problem.

Slide up/down effect with ng-show and ng-animate

I've written an Angular directive that does slideToggle() without jQuery.

https://github.com/EricWVGG/AngularSlideables

Validate that a string is a positive integer

My function checks if number is +ve and could be have decimal value as well.

       function validateNumeric(numValue){
            var value = parseFloat(numValue);
            if (!numValue.toString().match(/^[-]?\d*\.?\d*$/)) 
                    return false;
            else if (numValue < 0) {
                return false;
            }
            return true;        
        }

Create an array of integers property in Objective-C

This should work:

@interface MyClass
{
    int _doubleDigits[10]; 
}

@property(readonly) int *doubleDigits;

@end

@implementation MyClass

- (int *)doubleDigits
{
    return _doubleDigits;
}

@end

CSS: center element within a <div> element

If the child element is inline (e.g not a div, table etc) I would wrap it up inside a div or a p and make the wrapper's text align css property equal to center.

    <div id="container">
        This text is aligned to the left.<br>
        So is this text.<br>
        <div style="text-align: center">
            This <button>button</button> is centered.
        </div>
        This text is still aligned left.
    </div>

Otherwise, if the element is a block (display: block, e.g a div or a p) with a fixed width, I'd set its margin left and right css properties to auto.

    <div id="container">
        This text is aligned to the left.<br>
        So is this text.<br>
        <div style="margin: 0 auto; width: 200px; background: red; color: white;">
            My parent is centered.
        </div>
        This text is still aligned left.
    </div>

You could of course add a text-align: center to the wrapper element to make its contents centered as well.

I won't bother with positioning because IMHO its not the way to go for the OPs problem but be sure to check this link out, very helpful.

Object variable or With block variable not set (Error 91)

As I wrote in my comment, the solution to your problem is to write the following:

Set hyperLinkText = hprlink.Range

Set is needed because TextRange is a class, so hyperLinkText is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.

How do you right-justify text in an HTML textbox?

Using inline styles:

<input type="text" style="text-align: right"/>

or, put it in a style sheet, like so:

<style>
   .rightJustified {
        text-align: right;
    }
</style>

and reference the class:

<input type="text" class="rightJustified"/>

Curl error 60, SSL certificate issue: self signed certificate in certificate chain

Important: This issue drove me crazy for a couple days and I couldn't figure out what was going on with my curl & openssl installations. I finally figured out that it was my intermediate certificate (in my case, GoDaddy) which was out of date. I went back to my godaddy SSL admin panel, downloaded the new intermediate certificate, and the issue disappeared.

I'm sure this is the issue for some of you.

Apparently, GoDaddy had changed their intermediate certificate at some point, due to scurity issues, as they now display this warning:

"Please be sure to use the new SHA-2 intermediate certificates included in your downloaded bundle."

Hope this helps some of you, because I was going nuts and this cleaned up the issue on ALL my servers.

What does the @Valid annotation indicate in Spring?

Another handy aspect of @Valid not mentioned above is that (ie: using Postman to test an endpoint) @Valid will format the output of an incorrect REST call into formatted JSON instead of a blob of barely readable text. This is very useful if you are creating a commercially consumable API for your users.

Redirecting to a page after submitting form in HTML

You need to use the jQuery AJAX or XMLHttpRequest() for post the data to the server. After data posting you can redirect your page to another page by window.location.href.

Example:

 var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      window.location.href = 'https://website.com/my-account';
    }
  };
  xhttp.open("POST", "demo_post.asp", true);
  xhttp.send();

Is "&#160;" a replacement of "&nbsp;"?

&#160; is the numeric reference for the entity reference &nbsp; — they are the exact same thing. It's likely your editor is simply inserting the numberic reference instead of the named one.

See the Wikipedia page for the non-breaking space.

Create a new object from type parameter in generic class

Not quite answering the question, but, there is a nice library for those kind of problems: https://github.com/typestack/class-transformer (although it won't work for generic types, as they don't really exists at run-time (here all work is done with class names (which are classes constructors)))

For instance:

import {Type, plainToClass, deserialize} from "class-transformer";

export class Foo
{
    @Type(Bar)
    public nestedClass: Bar;

    public someVar: string;

    public someMethod(): string
    {
        return this.nestedClass.someVar + this.someVar;
    }
}

export class Bar
{
    public someVar: string;
}

const json = '{"someVar": "a", "nestedClass": {"someVar": "B"}}';
const optionA = plainToClass(Foo, JSON.parse(json));
const optionB = deserialize(Foo, json);

optionA.someMethod(); // works
optionB.someMethod(); // works

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList(); 

Equivalent of Oracle's RowID in SQL Server

Check out the new ROW_NUMBER function. It works like this:

SELECT ROW_NUMBER() OVER (ORDER BY EMPID ASC) AS ROWID, * FROM EMPLOYEE

Real differences between "java -server" and "java -client"?

IIRC the server VM does more hotspot optimizations at startup so it runs faster but takes a little longer to start and uses more memory. The client VM defers most of the optimization to allow faster startup.

Edit to add: Here's some info from Sun, it's not very specific but will give you some ideas.

AngularJS : Why ng-bind is better than {{}} in angular?

There is some flickering problem in {{ }} like when you refresh the page then for a short spam of time expression is seen.So we should use ng-bind instead of expression for data depiction.

Difference between EXISTS and IN in SQL?

I think,

  • EXISTS is when you need to match the results of query with another subquery. Query#1 results need to be retrieved where SubQuery results match. Kind of a Join.. E.g. select customers table#1 who have placed orders table#2 too

  • IN is to retrieve if the value of a specific column lies IN a list (1,2,3,4,5) E.g. Select customers who lie in the following zipcodes i.e. zip_code values lies in (....) list.

When to use one over the other... when you feel it reads appropriately (Communicates intent better).

HTML5 Dynamically create Canvas

Alternative

Use element .innerHTML= which is quite fast in modern browsers

_x000D_
_x000D_
document.body.innerHTML = "<canvas width=500 height=150 id='CursorLayer'>";


// TEST

var ctx = CursorLayer.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(100, 100, 50, 50);
_x000D_
canvas { border: 1px solid black }
_x000D_
_x000D_
_x000D_

Spring Maven clean error - The requested profile "pom.xml" could not be activated because it does not exist

I was getting this same warning everytime I was doing 'maven clean'. I found the solution :

Step - 1 Right click on your project in Eclipse

Step - 2 Click Properties

Step - 3 Select Maven in the left hand side list.

Step - 4 You will notice "pom.xml" in the Active Maven Profiles text box on the right hand side. Clear it and click Apply.

Below is the screen shot :

Properties dialog box

Hope this helps. :)

Stop a youtube video with jquery?

I've had this problem before and the conclusion I've come to is that the only way to stop a video in IE is to remove it from the DOM.

How can I convert an image into a Base64 string?

If you're doing this on Android, here's a helper copied from the React Native codebase:

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.util.Base64;
import android.util.Base64OutputStream;
import android.util.Log;

// You probably don't want to do this with large files
// (will allocate a large string and can cause an OOM crash).
private String readFileAsBase64String(String path) {
  try {
    InputStream is = new FileInputStream(path);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Base64OutputStream b64os = new Base64OutputStream(baos, Base64.DEFAULT);
    byte[] buffer = new byte[8192];
    int bytesRead;
    try {
      while ((bytesRead = is.read(buffer)) > -1) {
        b64os.write(buffer, 0, bytesRead);
      }
      return baos.toString();
    } catch (IOException e) {
      Log.e(TAG, "Cannot read file " + path, e);
      // Or throw if you prefer
      return "";
    } finally {
      closeQuietly(is);
      closeQuietly(b64os); // This also closes baos
    }
  } catch (FileNotFoundException e) {
    Log.e(TAG, "File not found " + path, e);
    // Or throw if you prefer
    return "";
  }
}

private static void closeQuietly(Closeable closeable) {
  try {
    closeable.close();
  } catch (IOException e) {
  }
}

How does Java deal with multiple conditions inside a single IF statement

Yes,that is called short-circuiting.

Please take a look at this wikipedia page on short-circuiting

Run bash script as daemon

Another cool trick is to run functions or subshells in background, not always feasible though

name(){
  echo "Do something"
  sleep 1
}

# put a function in the background
name &
#Example taken from here
#https://bash.cyberciti.biz/guide/Putting_functions_in_background

Running a subshell in the background

(echo "started"; sleep 15; echo "stopped") &

Android Intent Cannot resolve constructor

this work for me

    ncharacters.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent openncharacter = new Intent(getApplicationContext(),ncharacters.class);
            startActivity(openncharacter);
        }
    });

INSERT INTO vs SELECT INTO

I only want to cover second point of the question that is related to performance, because no body else has covered this. Select Into is a lot more faster than insert into, when it comes to tables with large datasets. I prefer select into when I have to read a very large table. insert into for a table with 10 million rows may take hours while select into will do this in minutes, and as for as losing indexes on new table is concerned you can recreate the indexes by query and can still save a lot more time when compared to insert into.

How to mock a final class with mockito

This can be done if you are using Mockito2, with the new incubating feature which supports mocking of final classes & methods.

Key points to note:
1. Create a simple file with the name “org.mockito.plugins.MockMaker” and place it in a folder named “mockito-extensions”. This folder should be made available on the classpath.
2. The content of the file created above should be a single line as given below:
mock-maker-inline

The above two steps are required in order to activate the mockito extension mechanism and use this opt-in feature.

Sample classes are as follows:-

FinalClass.java

public final class FinalClass {

public final String hello(){
    System.out.println("Final class says Hello!!!");
    return "0";
}

}

Foo.java

public class Foo {

public String executeFinal(FinalClass finalClass){
    return finalClass.hello();
}

}

FooTest.java

public class FooTest {

@Test
public void testFinalClass(){
    // Instantiate the class under test.
    Foo foo = new Foo();

    // Instantiate the external dependency
    FinalClass realFinalClass = new FinalClass();

    // Create mock object for the final class. 
    FinalClass mockedFinalClass = mock(FinalClass.class);

    // Provide stub for mocked object.
    when(mockedFinalClass.hello()).thenReturn("1");

    // assert
    assertEquals("0", foo.executeFinal(realFinalClass));
    assertEquals("1", foo.executeFinal(mockedFinalClass));

}

}

Hope it helps.

Complete article present here mocking-the-unmockable.

What is VanillaJS?

VanillaJS === JavaScript i.e.VanillaJS is native JavaScript

Why, Vanilla says it all!!!

Computer software, and sometimes also other computing-related systems like computer hardware or algorithms, are called vanilla when not customized from their original form, meaning that they are used without any customization or updates applied to them (Refer this article). So Vanilla often refers to pure or plain.

In the English language Vanilla has a similar meaning, In information technology, vanilla (pronounced vah-NIHL-uh ) is an adjective meaning plain or basic. Or having no special or extra features, ordinary or standard.

So why name it VanillaJS? As the accepted answer says some bosses want to work with a framework (because it's more organized and flexible and do all the things we want??) but simply JavaScript will do the job. Yet you need to add a framework somewhere. Use VanillaJS...

Is it a Joke? YES

Want some fun? Where can you find it, http://vanilla-js.com/ Download and see for yourself!!! It's 0 bytes uncompressed, 25 bytes gzipped :D

Found this pun on internet regarding JS frameworks (Not to condemn the existing JS frameworks though, they'll make life really easy :)), enter image description here

Also refer,

What is the correct way to read a serial port using .NET framework?

Could you try something like this for example I think what you are wanting to utilize is the port.ReadExisting() Method

 using System;
 using System.IO.Ports;

 class SerialPortProgram 
 { 
  // Create the serial port with basic settings 
    private SerialPort port = new   SerialPort("COM1",
      9600, Parity.None, 8, StopBits.One); 
    [STAThread] 
    static void Main(string[] args) 
    { 
      // Instatiate this 
      SerialPortProgram(); 
    } 

    private static void SerialPortProgram() 
    { 
        Console.WriteLine("Incoming Data:");
         // Attach a method to be called when there
         // is data waiting in the port's buffer 
        port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); 
        // Begin communications 
        port.Open(); 
        // Enter an application loop to keep this thread alive 
        Console.ReadLine();
     } 

    private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) 
    { 
       // Show all the incoming data in the port's buffer
       Console.WriteLine(port.ReadExisting()); 
    } 
}

Or is you want to do it based on what you were trying to do , you can try this

public class MySerialReader : IDisposable
{
  private SerialPort serialPort;
  private Queue<byte> recievedData = new Queue<byte>();

  public MySerialReader()
  {
    serialPort = new SerialPort();
    serialPort.Open();
    serialPort.DataReceived += serialPort_DataReceived;
  }

  void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
  {
    byte[] data = new byte[serialPort.BytesToRead];
    serialPort.Read(data, 0, data.Length);
    data.ToList().ForEach(b => recievedData.Enqueue(b));
    processData();
  }

  void processData()
  {
    // Determine if we have a "packet" in the queue
    if (recievedData.Count > 50)
    {
        var packet = Enumerable.Range(0, 50).Select(i => recievedData.Dequeue());
    }
  }

  public void Dispose()
  {
        if (serialPort != null)
        {
            serialPort.Dispose();
        }
  }