Programs & Examples On #Geshi

Geshi is a free software library that allows syntax highlighting of source code for several markup and programming languages.

lexers vs parsers

To answer the question as asked (without repeating unduly what appears in other answers)

Lexers and parsers are not very different, as suggested by the accepted answer. Both are based on simple language formalisms: regular languages for lexers and, almost always, context-free (CF) languages for parsers. They both are associated with fairly simple computational models, the finite state automaton and the push-down stack automaton. Regular languages are a special case of context-free languages, so that lexers could be produced with the somewhat more complex CF technology. But it is not a good idea for at least two reasons.

A fundamental point in programming is that a system component should be buit with the most appropriate technology, so that it is easy to produce, to understand and to maintain. The technology should not be overkill (using techniques much more complex and costly than needed), nor should it be at the limit of its power, thus requiring technical contortions to achieve the desired goal.

That is why "It seems fashionable to hate regular expressions". Though they can do a lot, they sometimes require very unreadable coding to achieve it, not to mention the fact that various extensions and restrictions in implementation somewhat reduce their theoretical simplicity. Lexers do not usually do that, and are usually a simple, efficient, and appropriate technology to parse token. Using CF parsers for token would be overkill, though it is possible.

Another reason not to use CF formalism for lexers is that it might then be tempting to use the full CF power. But that might raise sructural problems regarding the reading of programs.

Fundamentally, most of the structure of program text, from which meaning is extracted, is a tree structure. It expresses how the parse sentence (program) is generated from syntax rules. Semantics is derived by compositional techniques (homomorphism for the mathematically oriented) from the way syntax rules are composed to build the parse tree. Hence the tree structure is essential. The fact that tokens are identified with a regular set based lexer does not change the situation, because CF composed with regular still gives CF (I am speaking very loosely about regular transducers, that transform a stream of characters into a stream of token).

However, CF composed with CF (via CF transducers ... sorry for the math), does not necessarily give CF, and might makes things more general, but less tractable in practice. So CF is not the appropriate tool for lexers, even though it can be used.

One of the major differences between regular and CF is that regular languages (and transducers) compose very well with almost any formalism in various ways, while CF languages (and transducers) do not, not even with themselves (with a few exceptions).

(Note that regular transducers may have others uses, such as formalization of some syntax error handling techniques.)

BNF is just a specific syntax for presenting CF grammars.

EBNF is a syntactic sugar for BNF, using the facilities of regular notation to give terser version of BNF grammars. It can always be transformed into an equivalent pure BNF.

However, the regular notation is often used in EBNF only to emphasize these parts of the syntax that correspond to the structure of lexical elements, and should be recognized with the lexer, while the rest with be rather presented in straight BNF. But it is not an absolute rule.

To summarize, the simpler structure of token is better analyzed with the simpler technology of regular languages, while the tree oriented structure of the language (of program syntax) is better handled by CF grammars.

I would suggest also looking at AHR's answer.

But this leaves a question open: Why trees?

Trees are a good basis for specifying syntax because

  • they give a simple structure to the text

  • there are very convenient for associating semantics with the text on the basis of that structure, with a mathematically well understood technology (compositionality via homomorphisms), as indicated above. It is a fundamental algebraic tool to define the semantics of mathematical formalisms.

Hence it is a good intermediate representation, as shown by the success of Abstract Syntax Trees (AST). Note that AST are often different from parse tree because the parsing technology used by many professionals (Such as LL or LR) applies only to a subset of CF grammars, thus forcing grammatical distorsions which are later corrected in AST. This can be avoided with more general parsing technology (based on dynamic programming) that accepts any CF grammar.

Statement about the fact that programming languages are context-sensitive (CS) rather than CF are arbitrary and disputable.

The problem is that the separation of syntax and semantics is arbitrary. Checking declarations or type agreement may be seen as either part of syntax, or part of semantics. The same would be true of gender and number agreement in natural languages. But there are natural languages where plural agreement depends on the actual semantic meaning of words, so that it does not fit well with syntax.

Many definitions of programming languages in denotational semantics place declarations and type checking in the semantics. So stating as done by Ira Baxter that CF parsers are being hacked to get a context sensitivity required by syntax is at best an arbitrary view of the situation. It may be organized as a hack in some compilers, but it does not have to be.

Also it is not just that CS parsers (in the sense used in other answers here) are hard to build, and less efficient. They are are also inadequate to express perspicuously the kinf of context-sensitivity that might be needed. And they do not naturally produce a syntactic structure (such as parse-trees) that is convenient to derive the semantics of the program, i.e. to generate the compiled code.

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

Try this:

<div id="wrapper">
    <div class="float left">left</div>
    <div class="float right">right</div>

#wrapper {

.float {

.left {

.right {


Rails 4 - Strong Parameters - Nested Objects

I found this suggestion useful in my case:

  def product_params
    params.require(:product).permit(:name).tap do |whitelisted|
      whitelisted[:data] = params[:product][:data]

Check this link of Xavier's comment on github.

This approach whitelists the entire params[:measurement][:groundtruth] object.

Using the original questions attributes:

  def product_params
    params.require(:measurement).permit(:name, :groundtruth).tap do |whitelisted|
      whitelisted[:groundtruth] = params[:measurement][:groundtruth]

How to set the locale inside a Debian/Ubuntu Docker container?

You guys don't need those complex things to set locales on Ubuntu/Debian. You don't even need /etc/local.gen file.

Simply locale-gen will do everything and the author only missed locales package.

RUN apt-get update && apt-get install -y locales && rm -rf /var/lib/apt/lists/* \
 && locale-gen "en_US.UTF-8"
    LANGUAGE=en_US:en \

I found this the simplest and the most effective. I confirm it works on Ubuntu 16.04.

Connect to network drive with user name and password

I really don't know the hidden process, but I use a webrequest, this way I'm able to pass the credentials, and it worked perfectly for me.

var ftpDownloadFile = WebRequest.Create("filePath");
ftpDownloadFile.Method = WebRequestMethods.Ftp.DownloadFile;
ftpDownloadFile.Credentials = new NetworkCredential("user", "pass");
using (var reader = (FtpWebResponse)ftpDownloadFile.GetResponse())
using (var responseStream = reader.GetResponseStream())
    var writeStream = new FileStream(Path.Combine(LocalStorage), FileMode.Create);
    const int length = 2048;
    var buffer = new Byte[length];
    if (responseStream != null)
        var bytesRead = responseStream.Read(buffer, 0, length);
        while (bytesRead > 0)
            writeStream.Write(buffer, 0, bytesRead);
            bytesRead = responseStream.Read(buffer, 0, length);

How to remove a variable from a PHP session array

if (isset($_POST['remove'])) {
    $_SESSION["name"] = array_values($_SESSION["name"]);

Since $_SESSION['name'] is an array, you need to find the array key that points at the name value you're interested in. The last line rearranges the index of the array for the next use.

What is the perfect counterpart in Python for "while not EOF"

You can use below code snippet to read line by line, till end of file

line = obj.readline()
while(line != ''):

    # Do Something

    line = obj.readline()

How do I find the location of my Python site-packages directory?

pip show will give all the details about a package: [pip show][1]

To get the location:

pip show <package_name>| grep Location

Python Save to file

You need to open the file again using open(), but this time passing 'w' to indicate that you want to write to the file. I would also recommend using with to ensure that the file will be closed when you are finished writing to it.

with open('Failed.txt', 'w') as f:
    for ip in [k for k, v in ips.iteritems() if v >=5]:

Naturally you may want to include newlines or other formatting in your output, but the basics are as above.

The same issue with closing your file applies to the reading code. That should look like this:

ips = {}
with open('today','r') as myFile:
    for line in myFile:
        parts = line.split(' ')
        if parts[1] == 'Failure':
            if parts[0] in ips:
                ips[pars[0]] += 1
                ips[parts[0]] = 0

How to upload a file in Django?

Generally speaking when you are trying to 'just get a working example' it is best to 'just start writing code'. There is no code here to help you with, so it makes answering the question a lot more work for us.

If you want to grab a file, you need something like this in an html file somewhere:

<form method="post" enctype="multipart/form-data">
    <input type="file" name="myfile" />
    <input type="submit" name="submit" value="Upload" />

That will give you the browse button, an upload button to start the action (submit the form) and note the enctype so Django knows to give you request.FILES

In a view somewhere you can access the file with

def myview(request):
    request.FILES['myfile'] # this is my file

There is a huge amount of information in the file upload docs

I recommend you read the page thoroughly and just start writing code - then come back with examples and stack traces when it doesn't work.

Make a VStack fill the width of the screen in SwiftUI

 var body: some View {
      VStack {
           List {
                ForEach(viewModel.parents) { k in
                    VideosRowView(parent: k)

How can I convert a string to a number in Perl?

Perl is weakly typed and context based. Many scalars can be treated both as strings and numbers, depending on the operators you use. $a = 7*6; $b = 7x6; print "$a $b\n";
You get 42 777777.

There is a subtle difference, however. When you read numeric data from a text file into a data structure, and then view it with Data::Dumper, you'll notice that your numbers are quoted. Perl treats them internally as strings.
Read:$my_hash{$1} = $2 if /(.+)=(.+)\n/;.
Dump:'foo' => '42'

If you want unquoted numbers in the dump:
Read:$my_hash{$1} = $2+0 if /(.+)=(.+)\n/;.
Dump:'foo' => 42

After $2+0 Perl notices that you've treated $2 as a number, because you used a numeric operator.

I noticed this whilst trying to compare two hashes with Data::Dumper.

Your password does not satisfy the current policy requirements

NOTE: This might not be a secure solution. But if you are working on a test environment, just need a quick fix and doesn't even care about the security settings. This is a quick solution.

The same issue happened to me when I ran "mysql_secure_installation" and modified password security level to 'medium'.

I bypassed the error by running the followings:

mysql -h localhost -u root -p
mysql>uninstall plugin validate_password;

make sure you reinstall the plugin "validate_password" if necessary.

This compilation unit is not on the build path of a Java project

Another alternative to Loganathan Mohanraj's solution (which effectively does the same, but from the GUI):

  1. Right-Click on your project
  2. Go to "Properties"
  3. Choose "Project Natures"
  4. Click on "Add"
  5. Choose "Java"
  6. Click "Apply and Close"

Converting RGB to grayscale/intensity

The specific numbers in the question are from CCIR 601 (see the Wikipedia link below).

If you convert RGB -> grayscale with slightly different numbers / different methods, you won't see much difference at all on a normal computer screen under normal lighting conditions -- try it.

Here are some more links on color in general:

Wikipedia Luma

Bruce Lindbloom 's outstanding web site

chapter 4 on Color in the book by Colin Ware, "Information Visualization", isbn 1-55860-819-2; this long link to Ware in may or may not work

cambridgeincolor : excellent, well-written "tutorials on how to acquire, interpret and process digital photographs using a visually-oriented approach that emphasizes concept over procedure"

Should you run into "linear" vs "nonlinear" RGB, here's part of an old note to myself on this. Repeat, in practice you won't see much difference.

RGB -> ^gamma -> Y -> L*

In color science, the common RGB values, as in html rgb( 10%, 20%, 30% ), are called "nonlinear" or Gamma corrected. "Linear" values are defined as

Rlin = R^gamma,  Glin = G^gamma,  Blin = B^gamma

where gamma is 2.2 for many PCs. The usual R G B are sometimes written as R' G' B' (R' = Rlin ^ (1/gamma)) (purists tongue-click) but here I'll drop the '.

Brightness on a CRT display is proportional to RGBlin = RGB ^ gamma, so 50% gray on a CRT is quite dark: .5 ^ 2.2 = 22% of maximum brightness. (LCD displays are more complex; furthermore, some graphics cards compensate for gamma.)

To get the measure of lightness called L* from RGB, first divide R G B by 255, and compute

Y = .2126 * R^gamma + .7152 * G^gamma + .0722 * B^gamma

This is Y in XYZ color space; it is a measure of color "luminance". (The real formulas are not exactly x^gamma, but close; stick with x^gamma for a first pass.)


L* = 116 * Y ^ 1/3 - 16

"... aspires to perceptual uniformity [and] closely matches human perception of lightness." -- Wikipedia Lab color space

In Subversion can I be a user other than my login name?

You can setup a default username via ~/.subversion/servers:

yourgroupname =

username = yourusername

Please be aware that older versions of svn do not support it (e.g. 1.3.1 [sic!]).

A TypeScript GUID class?

There is an implementation in my TypeScript utilities based on JavaScript GUID generators.

Here is the code:

class Guid {_x000D_
  static newGuid() {_x000D_
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
      var r = Math.random() * 16 | 0,_x000D_
        v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
      return v.toString(16);_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
  var id = Guid.newGuid();_x000D_

Please note the following:

C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.

JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).

How to redirect DNS to different ports

You can use SRV records: TTL class SRV priority weight port target.

Service: the symbolic name of the desired service.

Proto: the transport protocol of the desired service; this is usually either TCP or UDP.

Name: the domain name for which this record is valid, ending in a dot.

TTL: standard DNS time to live field.

Class: standard DNS class field (this is always IN).

Priority: the priority of the target host, lower value means more preferred.

Weight: A relative weight for records with the same priority.

Port: the TCP or UDP port on which the service is to be found.

Target: the canonical hostname of the machine providing the service, ending in a dot.

Example: 86400 IN SRV 0 5 5060

So what I think you're looking for is to add something like this to your DNS hosts file: 86400 IN SRV 10 40 25565 86400 IN SRV 10 30 25566 86400 IN SRV 10 30 25567

On a side note, I highly recommend you go with a hosting company rather than hosting the servers yourself. It's just asking for trouble with your home connection (DDoS and Bandwidth/Connection Speed), but it's up to you.

How can I exclude a directory from Visual Studio Code "Explore" tab?

Use files.exclude:

  • Go to File -> Preferences -> Settings (or on Mac Code -> Preferences -> Settings)
  • Pick the workspace settings tab
  • Add this code to the settings.json file displayed on the right side:

    // Place your settings in this file to overwrite default and user settings.
        "settings": {
            "files.exclude": {
                "**/.git": true,         // this is a default value
                "**/.DS_Store": true,    // this is a default value
                "**/node_modules": true, // this excludes all folders 
                                        // named "node_modules" from 
                                        // the explore tree
                // alternative version
                "node_modules": true    // this excludes the folder 
                                        // only from the root of
                                        // your workspace 

If you chose File -> Preferences -> User Settings then you configure the exclude folders globally for your current user.

Linux command: How to 'find' only text files?

How about this

 find . -type f|xargs grep "needle text"

How do I make a MySQL database run completely in memory?

Assuming you understand the consequences of using the MEMORY engine as mentioned in comments, and here, as well as some others you'll find by searching about (no transaction safety, locking issues, etc) - you can proceed as follows:

MEMORY tables are stored differently than InnoDB, so you'll need to use an export/import strategy. First dump each table separately to a file using SELECT * FROM tablename INTO OUTFILE 'table_filename'. Create the MEMORY database and recreate the tables you'll be using with this syntax: CREATE TABLE tablename (...) ENGINE = MEMORY;. You can then import your data using LOAD DATA INFILE 'table_filename' INTO TABLE tablename for each table.

Reading rather large json files in Python

The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.

The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.

The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.

Edit: Also worth a look - kashif's comment about json-streamer and Henrik Heino's comment about bigjson.

Detecting the character encoding of an HTTP POST request

the default encoding of a HTTP POST is ISO-8859-1.

else you have to look at the Content-Type header that will then look like

Content-Type: application/x-www-form-urlencoded ; charset=UTF-8

You can maybe declare your form with

<form enctype="application/x-www-form-urlencoded;charset=UTF-8">


<form accept-charset="UTF-8">

to force the encoding.

Some references :

How can I use getSystemService in a non-activity class (LocationManager)?

Use this in Activity:

private Context context = this;

Utils.showToast(context, "toast");

in Utils:

public class Utils {

    public static boolean isInternetAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();


How can you make a custom keyboard in Android?

Had the same problem. I used table layout at first but the layout kept changing after a button press. Found this page very useful though.

What is the difference between dynamic and static polymorphism in Java?

In simple terms :

Static polymorphism : Same method name is overloaded with different type or number of parameters in same class (different signature). Targeted method call is resolved at compile time.

Dynamic polymorphism: Same method is overridden with same signature in different classes. Type of object on which method is being invoked is not known at compile time but will be decided at run time.

Generally overloading won't be considered as polymorphism.

From java tutorial page :

Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class

MySQL stored procedure vs function, which would I use when?

One significant difference is that you can include a function in your SQL queries, but stored procedures can only be invoked with the CALL statement:

UDF Example:

   RETURN CONCAT('Hello, ',s,'!');
Query OK, 0 rows affected (0.00 sec)

CREATE TABLE names (id int, name varchar(20));
INSERT INTO names VALUES (1, 'Bob');
INSERT INTO names VALUES (2, 'John');
INSERT INTO names VALUES (3, 'Paul');

SELECT hello(name) FROM names;
| hello(name)  |
| Hello, Bob!  |
| Hello, John! |
| Hello, Paul! |
3 rows in set (0.00 sec)

Sproc Example:

delimiter //

CREATE PROCEDURE simpleproc (IN s CHAR(100))
   SELECT CONCAT('Hello, ', s, '!');
Query OK, 0 rows affected (0.00 sec)

delimiter ;

CALL simpleproc('World');
| CONCAT('Hello, ', s, '!') |
| Hello, World!             |
1 row in set (0.00 sec)

how to specify local modules as npm package dependencies

If it's acceptible to simply publish your modules preinstalled in node_modules alongside your other files, you can do it like this:

// ./node_modules/foo/package.json

// ./package.json
"dependencies": {

// ./app.js
var foo = require('foo');

You may also want to store your module on git and tell your parent package.json to install the dependency from git:

TCPDF ERROR: Some data has already been output, can't send PDF file

Use ob_start(); at the beginning of your code.

How do I load an HTML page in a <div> using JavaScript?

Use this simple code

<div w3-include-HTML="content.html"></div>

Format of the initialization string does not conform to specification starting at index 0

I had the same problem and finally I managed to resolve it in the following way:

The problem was in the connection string definition in my web.config.

<add name="DefaultConnection" connectionString="DefaultConnection_ConnectionString" providerName="System.Data.SqlClient"/>

The above worked perfect locally because I used a local Database when I managed users and roles. When I transfered my application to IIS the local DB was not longer accessible, in addition I would like to use my DB in SQL Server. So I change the above connection string the following SQL Server DB equivalent:

<add name="DefaultConnection" connectionString="data source=MY_SQL_SERVER; Initial Catalog=MY_DATABASE_NAME; Persist Security Info=true; User Id=sa;Password=Mybl00dyPa$$" providerName="System.Data.SqlClient"/>

NOTE: The above, also, suppose that you are going to use the same SQL Server from your local box (in case that you incorporate it into your local web.config - that is what exactly I did in my case).

How can I perform an inspect element in Chrome on my Galaxy S3 Android device?

Keep in mind that if you want to use the chrome inspect in Windows, besides enabling usb debugging on you mobile, you should also install the usb driver for Windows.

You can find the drivers you need from the list here:

Furthermore, you should use a newer version of Chrome mobile than the one in your Desktop.

How to move mouse cursor using C#?

First Add a Class called Win32.cs

public class Win32
    public static extern long SetCursorPos(int x, int y);

    public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);

    public struct POINT
        public int x;
        public int y;

        public POINT(int X, int Y)
            x = X;
            y = Y;

You can use it then like this:

Win32.POINT p = new Win32.POINT(xPos, yPos);

Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);

SQL search multiple values in same field

This will works perfectly in both cases, one or multiple fields searching multiple words.

Hope this will help someone. Thanks

declare @searchTrm varchar(MAX)='one two three four'; 
--select value from STRING_SPLIT(@searchTrm, ' ') where trim(value)<>''
select * from Bols 
    FROM STRING_SPLIT(@searchTrm, ' ')  
        BolNumber like '%'+ value+'%'
        or UserComment like '%'+ value+'%'
        or RequesterId like '%'+ value+'%' )

Read/Parse text file line by line in VBA

for the most basic read of a text file, use open


Dim FileNum As Integer
Dim DataLine As String

FileNum = FreeFile()
Open "Filename" For Input As #FileNum

While Not EOF(FileNum)
    Line Input #FileNum, DataLine ' read in data 1 line at a time
    ' decide what to do with dataline, 
    ' depending on what processing you need to do for each case

PyTorch: How to get the shape of a Tensor as a list of int

Previous answers got you list of torch.Size Here is how to get list of ints

listofints = [int(x) for x in tensor.shape]

Can't bind to 'ngModel' since it isn't a known property of 'input'

This is for the folks who use plain JavaScript instead of Type Script. In addition to referencing the forms script file on top of the page like below:

<script src="node_modules/@angular/forms/bundles/forms.umd.js"></script>

You should also tell the the module loader to load the ng.forms.FormsModule. After making the changes my imports property of NgModule method looked like below:

imports: [ng.platformBrowser.BrowserModule, ng.forms.FormsModule],

How do you extract a column from a multi-dimensional array?

All columns from a matrix into a new list:

N = len(matrix) 
column_list = [ [matrix[row][column] for row in range(N)] for column in range(N) ]

How can I open a .tex file?

I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.

I have to assume you are using windows because you have mentioned notepad++.

  1. Use notepad++. Right click on the file and choose "edit with notepad++"

  2. Use notepad Change the filename extension to .txt and double click the file.

  3. Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"

If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.

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

One point I noticed with Primefaces 3.4 and Netbeans 7.2:

Remove the Netbeans auto-filled parameters for function handleFileUpload i.e. (event) otherwise event could be null.

    <p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload(event)}"

    <p:growl id="messages" showDetail="true"/>

Error with multiple definitions of function

Here is a highly simplified but hopefully relevant view of what happens when you build your code in C++.

C++ splits the load of generating machine executable code in following different phases -

  1. Preprocessing - This is where any macros - #defines etc you might be using get expanded.

  2. Compiling - Each cpp file along with all the #included files in that file directly or indirectly (together called a compilation unit) is converted into machine readable object code.

    This is where C++ also checks that all functions defined (i.e. containing a body in { } e.g. void Foo( int x){ return Boo(x); }) are referring to other functions in a valid manner.

    The way it does that is by insisting that you provide at least a declaration of these other functions (e.g. void Boo(int); ) before you call it so it can check that you are calling it properly among other things. This can be done either directly in the cpp file where it is called or usually in an included header file.

    Note that only the machine code that corresponds to functions defined in this cpp and included files gets built as the object (binary) version of this compilation unit (e.g. Foo) and not the ones that are merely declared (e.g. Boo).

  3. Linking - This is the stage where C++ goes hunting for stuff declared and called in each compilation unit and links it to the places where it is getting called. Now if there was no definition found of this function the linker gives up and errors out. Similarly if it finds multiple definitions of the same function signature (essentially the name and parameter types it takes) it also errors out as it considers it ambiguous and doesn't want to pick one arbitrarily.

The latter is what is happening in your case. By doing a #include of the fun.cpp file, both fun.cpp and mainfile.cpp have a definition of funct() and the linker doesn't know which one to use in your program and is complaining about it.

The fix as Vaughn mentioned above is to not include the cpp file with the definition of funct() in mainfile.cpp and instead move the declaration of funct() in a separate header file and include that in mainline.cpp. This way the compiler will get the declaration of funct() to work with and the linker would get just one definition of funct() from fun.cpp and will use it with confidence.

React fetch data in server before render

I've just stumbled upon this problem too, learning React, and solved it by showing spinner until the data is ready.

    render() {
    if ( === null) {
        return (
            <div className="MyView">
    else {
            <div className="MyView">
                <ReactJson src={}/>

Tomcat: How to find out running tomcat version

I know it is maybe too late for this, but this could be usefull: If you try to know Apache Tomcat Server version from Java code, you can use:

from a HttpServlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response) {

from a ServletContextListener:

public void contextInitialized(ServletContextEvent event)  { 

What's the difference between F5 refresh and Shift+F5 in Google Chrome browser?

It ignores the cached content when refreshing...

F5 or Control + R = Reload the current page
Control+Shift+R or Shift + F5 = Reload your current page, ignoring cached content

Display progress bar while doing some work in C#?

And another example that BackgroundWorker is the right way to do it...

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace SerialSample
    public partial class Form1 : Form
        private BackgroundWorker _BackgroundWorker;
        private Random _Random;

        public Form1()
            _ProgressBar.Style = ProgressBarStyle.Marquee;
            _ProgressBar.Visible = false;
            _Random = new Random();


        private void InitializeBackgroundWorker()
            _BackgroundWorker = new BackgroundWorker();
            _BackgroundWorker.WorkerReportsProgress = true;

            _BackgroundWorker.DoWork += (sender, e) => ((MethodInvoker)e.Argument).Invoke();
            _BackgroundWorker.ProgressChanged += (sender, e) =>
                    _ProgressBar.Style = ProgressBarStyle.Continuous;
                    _ProgressBar.Value = e.ProgressPercentage;
            _BackgroundWorker.RunWorkerCompleted += (sender, e) =>
                if (_ProgressBar.Style == ProgressBarStyle.Marquee)
                    _ProgressBar.Visible = false;

        private void buttonStart_Click(object sender, EventArgs e)
            _BackgroundWorker.RunWorkerAsync(new MethodInvoker(() =>
                    _ProgressBar.BeginInvoke(new MethodInvoker(() => _ProgressBar.Visible = true));
                    for (int i = 0; i < 1000; i++)
                        _BackgroundWorker.ReportProgress(i / 10);

How to pass a parameter to Vue @click event handler

Just use a normal Javascript expression, no {} or anything necessary:


if you also need the event object:

@click="addToCount(item.contactID, $event)"

Finding blocking/locking queries in MS SQL (mssql)

You may find this query useful:

FROM sys.dm_exec_requests
WHERE DB_NAME(database_id) = 'YourDBName' 
AND blocking_session_id <> 0

error: pathspec 'test-branch' did not match any file(s) known to git

just follow three steps, git branch problem will be solved.

git remote update
git fetch
git checkout --track origin/test-branch

How to convert float number to Binary?

Keep multiplying the number after decimal by 2 till it becomes 1.0:

0.25*2 = 0.50
0.50*2 = 1.00

and the result is in reverse order being .01

How to URL encode in Python 3?

You misread the documentation. You need to do two things:

  1. Quote each key and value from your dictionary, and
  2. Encode those into a URL

Luckily urllib.parse.urlencode does both those things in a single step, and that's the function you should be using.

from urllib.parse import urlencode, quote_plus

payload = {'username':'administrator', 'password':'xyz'}
result = urlencode(payload, quote_via=quote_plus)
# 'password=xyz&username=administrator'

Set value to an entire column of a pandas dataframe

You can do :

df['industry'] = 'yyy'

Make the size of a heatmap bigger with seaborn

add plt.figure(figsize=(16,5)) before the sns.heatmap and play around with the figsize numbers till you get the desired size


plt.figure(figsize = (16,5))

ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5)

Bash: infinite sleep (infinite blocking)

Instead of killing the window manager, try running the new one with --replace or -replace if available.

javascript - Create Simple Dynamic Array

A little late to this game, but there is REALLY cool stuff you can do with ES6 these days.

You can now fill an array of dynamic length with random numbers in one line of code!

[...Array(10).keys()].map(() => Math.floor(Math.random() * 100))

jquery: animate scrollLeft

First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate


    $('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);

    $('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);

The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.

After installing SQL Server 2014 Express can't find local db

Also, if you just installed localDB, you won't see the instance in the configuration manager. You would need to initiate it first, and then connect to it using server name (localdb)\mssqllocaldb. Source

How do I get the offset().top value of an element without using jQuery?

For Angular 2+ to get the offset of the current element (this.el.nativeElement is equvalent of $(this) in jquery):

export class MyComponent implements  OnInit {

constructor(private el: ElementRef) {}

    ngOnInit() {
      //This is the important line you can use in your function in the code
        let offset = this.el.nativeElement.getBoundingClientRect().top;



Is Java RegEx case-insensitive?

Yes, case insensitivity can be enabled and disabled at will in Java regex.

It looks like you want something like this:

        "Have a meRry MErrY Christmas ho Ho hO"
            .replaceAll("(?i)\\b(\\w+)(\\s+\\1)+\\b", "$1")
    // Have a meRry Christmas ho

Note that the embedded Pattern.CASE_INSENSITIVE flag is (?i) not \?i. Note also that one superfluous \b has been removed from the pattern.

The (?i) is placed at the beginning of the pattern to enable case-insensitivity. In this particular case, it is not overridden later in the pattern, so in effect the whole pattern is case-insensitive.

It is worth noting that in fact you can limit case-insensitivity to only parts of the whole pattern. Thus, the question of where to put it really depends on the specification (although for this particular problem it doesn't matter since \w is case-insensitive.

To demonstrate, here's a similar example of collapsing runs of letters like "AaAaaA" to just "A".

        "AaAaaA eeEeeE IiiIi OoooOo uuUuUuu"
            .replaceAll("(?i)\\b([A-Z])\\1+\\b", "$1")
    ); // A e I O u

Now suppose that we specify that the run should only be collapsed only if it starts with an uppercase letter. Then we must put the (?i) in the appropriate place:

        "AaAaaA eeEeeE IiiIi OoooOo uuUuUuu"
            .replaceAll("\\b([A-Z])(?i)\\1+\\b", "$1")
    ); // A eeEeeE I O uuUuUuu

More generally, you can enable and disable any flag within the pattern as you wish.

See also

Related questions

How do I get console input in javascript?

You can try something like process.argv, that is if you are using node.js to run the program.
console.log(process.argv) => Would print an array containing


You get the user provided input via array index, i.e., console.log(process.argv[3]) This should provide you with the input which you can store.


var somevariable = process.argv[3]; // input one
var somevariable2 = process.argv[4]; // input two


If you are building a command-line program then the npm package yargs would be really helpful.

What are best practices that you use when writing Objective-C and Cocoa?

All these comments are great, but I'm really surprised nobody mentioned Google's Objective-C Style Guide that was published a while back. I think they have done a very thorough job.

Sending a JSON to server and retrieving a JSON in return, without JQuery

Using new api fetch:

const dataToSend = JSON.stringify({"email": "[email protected]", "password": "101010"});
let dataReceived = ""; 
fetch("", {
    credentials: "same-origin",
    mode: "same-origin",
    method: "post",
    headers: { "Content-Type": "application/json" },
    body: dataToSend
    .then(resp => {
        if (resp.status === 200) {
            return resp.json()
        } else {
            console.log("Status: " + resp.status)
            return Promise.reject("server")
    .then(dataJson => {
        dataReceived = JSON.parse(dataJson)
    .catch(err => {
        if (err === "server") return

console.log(`Received: ${dataReceived}`)                
_x000D_ You need to handle when server sends other status rather than 200(ok), you should reject that result because if you were to left it in blank, it will try to parse the json but there isn't, so it will throw an error

Set value of textarea in jQuery

Textarea has no value attribute, its value comes between tags, i.e: <textarea>my text</textarea>, it is not like the input field (<input value="my text" />). That's why attr doesn't work :)

Issue when importing dataset: `Error in scan(...): line 1 did not have 145 elements`

Beside all the guidance mentioned above,you can also check all the data.

If there are blanks between words, you must replace them with "_".

However that how I solve my own problem.

Variable used in lambda expression should be final or effectively final

if it is not necessary to modify the variable than a general workaround for this kind of problem would be to extract the part of code which use lambda and use final keyword on method-parameter.

Go To Definition: "Cannot navigate to the symbol under the caret."

I also came across this once. There is something wrong with TFS in VS 2015.

I followed these steps and it worked

  1. Cleared TFS Cache This might be here:

    C:\Users\(UserName)\AppData\Local\Microsoft\Team Foundation\(Version)\Cache

Note: path may vary based on operating system so don't blame me.

  1. Emptied Symbol Cache

    Tools > Options > Debugging > Symbols > EmptySymbolCache

  2. Restarted Visual Studio (It Might ask for connecting to TFS again)

This Worked for me.:)

How to build an APK file in Eclipse?

The bin/XXX.apk file can be built automatically as soon as you save any source file:

Window/Preferences, Android/Build, uncheck "skip packaging and indexing..."

What is the difference between static_cast<> and C style casting?

Since there are many different kinds of casting each with different semantics, static_cast<> allows you to say "I'm doing a legal conversion from one type to another" like from int to double. A plain C-style cast can mean a lot of things. Are you up/down casting? Are you reinterpreting a pointer?

Add spaces between the characters of a string in Java?

I am creating a java method for this purpose with dynamic character

public String insertSpace(String myString,int indexno,char myChar){
    myString=myString.substring(0, indexno)+ myChar+myString.substring(indexno);
    return myString;

CSS performance relative to translateZ(0)

I can attest to the fact that -webkit-transform: translate3d(0, 0, 0); will mess with the new position: -webkit-sticky; property. With a left drawer navigation pattern that I was working on, the hardware acceleration I wanted with the transform property was messing with the fixed positioning of my top nav bar. I turned off the transform and the positioning worked fine.

Luckily, I seem to have had hardware acceleration on already, because I had -webkit-font-smoothing: antialiased on the html element. I was testing this behavior in iOS7 and Android.

HTTP 1.0 vs 1.1

? HTTP 1.0 (1994)

  • It is still in use
  • Can be used by a client that cannot deal with chunked (or compressed) server replies

? HTTP 1.1 (1996- 2015)

  • Formalizes many extensions to version 1.0
  • Supports persistent and pipelined connections
  • Supports chunked transfers, compression/decompression
  • Supports virtual hosting (a server with a single IP Address hosting multiple domains)
  • Supports multiple languages
  • Supports byte-range transfers; useful for resuming interrupted data transfers

HTTP 1.1 is an enhancement of HTTP 1.0. The following lists the four major improvements:

  1. Efficient use of IP addresses, by allowing multiple domains to be served from a single IP address.

  2. Faster response, by allowing a web browser to send multiple requests over a single persistent connection.

  3. Faster response for dynamically-generated pages, by support for chunked encoding, which allows a response to be sent before its total length is known.
  4. Faster response and great bandwidth savings, by adding cache support.

Missing artifact com.sun:tools:jar

I ran into the same problem and the way I was able to resolve it was add the dependency location of tools.jar into the pom.xml. Like so:

   <systemPath>C:\Program Files\Java\jdk1.6.0_29\lib\tools.jar</systemPath>

Make sure you change the <systemPath> to where ever your tools.jar file is located.

MySQL Error: #1142 - SELECT command denied to user

This error happened on my server when I imported a view with an invalid definer.

Removing the faulty view fixed the error.

The error message didn't say anything about the view in question, but was "complaining" about one of the tables, that was used in the view.

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)


enter image description here

SQL Server Script to create a new user


Use MyDatabase;

IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'AdminLOGIN')
    EXEC sp_addrolemember N'db_owner', N'AdminLOGIN'
    EXEC master..sp_addsrvrolemember @loginame = N'adminlogin', @rolename = N'sysadmin'

this full help you for network using:

1- Right-click on SQL Server instance at root of Object Explorer, click on Properties
Select Security from the left pane.

2- Select the SQL Server and Windows Authentication mode radio button, and click OK.

3- Right-click on the SQL Server instance, select Restart (alternatively, open up Services and restart the SQL Server service).

4- Close sql server application and reopen it

5- open 'SQL Server Configuration Manager' and tcp enabled for network

6-Double-click the TCP/IP protocol, go to the IP Addresses tab and scroll down to the IPAll section.

7-Specify the 1433 in the TCP Port field (or another port if 1433 is used by another MSSQL Server) and press the OK 

8-Open in Sql Server: Security And Login  And Right Click on Login Name And Select Peroperties And Select Server Roles And 
  Checked The Sysadmin And Bulkadmin then Ok.
9-firewall: Open cmd as administrator and type: 
      netsh firewall set portopening protocol = TCP port = 1433 name = SQLPort mode = ENABLE scope = SUBNET profile = CURRENT

How to join three table by laravel eloquent model


$articles = DB::table('articles')
            ->select(' as articles_id', ..... )
            ->join('categories', 'articles.categories_id', '=', '')
            ->join('users', 'articles.user_id', '=', '')


PHP date() format when inserting into datetime in MySQL

$date_old = '23-5-2016 23:15:23'; 
//Date for database
$date_for_database = date ('Y-m-d H:i:s'", strtotime($date_old));

//Format should be like 'Y-m-d H:i:s'`enter code here`

Postman: How to make multiple requests at the same time

Not sure if people are still looking for simple solutions to this, but you are able to run multiple instances of the "Collection Runner" in Postman. Just create a runner with some requests and click the "Run" button multiple times to bring up multiple instances.

Difference between Mutable objects and Immutable objects

Mutable objects can have their fields changed after construction. Immutable objects cannot.

public class MutableClass {

 private int value;

 public MutableClass(int aValue) {
  value = aValue;

 public void setValue(int aValue) {
  value = aValue;

 public getValue() {
  return value;


public class ImmutableClass {

 private final int value;
 // changed the constructor to say Immutable instead of mutable
 public ImmutableClass (final int aValue) {
  //The value is set. Now, and forever.
  value = aValue;

 public final getValue() {
  return value;


How do I pass a class as a parameter in Java?

Class as paramater. Example.

Three classes:

class TestCar {

    private int UnlockCode = 111;
    protected boolean hasAirCondition = true;
    String brand = "Ford";
    public String licensePlate = "Arizona 111";


class Terminal {

public void hackCar(TestCar car) {


class Story {

    public static void main(String args[]) {
        TestCar testCar = new TestCar();
        Terminal terminal = new Terminal();


In class Terminal method hackCar() take class TestCar as parameter.

VBA paste range

I would try

Set Ticker = Range(Cells(2, 1), Cells(65, 1))


How can I set an SQL Server connection string?

They are a number of things to worry about when connecting to SQL Server on another machine.

  • Host/IP address of the machine
  • Initial catalog (database name)
  • Valid username/password

Very often SQL Server may be running as a default instance which means you can simply specify the hostname/IP address, but you may encounter a scenario where it is running as a named instance (SQL Server Express Edition for instance). In this scenario you'll have to specify the hostname/instance name.

How to set custom favicon in Express?

If you are using Express.static to serve a folder, just put the favicon.ico file in the root of that folder and it will be served when the browser requests it. There's no need to add a link tag to your html or a special middleware route in the application code.

If you're behind a reverse proxy, you may need to specify the media/mime type for the file (here's how in IIS) but if you navigate directly to your app it "just works".

Find and replace - Add carriage return OR Newline

You can also try \x0d\x0a in the "Replace with" box with "Use regular Expression" box checked to get carriage return + line feed using Visual Studio Find/Replace. Using \n (line feed) is the same as \x0a

How to read a large file line by line?

I would strongly recommend not using the default file loading as it is horrendously slow. You should look into the numpy functions and the IOpro functions (e.g. numpy.loadtxt()).

Then you can break your pairwise operation into chunks:

import numpy as np
import math

lines_total = n    
similarity = np.zeros(n,n)
lines_per_chunk = m
n_chunks = math.ceil(float(n)/m)
for i in xrange(n_chunks):
    for j in xrange(n_chunks):
        chunk_i = (function of your choice to read lines i*lines_per_chunk to (i+1)*lines_per_chunk)
        chunk_j = (function of your choice to read lines j*lines_per_chunk to (j+1)*lines_per_chunk)
                   j*lines_per_chunk:(j+1)*lines_per_chunk] = fast_operation(chunk_i, chunk_j) 

It's almost always much faster to load data in chunks and then do matrix operations on it than to do it element by element!!

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

Plotting images side by side using matplotlib

If the images are in an array and you want to iterate through each element and print it, you can write the code as follows:

plt.figure(figsize=(10,10)) # specifying the overall grid size

for i in range(25):
    plt.subplot(5,5,i+1)    # the number of images in the grid is 5*5 (25)

Also note that I used subplot and not subplots. They're both different

SQL: How to to SUM two values from different tables

you can also try this in sql-server !!

select, + as mytotal from [dbo].[cash] a join [dbo].[cheque] b on 


or try using sum,union

select sum(total)  as mytotal,city
    select * from cash union
    select * from cheque
) as vij
group by city 

Run a JAR file from the command line and specify classpath

When you specify -jar then the -cp parameter will be ignored.

From the documentation:

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

You also cannot "include" needed jar files into another jar file (you would need to extract their contents and put the .class files into your jar file)

You have two options:

  1. include all jar files from the lib directory into the manifest (you can use relative paths there)
  2. Specify everything (including your jar) on the commandline using -cp:
    java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main

Git push rejected after feature branch rebase

I would do as below

rebase feature
git checkout -b feature2 origin/feature
git push -u origin feature2:feature2
Delete the old remote branch feature
git push -u origin feature:feature

Now the remote will have feature(rebased on latest master) and feature2(with old master head). This would allow you to compare later if you have done mistakes in reolving conflicts.

How to get different colored lines for different plots in a single figure?

I would like to offer a minor improvement on the last loop answer given in the previous post (that post is correct and should still be accepted). The implicit assumption made when labeling the last example is that plt.label(LIST) puts label number X in LIST with the line corresponding to the Xth time plot was called. I have run into problems with this approach before. The recommended way to build legends and customize their labels per matplotlibs documentation ( is to have a warm feeling that the labels go along with the exact plots you think they do:

# Plot several different functions...
labels = []
plotHandles = []
for i in range(1, num_plots + 1):
    x, = plt.plot(some x vector, some y vector) #need the ',' per ** below
    labels.append(some label)
plt.legend(plotHandles, labels, 'upper left',ncol=1)

**: Matplotlib Legends not working

How do I select the "last child" with a specific class name in CSS?

You can use the adjacent sibling selector to achieve something similar, that might help.

.list-item.other-class + .list-item:not(.other-class)

Will effectively target the immediately following element after the last element with the class other-class.

Read more here:

How to return a 200 HTTP Status Code from ASP.NET MVC 3 controller

In your controller you'd return an HttpStatusCodeResult like this...

public ActionResult SomeMethod(...your method parameters go here...)
   // todo: put your processing code here

   //If not using MVC5
   return new HttpStatusCodeResult(200);

   //If using MVC5
   return new HttpStatusCodeResult(HttpStatusCode.OK);  // OK = 200

Looping Over Result Sets in MySQL

Use cursors.

A cursor can be thought of like a buffered reader, when reading through a document. If you think of each row as a line in a document, then you would read the next line, perform your operations, and then advance the cursor.

Converting dict to OrderedDict

You are creating a dictionary first, then passing that dictionary to an OrderedDict. For Python versions < 3.6 (*), by the time you do that, the ordering is no longer going to be correct. dict is inherently not ordered.

Pass in a sequence of tuples instead:

ship = [("NAME", "Albatross"),
        ("HP", 50),
        ("BLASTERS", 13),
        ("THRUSTERS", 18),
        ("PRICE", 250)]
ship = collections.OrderedDict(ship)

What you see when you print the OrderedDict is it's representation, and it is entirely correct. OrderedDict([('PRICE', 250), ('HP', 50), ('NAME', 'Albatross'), ('BLASTERS', 13), ('THRUSTERS', 18)]) just shows you, in a reproducable representation, what the contents are of the OrderedDict.

(*): In the CPython 3.6 implementation, the dict type was updated to use a more memory efficient internal structure that has the happy side effect of preserving insertion order, and by extension the code shown in the question works without issues. As of Python 3.7, the Python language specification has been updated to require that all Python implementations must follow this behaviour. See this other answer of mine for details and also why you'd still may want to use an OrderedDict() for certain cases.

Why is setTimeout(fn, 0) sometimes useful?

setTimout on 0 is also very useful in the pattern of setting up a deferred promise, which you want to return right away:

myObject.prototype.myMethodDeferred = function() {
    var deferredObject = $.Deferred();
    var that = this;  // Because setTimeout won't work right with this
    setTimeout(function() { 
        return, deferredObject);
    }, 0);
    return deferredObject.promise();

Serializing list to JSON

You can use pure Python to do it:

import json
list = [1, 2, (3, 4)] # Note that the 3rd element is a tuple (3, 4)
json.dumps(list) # '[1, 2, [3, 4]]'

Darken background image on hover

Just try this code.

    box-shadow: 0 25px 50px -25px rgba(0, 0, 0, .5) inset; 
    -webkit-box-shadow: 0 25px 50px -25px rgba(0, 0, 0, .5) inset; 
    -moz-box-shadow: 0 25px 50px -25px rgba(0, 0, 0, .5) inset; 
    -o-box-shadow: 0 25px 50px -25px rgba(0, 0, 0, .5) inset;

Calculating time difference between 2 dates in minutes

Try this one:

select * from MyTab T where date_add(T.runTime, INTERVAL 20 MINUTE) < NOW()

NOTE: this should work if you're using MySQL DateTime format. If you're using Unix Timestamp (integer), then it would be even easier:

select * from MyTab T where UNIX_TIMESTAMP() - T.runTime > 20*60

UNIX_TIMESTAMP() function returns you current unix timestamp.

Android: keeping a background service alive (preventing process death)

Keep your service footprint small, this reduces the probability of Android closing your application. You can't prevent it from being killed because if you could then people could easily create persistent spyware

Read XML file using javascript

You can use below script for reading child of the above xml. It will work with IE and Mozila Firefox both.

<script type="text/javascript">

function readXml(xmlFile){

var xmlDoc;

if(typeof window.DOMParser != "undefined") {
    xmlhttp=new XMLHttpRequest();"GET",xmlFile,false);
    if (xmlhttp.overrideMimeType){
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var tagObj=xmlDoc.getElementsByTagName("marker");
var typeValue = tagObj[0].getElementsByTagName("type")[0].childNodes[0].nodeValue;
var titleValue = tagObj[0].getElementsByTagName("title")[0].childNodes[0].nodeValue;

How to retrieve inserted id after inserting row in SQLite using Python?

You could use cursor.lastrowid (see "Optional DB API Extensions"):

cursor.execute('''CREATE TABLE foo (id integer primary key autoincrement ,
                                    username varchar(50),
                                    password varchar(50))''')
cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
# 1

If two people are inserting at the same time, as long as they are using different cursors, cursor.lastrowid will return the id for the last row that cursor inserted:

cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',

cursor2.execute('INSERT INTO foo (username,password) VALUES (?,?)',

# 3
# 2

cursor.execute('INSERT INTO foo (id,username,password) VALUES (?,?,?)',
# 100

Note that lastrowid returns None when you insert more than one row at a time with executemany:

cursor.executemany('INSERT INTO foo (username,password) VALUES (?,?)',
# None

How do I write a method to calculate total cost for all items in an array?

In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like

float total;
total += theItem.getUnits() * theItem.getPrice();

total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.

How to include Javascript file in Asp.Net page

Probably the file is not in the path specified. '../../../' will move 3 step up to the directory in which the page is located and look for the js file in a folder named JS.

Also the language attribute is Deprecated.

See Scripts:

18.2.1 The SCRIPT element

language = cdata [CI]

Deprecated. This attribute specifies the scripting language of the contents of this element. Its value is an identifier for the language, but since these identifiers are not standard, this attribute has been deprecated in favor of type.


Try changing

<script src="../../../JS/Registration.js" language="javascript" type="text/javascript" /> 


<script src="../../../JS/Registration.js" language="javascript" type="text/javascript"></script>

How to animate GIFs in HTML document?


<img src="" alt="this slowpoke moves"  width="250" alt="404 image"/>

and switch the src with your source. If the alt pops up, try a different url. If it doesn't work, restart your computer or switch your browser.

Border around each cell in a range

You can also include this task within another macro, without opening a new one:

I don't put Sub and end Sub, because the macro contains much longer code, as per picture below

With Sheets("1_PL").Range("EF1631:JJ1897")
    With .Borders
    .LineStyle = xlContinuous
    .Color = vbBlack
    .Weight = xlThin
    End With
[![enter image description here][1]][1]End With

Remove Item in Dictionary based on Value

In my case I use this

  var key=dict.FirstOrDefault(m => m.Value == s).Key;

How to change the application launcher icon on Flutter?

Setting the launcher icons like a native developer

I was having some trouble using and understanding the flutter_launcher_icons package. This answer is how you would do it if you were creating an app for Android or iOS natively. It is pretty fast and easy once you have done it a few times.


Android launcher icons have both a foreground and a background layer.

enter image description here

(image adapted from Android documentation)

The easiest way to create launcher icons for Android is to use the Asset Studio that is available right in Android Studio. You don't even have to leave your Flutter project. (VS Code users, you might consider using Android Studio just for this step. It's really very convenient and it doesn't hurt to be familiar with another IDE.)

Right click on the android folder in the project outline. Go to New > Image Asset. (Try right clicking the android/app folder if you don't see Image Asset as an option. Also see the comments below for more suggestions.) Now you can select an image to create your launcher icon from.

Note: I usually use a 1024x1024 pixel image but you should certainly use nothing smaller that 512x512. If you are using Gimp or Inkscape, you should have two layers, one for the foreground and one for the background. The foreground image should have transparent areas for the background layer to show through.

enter image description here

(lion clipart from here)

This will replace the current launcher icons. You can find the generated icons in the mipmap folders:

If you would prefer to create the launcher icons manually, see this answer for help.

Finally, make sure that the launcher icon name in the AndroidManifest is the same as what you called it above (ic_launcher by default):

application android:icon="@mipmap/ic_launcher"

Run the app in the emulator to confirm that the launcher icon was created successfully.


I always used to individually resize my iOS icons by hand, but if you have a Mac, there is a free app in the Mac App Store called Icon Set Creator. You give it an image (of at least 1024x1024 pixels) and it will spit out all the sizes that you need (plus the Contents.json file). Thanks to this answer for the suggestion.

iOS icons should not have any transparency. See more guidelines here.

After you have created the icon set, start Xcode (assuming you have a Mac) and use it to open the ios folder in your Flutter project. Then go to Runner > Assets.xcassets and delete the AppIcon item.

enter image description here

After that right-click and choose Import.... Choose the icon set that you just created.

That's it. Confirm that the icon was created by running the app in the simulator.

If you don't have a Mac...

You can still create all of the images by hand. In your Flutter project go to ios/Runner/Assets.xcassets/AppIcon.appiconset.

The image sizes that you need are the multiplied sizes in the filename. For example, [email protected] would be 29 times 3, that is, 87 pixels square. You either need to keep the same icon names or edit the JSON file.

SQL Server Format Date DD.MM.YYYY HH:MM:SS


javascript onclick increment number

var i=0; 
function increment() {           

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

For me closing all other Android Studio solved the problem.

I had opened 3 android studios when I was getting the error, after I closed 2 I didn't get any error.

No need to add any code related to multiDex !

MySQL, Check if a column exists in a table with SQL

Many thanks to Mfoo who has put the really nice script for adding columns dynamically if not exists in the table. I have improved his answer with PHP. The script additionally helps you find how many tables actually needed 'Add column' mysql comand. Just taste the recipe. Works like charm.

ini_set('max_execution_time', 0);

$host = 'localhost';
$username = 'root';
$password = '';
$database = 'books';

$con = mysqli_connect($host, $username, $password);
if(!$con) { echo "Cannot connect to the database ";die();}
mysqli_select_db($con, $database);
$result=mysqli_query($con, 'show tables');
$tableArray = array();
while($tables = mysqli_fetch_row($result)) 
     $tableArray[] = $tables[0];    

$already = 0;
$new = 0;
for($rs = 0; $rs < count($tableArray); $rs++)
    $exists = FALSE;

    $result = mysqli_query($con, "SHOW COLUMNS FROM ".$tableArray[$rs]." LIKE 'tags'");
    $exists = (mysqli_num_rows($result))?TRUE:FALSE;

    if($exists == FALSE)
        mysqli_query($con, "ALTER TABLE ".$tableArray[$rs]." ADD COLUMN tags VARCHAR(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL");
        echo '#'.$new.' Table DONE!<br/>';
        echo '#'.$already.' Field defined alrady!<br/>';    
    echo '<br/>';

Make Bootstrap Popover Appear/Disappear on Hover instead of Click

If you want to hover the popover itself as well you have to use a manual trigger.

This is what i came up with:

function enableThumbPopover() {
    var counter;

        trigger: 'manual',
        animation: false,
        html: true,
        title: function () {
            return $(this).parent().find('.thumbPopover > .title').html();
        content: function () {
            return $(this).parent().find('.thumbPopover > .body').html();
        container: 'body',
        placement: 'auto'
    }).on("mouseenter",function () {
        var _this = this; // thumbcontainer

        console.log('thumbcontainer mouseenter')
        // clear the counter
        // Close all other Popovers

        // start new timeout to show popover
        counter = setTimeout(function(){
            $(".popover").on("mouseleave", function () {
        }, 400);

    }).on("mouseleave", function () {
        var _this = this;

        setTimeout(function () {
            if (!$(".popover:hover").length) {
                if(!$(_this).is(':hover')) // change $(this) to $(_this) 
        }, 200);

Add common prefix to all cells in Excel

Type this in cell B1, and copy down...


This would also work:


And here's one of many ways to do this in VBA (Disclaimer: I don't code in VBA very often!):

Sub AddX()
    Dim i As Long

    With ActiveSheet
    For i = 1 To .Range("A65536").End(xlUp).Row Step 1
        .Cells(i, 2).Value = "X" & Trim(Str(.Cells(i, 1).Value))
    Next i
    End With
End Sub

Server returned HTTP response code: 401 for URL: https

401 means "Unauthorized", so there must be something with your credentials.

I think that java URL does not support the syntax you are showing. You could use an Authenticator instead.

Authenticator.setDefault(new Authenticator() {

    protected PasswordAuthentication getPasswordAuthentication() {          
        return new PasswordAuthentication(login, password.toCharArray());

and then simply invoking the regular url, without the credentials.

The other option is to provide the credentials in a Header:

String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);

PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.

How do I convert between big-endian and little-endian values in C++?

If you have C++ 17 then add this header

#include <algorithm>

Use this template function to swap the bytes:

template <typename T>
void swapEndian(T& buffer)
    static_assert(std::is_pod<T>::value, "swapEndian support POD type only");
    char* startIndex = static_cast<char*>((void*);
    char* endIndex = startIndex + sizeof(buffer);
    std::reverse(startIndex, endIndex);

call it like:

swapEndian (stlContainer);

What is the difference between Collection and List in Java?

List and Set are two subclasses of Collection.

In List, data is in particular order.

In Set, it can not contain the same data twice.

In Collection, it just stores data with no particular order and can contain duplicate data.

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

If you are having problems with Silverlight projects the solution can be fairly simple. According to my experience in many cases debugging symbols are not being loaded due to the new ".xap" files not being deployed to temporary folder (either internal VS Cassini or IIS Express). In this situation full rebuilds or resetting VS settings won't help. The easiest solution is just to delete temporary internet files within your browser. If you are using IE for Silverlight development and testing I would recommend switching on "Delete browsing history on exit" option in order not to have such issues in the future.

How to launch an EXE from Web page (

Are you saying that you are having trouble inserting into a web page a link to a file that happens to have a .exe extension?

If that is the case, then take one step back. Imagine the file has a .htm extension, or a .css extension. How can you make that downloadable? If it is a static link, then the answer is clear: the file needs to be in the docroot for the ASP.NET app. IIS + ASP.NET serves up many kinds of content: .htm files, .css files, .js files, image files, implicitly. All these files are somewhere under the docroot, which by default is c:\inetpub\wwwroot, but for your webapp is surely something different. The fact that the file you want to expose has an .exe extension does not change the basic laws of IIS physics. The exe has to live under the docroot. The network share thing might work for some browsers.

The alternative of course is to dynamically write the content of the file directly to the Response.OutputStream. This way you don't need the .exe to be in your docroot, but it is not a direct download link. In this scenario, the file might be downloaded by a button click.

Something like this:

    string FullPathFilename = "\\\\server\\share\\CorpApp1.exe";
    string archiveName= System.IO.Path.GetFileName(FullPathFilename);
    Response.ContentType = "application/octet-stream";
    Response.AddHeader("content-disposition", "filename=" + archiveName);

How do I get the current date and time in PHP?

echo("<p class='time'>".date('H:i:s')."</p>");
echo("<p class='date'>".date('d/m/Y')."</p>");

Facebook Architecture

Facebook is using LAMP structure. Facebook’s back-end services are written in a variety of different programming languages including C++, Java, Python, and Erlang and they are used according to requirement. With LAMP Facebook uses some technologies ,to support large number of requests, like

  1. Memcache - It is a memory caching system that is used to speed up dynamic database-driven websites (like Facebook) by caching data and objects in RAM to reduce reading time. Memcache is Facebook’s primary form of caching and helps alleviate the database load. Having a caching system allows Facebook to be as fast as it is at recalling your data.

  2. Thrift (protocol) - It is a lightweight remote procedure call framework for scalable cross-language services development. Thrift supports C++, PHP, Python, Perl, Java, Ruby, Erlang, and others.

  3. Cassandra (database) - It is a database management system designed to handle large amounts of data spread out across many servers.

  4. HipHop for PHP - It is a source code transformer for PHP script code and was created to save server resources. HipHop transforms PHP source code into optimized C++. After doing this, it uses g++ to compile it to machine code.

If we go into more detail, then answer to this question go longer. We can understand more from following posts:

  1. How Does Facebook Work?
  2. Data Management, Facebook-style
  3. Facebook database design?
  4. Facebook wall's database structure
  5. Facebook "like" data structure

How to paste into a terminal?

Shift + Insert usually works throughout X11.

Resource files not found from JUnit test cases

You know that Maven is based on the Convention over Configuration pardigm? so you shouldn't configure things which are the defaults.

All that stuff represents the default in Maven. So best practice is don't define it it's already done.


Select Row number in postgres

SELECT tab.*,
    row_number() OVER () as rnum
  FROM tab;

Here's the relevant section in the docs.

P.S. This, in fact, fully matches the answer in the referenced question.

What values for checked and selected are false?

The empty string is false as a rule.

Apparently the empty string is not respected as empty in all browsers and the presence of the checked attribute is taken to mean checked. So the entire attribute must either be present or omitted.

How to write a basic swap function in Java

Java is pass by value. So the swap in the sense you mean is not possible. But you can swap contents of two objects or you do it inline.

Change the background color in a twitter bootstrap modal?

I used couple of hours trying to figure how to remove background from launched modal, so far tried

.modal-backdrop {    background: none; }

Didn't work even I have tried to work with javascript like

 <script type="text/javascript">   
 $('#modal-id').on('',  function () {
       $("").hide();     })

Also didn't work either. I just added



<div class="modal fade" id="myModal" data-backdrop="false">......</div>

And Applying css CLASS

.modal {     background-color: transparent !important;  }

Now its working like a charm This worked with Bootstrap 3

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)


You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

Linux Shell Script For Each File in a Directory Grab the filename and execute a program


for f in *.xls ; do xls2csv "$f" "${f%.xls}.csv" ; done

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

You have to use Javascript Filereader for this. (Introduction into filereader-api:

Once the user have choose a image you can read the file-path of the chosen image and place it into your html.


<form id="form1" runat="server">
    <input type='file' id="imgInp" />
    <img id="blah" src="#" alt="your image" />


function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {



How to stop BackgroundWorker correctly

MY example . DoWork is below:


    //this is never executed
        MessageBox.Show("Up to here? ...");
        e.Cancel = true;

inside DoLenghtyWork :

public void DoLenghtyWork()
    for(int i=0 ; i<10000000; i++) 
    {  int j = i/3; }

inside OtherStuff() :

public void OtherStuff()
    for(int i=0 ; i<10000000; i++) 
    {  int j = i/3; }

What you want to do is modify both DoLenghtyWork and OtherStuff() so that they become:

public void DoLenghtyWork()
        for(int i=0 ; i<10000000; i++) 
             int j = i/3; 

public void OtherStuff()
        for(int i=0 ; i<10000000; i++) 
            int j = i/3; 

PHP function to make slug (URL string)

Note: I have taken this from wordpress and it works!!

Use it like this:

echo sanitize('testing this link');


//taken from wordpress
function utf8_uri_encode( $utf8_string, $length = 0 ) {
    $unicode = '';
    $values = array();
    $num_octets = 1;
    $unicode_length = 0;

    $string_length = strlen( $utf8_string );
    for ($i = 0; $i < $string_length; $i++ ) {

        $value = ord( $utf8_string[ $i ] );

        if ( $value < 128 ) {
            if ( $length && ( $unicode_length >= $length ) )
            $unicode .= chr($value);
        } else {
            if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;

            $values[] = $value;

            if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
            if ( count( $values ) == $num_octets ) {
                if ($num_octets == 3) {
                    $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
                    $unicode_length += 9;
                } else {
                    $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
                    $unicode_length += 6;

                $values = array();
                $num_octets = 1;

    return $unicode;

//taken from wordpress
function seems_utf8($str) {
    $length = strlen($str);
    for ($i=0; $i < $length; $i++) {
        $c = ord($str[$i]);
        if ($c < 0x80) $n = 0; # 0bbbbbbb
        elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
        elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
        elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
        elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
        elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
        else return false; # Does not match any model
        for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
            if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
                return false;
    return true;

//function sanitize_title_with_dashes taken from wordpress
function sanitize($title) {
    $title = strip_tags($title);
    // Preserve escaped octets.
    $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
    // Remove percent signs that are not part of an octet.
    $title = str_replace('%', '', $title);
    // Restore octets.
    $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);

    if (seems_utf8($title)) {
        if (function_exists('mb_strtolower')) {
            $title = mb_strtolower($title, 'UTF-8');
        $title = utf8_uri_encode($title, 200);

    $title = strtolower($title);
    $title = preg_replace('/&.+?;/', '', $title); // kill entities
    $title = str_replace('.', '-', $title);
    $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
    $title = preg_replace('/\s+/', '-', $title);
    $title = preg_replace('|-+|', '-', $title);
    $title = trim($title, '-');

    return $title;

Where to find Application Loader app in Mac?

For anyone finding this now (23/09/2019) Application Loader has been removed from Xcode.

If you have built the application in Xcode you should be able to follow these instructions to upload your and distribute your project Upload an app

I am not sure what to do if you have been given a .ipa file, for example when building an Expo project, I'll update this post when i have an answer.

In the mean time more info can be found here. Developer Apple - Whats new

Import Script from a Parent Directory

If you want to run the script directly, you can:

  1. Add the FolderA's path to the environment variable (PYTHONPATH).
  2. Add the path to sys.path in the your script.


import module_you_wanted

DB2 Timestamp select statement

@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000

If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:

...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'


...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06' 
   AND usagetime < '2012-09-03 08:03:07'

How to get N rows starting from row M from sorted table in T-SQL

Ugly, hackish, but should work:

select top(M + N - 1) * from TableName
select top(N - 1) * from TableName

How do I change TextView Value inside Java Code?

First we need to find a Button:

Button mButton = (Button) findViewById(;

After that, you must implement View.OnClickListener and there you should find the TextView and execute the method setText:

mButton.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
        final TextView mTextView = (TextView) findViewById(;
        mTextView.setText("Some Text");

How to customize <input type="file">?

Easiest way..

    <input type="file" style="visibility: hidden;"/>

How do I restrict an input to only accept numbers?


directive('decimal', function() {
                return {
                    require: 'ngModel',
                    restrict: 'A',
                    link: function(scope, element, attr, ctrl) {
                        function inputValue(val) {
                            if (val) {
                                var digits = val.replace(/[^0-9.]/g, '');

                                if (digits.split('.').length > 2) {
                                    digits = digits.substring(0, digits.length - 1);

                                if (digits !== val) {
                                return parseFloat(digits);
                            return "";


directive('entero', function() {
            return {
                require: 'ngModel',
                restrict: 'A',
                link: function(scope, element, attr, ctrl) {
                    function inputValue(val) {
                        if (val) {
                            var value = val + ''; //convert to string
                            var digits = value.replace(/[^0-9]/g, '');

                            if (digits !== value) {
                            return parseInt(digits);
                        return "";

angular directives for validate numbers

Push method in React Hooks (useState)?

The same way you do it with "normal" state in React class components.


function App() {
  const [state, setState] = useState([]);

  return (
      <p>You clicked {state.join(" and ")}</p>
      <button onClick={() => setState([...state, "again"])}>Click me</button>
      //old way
      <button onClick={() => setState(state.concat("again"))}>Click me</button>

Passing a varchar full of comma delimited values to a SQL Server IN function

Without using dynamic SQL, you have to take the input variable and use a split function to put the data into a temp table and then join to that.

Get only specific attributes with from Laravel Collection

You can do this using a combination of existing Collection methods. It may be a little hard to follow at first, but it should be easy enough to break down.

// get your main collection with all the attributes...
$users = Users::get();

// build your second collection with a subset of attributes. this new
// collection will be a collection of plain arrays, not Users models.
$subset = $users->map(function ($user) {
    return collect($user->toArray())
        ->only(['id', 'name', 'email'])


First, the map() method basically just iterates through the Collection, and passes each item in the Collection to the passed in callback. The value returned from each call of the callback builds the new Collection generated by the map() method.

collect($user->toArray()) is just building a new, temporary Collection out of the Users attributes.

->only(['id', 'name', 'email']) reduces the temporary Collection down to only those attributes specified.

->all() turns the temporary Collection back into a plain array.

Put it all together and you get "For each user in the users collection, return an array of just the id, name, and email attributes."

Laravel 5.5 update

Laravel 5.5 added an only method on the Model, which basically does the same thing as the collect($user->toArray())->only([...])->all(), so this can be slightly simplified in 5.5+ to:

// get your main collection with all the attributes...
$users = Users::get();

// build your second collection with a subset of attributes. this new
// collection will be a collection of plain arrays, not Users models.
$subset = $users->map(function ($user) {
    return $user->only(['id', 'name', 'email']);

If you combine this with the "higher order messaging" for collections introduced in Laravel 5.4, it can be simplified even further:

// get your main collection with all the attributes...
$users = Users::get();

// build your second collection with a subset of attributes. this new
// collection will be a collection of plain arrays, not Users models.
$subset = $users->map->only(['id', 'name', 'email']);

Populating a ComboBox using C#

What you could do is create a new class, similar to @Gregoire's example, however, you would want to override the ToString() method so it appears correctly in the combo box e.g.

public class Language
    private string _name;
    private string _code;

    public Language(string name, string code)
        _name = name;
        _code = code;

    public string Name { get { return _name; }  }
    public string Code { get { return _code; } }
    public override void ToString()
        return _name;

Are these methods thread safe?

The only problem with threads is accessing the same object from different threads without synchronization.

If each function only uses parameters for reading and local variables, they don't need any synchronization to be thread-safe.

How to start new activity on button click


Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters

Extras are retrieved on the other side via:

protected void onCreate(Bundle savedInstanceState) {
    Intent intent = getIntent();
    String value = intent.getStringExtra("key"); //if it's a string you stored.

Don't forget to add your new activity in the AndroidManifest.xml:

<activity android:label="@string/app_name" android:name="NextActivity"/>

How to discover number of *logical* cores on Mac OS X?

Use the system_profiler | grep "Cores" command.

I have a:

MacBook Pro Retina, Mid 2012.

Processor: 2.6 GHz Intel Core i7

user$ system_profiler | grep "Cores"
      Total Number of Cores: 4

user$ sysctl -n hw.ncpu

According to Wikipedia, ( there is no Core i7 with 8 physical cores so the Hyperthreading idea must be the case. Ignore sysctl and use the system_profiler value for accuracy. The real question is whether or not you can efficiently run applications with 4 cores (long compile jobs?) without interrupting other processes.

Running a compiler parallelized with 4 cores doesn't appear to dramatically affect regular OS operations. So perhaps treating it as 8 cores is not so bad.

How does MySQL process ORDER BY and LIMIT in a query?

You could add [asc] or [desc] at the end of the order by to get the earliest or latest records

For example, this will give you the latest records first


Append the LIMIT clause after ORDER BY

What is AF_INET, and why do I need it?

it defines the protocols address family.this determines the type of socket created. pocket pc support AF_INET.

the content in the following page is quite decent

How to change shape color dynamically?

This solution worked for me using the android sdk v19:

//get the image button by id
ImageButton myImg = (ImageButton) findViewById(;

//get drawable from image button
GradientDrawable drawable = (GradientDrawable) myImg.getDrawable();

//set color as integer
//can use Color.parseColor(color) if color is a string

Remove part of string after "."

We can pretend they are filenames and remove extensions:

# [1] "NM_020506"    "NM_020519"    "NM_001030297" "NM_010281"    "NM_011419"    "NM_053155"

How to detect idle time in JavaScript elegantly?

Just a few thoughts, an avenue or two to explore.

Is it possible to have a function run every 10 seconds, and have that check a "counter" variable? If that's possible, you can have an on mouseover for the page, can you not? If so, use the mouseover event to reset the "counter" variable. If your function is called, and the counter is above the range that you pre-determine, then do your action.

Again, just some thoughts... Hope it helps.

How to merge two sorted arrays into a sorted array?

Algorithm could be enhanced in many ways. For instance, it is reasonable to check, if a[m-1]<b[0] or b[n-1]<a[0]. In any of those cases, there is no need to do more comparisons. Algorithm could just copy source arrays in the resulting one in the right order.

More complicated enhancements may include searching for interleaving parts and run merge algorithm for them only. It could save up much time, when sizes of merged arrays differ in scores of times.

How to use custom packages

For this kind of folder structure:


The simplest way is to use this:

import (

How do I set combobox read-only or user cannot write in a combo box only can select the given items?

Just change the DropDownStyle to DropDownList. Or if you want it completely read only you can set Enabled = false, or if you don't like the look of that I sometimes have two controls, one readonly textbox and one combobox and then hide the combo and show the textbox if it should be completely readonly and vice versa.

Print very long string completely in pandas dataframe

The way I often deal with the situation you describe is to use the .to_csv() method and write to stdout:

import sys


Update: it should now be possible to just use None instead of sys.stdout with similar effect!

This should dump the whole dataframe, including the entirety of any strings. You can use the to_csv parameters to configure column separators, whether the index is printed, etc. It will be less pretty than rendering it properly though.

I posted this originally in answer to the somewhat-related question at Output data from all columns in a dataframe in pandas

Check if URL has certain string with PHP

Have a look at the strpos function:

if(false !== strpos($url,'car')) {
    echo 'Car exists!';
else {
    echo 'No cars.';

Difference between /res and /assets directories

I know this is old, but just to make it clear, there is an explanation of each in the official android documentation:



This is empty. You can use it to store raw asset files. Files that you save here are compiled into an .apk file as-is, and the original filename is preserved. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the AssetManager. For example, this is a good location for textures and game data.


For arbitrary raw asset files. Saving asset files here instead of in the assets/ directory only differs in the way that you access them. These files are processed by aapt and must be referenced from the application using a resource identifier in the R class. For example, this is a good place for media, such as MP3 or Ogg files.

Apple Cover-flow effect using jQuery or other library?

Try Jquery Interface Elements here -

Here's a sample.

I looked around for a Jquery image carousel a few months ago and didn't find a good one so I gave up. This one was the best I could find.

Creating a JSON response using Django and Python

In View use this:


for getting validation messages without html

PHP find difference between two datetimes

I'm not sure what format you're looking for in your difference but here's how to do it using DateTime

$datetime1 = new DateTime();
$datetime2 = new DateTime('2011-01-03 17:13:00');
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
echo $elapsed;

Sql query to insert datetime in SQL Server

you need to add it like

insert into table1(date1) values('12-mar-2013');

Is there a way to perform "if" in python's lambda

Probably the worst python line I've written so far:

f = lambda x: sys.stdout.write(["2\n",][2*(x==2)-2])

If x == 2 you print,

if x != 2 you raise.

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

Maybe a little late to reply. I happen to run into the same problem today. I find that on Windows you can change the console encoder to utf-8 or other encoder that can represent your data. Then you can print it to sys.stdout.

First, run following code in the console:

chcp 65001

Then, start python do anything you want.

How do you get the logical xor of two variables in Python?

  • Python logical or: A or B: returns A if bool(A) is True, otherwise returns B
  • Python logical and: A and B: returns A if bool(A) is False, otherwise returns B

To keep most of that way of thinking, my logical xor definintion would be:

def logical_xor(a, b):
    if bool(a) == bool(b):
        return False
        return a or b

That way it can return a, b, or False:

>>> logical_xor('this', 'that')
>>> logical_xor('', '')
>>> logical_xor('this', '')
>>> logical_xor('', 'that')

DbEntityValidationException - How can I easily tell what caused the error?

Actually, this is just the validation issue, EF will validate the entity properties first before making any changes to the database. So, EF will check whether the property's value is out of range, like when you designed the table. Table_Column_UserName is varchar(20). But, in EF, you entered a value that longer than 20. Or, in other cases, if the column does not allow to be a Null. So, in the validation process, you have to set a value to the not null column, no matter whether you are going to make the change on it. I personally, like the Leniel Macaferi answer. It can show you the detail of the validation issues

How to concatenate multiple column values into a single column in Panda dataframe

The answer given by @allen is reasonably generic but can lack in performance for larger dataframes:

Reduce does a lot better:

from functools import reduce

import pandas as pd

# make data
df = pd.DataFrame(index=range(1_000_000))
df['1'] = 'CO'
df['2'] = 'BOB'
df['3'] = '01'
df['4'] = 'BILL'

def reduce_join(df, columns):
    assert len(columns) > 1
    slist = [df[x].astype(str) for x in columns]
    return reduce(lambda x, y: x + '_' + y, slist[1:], slist[0])

def apply_join(df, columns):
    assert len(columns) > 1
    return df[columns].apply(lambda row:'_'.join(row.values.astype(str)), axis=1)

# ensure outputs are equal
df1 = reduce_join(df, list('1234'))
df2 = apply_join(df, list('1234'))
assert df1.equals(df2)

# profile
%timeit df1 = reduce_join(df, list('1234'))  # 733 ms
%timeit df2 = apply_join(df, list('1234'))   # 8.84 s

Best practices with STDIN in Ruby?

It seems most answers are assuming the arguments are filenames containing content to be cat'd to the stdin. Below everything is treated as just arguments. If STDIN is from the TTY, then it is ignored.

$ cat tstarg.rb

while a=(ARGV.shift or (!STDIN.tty? and STDIN.gets) )
  puts a

Either arguments or stdin can be empty or have data.

$ cat numbers 
$ ./tstarg.rb a b c < numbers

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected]

Thanks to Vinod for the well presented answer.

I got the same error as Mick Byrne when I followed the steps above. Turning it back to All Unassigned sorted it but I had to tweak a few other things as well:

  • Add the user my site was running under to the users on the Security Tab in SMTP Virtual Server.
  • Changed the value in the mailSettings > network > host attribute in my web.config to the specific server IP (for example as opposed to localhost (which was pointing at in the hosts file).

Hope this saves someone a few mins of messing about.

Android emulator shows nothing except black screen and adb devices shows "device offline"

I had the same problem on API 28, and the fix turned out to be as below;

Enabling Skia rendering for Android UI

When using images for API 27 or later, the emulator can render the Android UI with Skia, which can render more smoothly and efficiently.

To enable Skia rendering, use the following commands in adb shell:

setprop debug.hwui.renderer skiagl

Zabbix server is not running: the information displayed may not be current

In my case i had to disable Linux SE

[root@webserverlocaldomain /]# setenforce 0

Disable Firewall

[root@webserverlocaldomain /]# systemctl stop firewalld

Edit config file uncommenting#

[root@webserverlocaldomain /]# vi /etc/zabbix/zabbix_server.conf


Then restart the services

[root@webserverlocaldomain /]# systemctl restart zabbix-server zabbix-agent httpd

PHP sessions default timeout

Yes, that's usually happens after 1440s (24 minutes)

Allow only numeric value in textbox using Javascript

Please note that, you should allow "system" key as well

    $(element).keydown(function (e) {
    var code = (e.keyCode ? e.keyCode : e.which), value;
    if (isSysKey(code) || code === 8 || code === 46) {
        return true;

    if (e.shiftKey || e.altKey || e.ctrlKey) {
        return ;

    if (code >= 48 && code <= 57) {
        return true;

    if (code >= 96 && code <= 105) {
        return true;

    return false;

function isSysKey(code) {
    if (code === 40 || code === 38 ||
            code === 13 || code === 39 || code === 27 ||
            code === 35 ||
            code === 36 || code === 37 || code === 38 ||
            code === 16 || code === 17 || code === 18 ||
            code === 20 || code === 37 || code === 9 ||
            (code >= 112 && code <= 123)) {
        return true;

    return false;

C++ unordered_map using a custom class type as the key

Most basic possible copy/paste complete runnable example of using a custom class as the key for an unordered_map (basic implementation of a sparse matrix):

// UnorderedMapObjectAsKey.cpp

#include <iostream>
#include <vector>
#include <unordered_map>

struct Pos
  int row;
  int col;

  Pos() { }
  Pos(int row, int col)
    this->row = row;
    this->col = col;

  bool operator==(const Pos& otherPos) const
    if (this->row == otherPos.row && this->col == otherPos.col) return true;
    else return false;

  struct HashFunction
    size_t operator()(const Pos& pos) const
      size_t rowHash = std::hash<int>()(pos.row);
      size_t colHash = std::hash<int>()(pos.col) << 1;
      return rowHash ^ colHash;

int main(void)
  std::unordered_map<Pos, int, Pos::HashFunction> umap;

  // at row 1, col 2, set value to 5
  umap[Pos(1, 2)] = 5;

  // at row 3, col 4, set value to 10
  umap[Pos(3, 4)] = 10;

  // print the umap
  std::cout << "\n";
  for (auto& element : umap)
    std::cout << "( " << element.first.row << ", " << element.first.col << " ) = " << element.second << "\n";
  std::cout << "\n";

  return 0;

Array Length in Java

If you want the logical size of the array, you can traverse all the values in the array and check them against zero. Increment the value if it is not zero and that would be the logical size. Because array size is fixed, you do not have any inbuilt method, may be you should have a look at collections.

Using File.listFiles with FileNameExtensionFilter

One-liner in java 8 syntax:

pdfTestDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".txt"));

How to add action listener that listens to multiple buttons

Using my approach, you can write the button click event handler in the 'classical way', just like how you did it in VB or MFC ;)

Suppose we have a class for a frame window which contains 2 buttons:

class MainWindow {
    Jbutton searchButton;
    Jbutton filterButton;

You can use my 'router' class to route the event back to your MainWindow class:

class MainWindow {
    JButton searchButton;
    Jbutton filterButton;
    ButtonClickRouter buttonRouter = new ButtonClickRouter(this);
    void initWindowContent() {
        // create your components here...
        // setup button listeners

    void on_searchButton() {
        // TODO your handler goes here...
    void on_filterButton() {
        // TODO your handler goes here...

Do you like it? :)

If you like this way and hate the Java's anonymous subclass way, then you are as old as I am. The problem of 'addActionListener(new ActionListener {...})' is that it squeezes all button handlers into one outer method which makes the programme look wired. (in case you have a number of buttons in one window)

Finally, the router class is at below. You can copy it into your programme without the need for any update.

Just one thing to mention: the button fields and the event handler methods must be accessible to this router class! To simply put, if you copy this router class in the same package of your programme, your button fields and methods must be package-accessible. Otherwise, they must be public.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ButtonClickRouter implements ActionListener {
    private Object target;

    ButtonClickRouter(Object target) { = target;

    public void actionPerformed(ActionEvent actionEvent) {
        // get source button
        Object sourceButton = actionEvent.getSource();

        // find the corresponding field of the button in the host class
        Field fieldOfSourceButton = null;
        for (Field field : target.getClass().getDeclaredFields()) {
            try {
                if (field.get(target).equals(sourceButton)) {
                    fieldOfSourceButton = field;
            } catch (IllegalAccessException e) {

        if (fieldOfSourceButton == null)

        // make the expected method name for the source button
        // rule: suppose the button field is 'searchButton', then the method
        // is expected to be 'void on_searchButton()'
        String methodName = "on_" + fieldOfSourceButton.getName();

        // find such a method
        Method expectedHanderMethod = null;
        for (Method method : target.getClass().getDeclaredMethods()) {
            if (method.getName().equals(methodName)) {
                expectedHanderMethod = method;

        if (expectedHanderMethod == null)

        // fire
        try {
        } catch (IllegalAccessException | InvocationTargetException e) { }

I'm a beginner in Java (not in programming), so maybe there are anything inappropriate in the above code. Review it before using it, please.

How can you program if you're blind?

NVDA is a good open source screen reader for win.

set up device for development (???????????? no permissions)

In my case on ubuntu 12.04 LTS, I had to change my HTC Incredible usb mode from charge to Media and then the device showed up under adb. Of course, debugging was already on in both cases.

Laravel - Eloquent or Fluent random row

I have table with thousands of records, so I need something fast. This is my code for pseudo random row:

// count all rows with flag active = 1
$count = MyModel::where('active', '=', '1')->count(); 

// get random id
$random_id = rand(1, $count - 1);  

// get first record after random id
$data = MyModel::where('active', '=', '1')->where('id', '>', $random_id)->take(1)->first(); 

Root password inside a Docker container

I am able to get it working with the below command.

root@gitnew:# docker exec -it --user $(username) $(containername) /bin/bash

HTTP requests and JSON parsing in Python

I recommend using the awesome requests library:

import requests

url = ''

params = dict(

resp = requests.get(url=url, params=params)
data = resp.json() # Check the JSON Response Content documentation below

JSON Response Content:

How to enable curl in xampp?

For XAMPP on MACOS or Linux, remove the semicolon in php.ini file after

How to sort a Ruby Hash by number value?

Since value is the last entry, you can do:


My docker container has no internet

I do not know what I am doing but that worked for me :

OTHER_BRIDGE=br-xxxxx # this is the other random docker bridge (`ip addr` to find)    
service docker stop

ip link set dev $OTHER_BRIDGE down
ip link set dev docker0 down
ip link delete $OTHER_BRIDGE type bridge
ip link delete docker0 type bridge
service docker start && service docker stop

iptables -t nat -A POSTROUTING ! -o docker0 -s -j MASQUERADE
iptables -t nat -A POSTROUTING ! -o docker0 -s -j MASQUERADE

service docker start

Retrieve specific commit from a remote Git repository

You can simply fetch a single commit of a remote repo with

git fetch <repo> <commit>


  • <repo> can be a remote repo name (e.g. origin) or even a remote repo URL (e.g.
  • <commit> can be the SHA1 commit

for example

git fetch 0a071603d87e0b89738599c160583a19a6d95545

after you fetched the commit (and the missing ancestors) you can simply checkout it with

git checkout FETCH_HEAD

Note that this will bring you in the "detached head" state.

How to escape apostrophe (') in MySql?

just write '' in place of ' i mean two times '

Algorithm: efficient way to remove duplicate integers from an array

Integer[] arrayInteger = {1,2,3,4,3,2,4,6,7,8,9,9,10}; 

Set set = new HashSet();
for(Integer i:arrayInteger)


Not class selector in jQuery

You need the :not() selector:


or, alternatively, the .not() method:


Gradients on UIView and UILabels On iPhone

I realize this is an older thread, but for future reference:

As of iPhone SDK 3.0, custom gradients can be implemented very easily, without subclassing or images, by using the new CAGradientLayer:

 UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)] autorelease];
 CAGradientLayer *gradient = [CAGradientLayer layer];
 gradient.frame = view.bounds;
 gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
 [view.layer insertSublayer:gradient atIndex:0];

Take a look at the CAGradientLayer docs. You can optionally specify start and end points (in case you don't want a linear gradient that goes straight from the top to the bottom), or even specific locations that map to each of the colors.

How to add "on delete cascade" constraints?

Based off of @Mike Sherrill Cat Recall's answer, this is what worked for me:

ALTER TABLE "Children"
DROP CONSTRAINT "Children_parentId_fkey",
ADD CONSTRAINT "Children_parentId_fkey"
  FOREIGN KEY ("parentId")
  REFERENCES "Parent"(id)

How to implement endless list with RecyclerView?

This is how I do it, simple and short:

    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
        public void onScrolled(RecyclerView recyclerView, int dx, int dy)
            if(!recyclerView.canScrollVertically(1) && dy != 0)
                // Load more results here


Apache shows PHP code instead of executing it

Wow, lots of solutions here! Here's what I did on Ubuntu 16.04:

sudo apt-get install php libapache2-mod-php
sudo a2enmod mpm_prefork && sudo a2enmod php7.0
sudo service apache2 restart

Update just one gem with bundler

bundle update gem-name [--major|--patch|--minor]

This also works for dependencies.

How can I change the remote/target repository URL on Windows?

One more way to do this is:

git config remote.origin.url

To see the existing URL just do:

git config remote.origin.url

How to get a list of sub-folders and their files, ordered by folder-names

dir /b /a-d /s *.* will fulfill your requirement.

starting file download with JavaScript

I have created an open source jQuery File Download plugin (Demo with examples) (GitHub) which could also help with your situation. It works pretty similarly with an iframe but has some cool features that I have found quite handy:

  • User never leaves the same page they initiated a file download from. This feature is becoming crucial for modern web applications
  • Tested cross browser support (including mobile!)
  • It supports POST and GET requests in a manner similar to jQuery's AJAX API
  • successCallback and failCallback functions allow for you to be explicit about what the user sees in either situation
  • In conjunction with jQuery UI a developer can easily show a modal telling the user that a file download is occurring, disband the modal after the download starts or even inform the user in a friendly manner that an error has occurred. See the Demo for an example of this.

JTable won't show column headers

As said in previous answers the 'normal' way is to add it to a JScrollPane, but sometimes you don't want it to scroll (don't ask me when:)). Then you can add the TableHeader yourself. Like this:

JPanel tablePanel = new JPanel(new BorderLayout());
JTable table = new JTable();
tablePanel.add(table, BorderLayout.CENTER);
tablePanel.add(table.getTableHeader(), BorderLayout.NORTH);