Programs & Examples On #Static reflection

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`

Why is this printing 'None' in the output?

Because of double print function. I suggest you to use return instead of print inside the function definition.

def lyrics():
    return "The very first line"
print(lyrics())

OR

def lyrics():
    print("The very first line")
lyrics()

Smooth GPS data

What you are looking for is called a Kalman Filter. It's frequently used to smooth navigational data. It is not necessarily trivial, and there is a lot of tuning you can do, but it is a very standard approach and works well. There is a KFilter library available which is a C++ implementation.

My next fallback would be least squares fit. A Kalman filter will smooth the data taking velocities into account, whereas a least squares fit approach will just use positional information. Still, it is definitely simpler to implement and understand. It looks like the GNU Scientific Library may have an implementation of this.

Can I delete a git commit but keep the changes?

It's as simple as this:

git reset HEAD^

Note: some shells treat ^ as a special character (for example some Windows shells or ZSH with globbing enabled), so you may have to quote "HEAD^" in those cases.

git reset without a --hard or --soft moves your HEAD to point to the specified commit, without changing any files. HEAD^ refers to the (first) parent commit of your current commit, which in your case is the commit before the temporary one.

Note that another option is to carry on as normal, and then at the next commit point instead run:

git commit --amend [-m … etc]

which will instead edit the most recent commit, having the same effect as above.

Note that this (as with nearly every git answer) can cause problems if you've already pushed the bad commit to a place where someone else may have pulled it from. Try to avoid that

Removing viewcontrollers from navigation stack

// removing the viewcontrollers by class names from stack and then dismissing the current view.

 self.navigationController?.viewControllers.removeAll(where: { (vc) -> Bool in
      if vc.isKind(of: ViewController.self) || vc.isKind(of: ViewController2.self) 
       {
        return true
        } 
     else 
        {
         return false
         }
        })
self.navigationController?.popViewController(animated: false)
self.dismiss(animated: true, completion: nil)

How to ignore whitespace in a regular expression subject string?

While the accepted answer is technically correct, a more practical approach, if possible, is to just strip whitespace out of both the regular expression and the search string.

If you want to search for "my cats", instead of:

myString.match(/m\s*y\s*c\s*a\*st\s*s\s*/g)

Just do:

myString.replace(/\s*/g,"").match(/mycats/g)

Warning: You can't automate this on the regular expression by just replacing all spaces with empty strings because they may occur in a negation or otherwise make your regular expression invalid.

Logging with Retrofit 2

You can also add Facebook's Stetho and look at the network traces in Chrome: http://facebook.github.io/stetho/

final OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
    builder.networkInterceptors().add(new StethoInterceptor());
}

Then open "chrome://inspect" in Chrome...

How to Round to the nearest whole number in C#

I was looking for this, but my example was to take a number, such as 4.2769 and drop it in a span as just 4.3. Not exactly the same, but if this helps:

Model.Statistics.AverageReview   <= it's just a double from the model

Then:

@Model.Statistics.AverageReview.ToString("n1")   <=gives me 4.3
@Model.Statistics.AverageReview.ToString("n2")   <=gives me 4.28

etc...

css transform, jagged edges in chrome

Adding the following on the div surrounding the element in question fixed this for me.

-webkit-transform-style: preserve-3d;

The jagged edges were appearing around the video window in my case.

SQL INSERT INTO from multiple tables

If I'm understanding you correctly, you should be able to do this in one query, joining table1 and table2 together:

INSERT INTO table3 { name, age, sex, city, id, number}
SELECT p.name, p.age, p.sex, p.city, p.id, c.number
FROM table1 p
INNER JOIN table2 c ON c.Id = p.Id

How to check if a database exists in SQL Server?

IF EXISTS (SELECT name FROM master.sys.databases WHERE name = N'YourDatabaseName')
  Do your thing...

By the way, this came directly from SQL Server Studio, so if you have access to this tool, I recommend you start playing with the various "Script xxxx AS" functions that are available. Will make your life easier! :)

How do I overload the square-bracket operator in C#?

Operators                           Overloadability

+, -, *, /, %, &, |, <<, >>         All C# binary operators can be overloaded.

+, -, !,  ~, ++, --, true, false    All C# unary operators can be overloaded.

==, !=, <, >, <= , >=               All relational operators can be overloaded, 
                                    but only as pairs.

&&, ||                  They can't be overloaded

() (Conversion operator)        They can't be overloaded

+=, -=, *=, /=, %=                  These compound assignment operators can be 
                                    overloaded. But in C#, these operators are
                                    automatically overloaded when the respective
                                    binary operator is overloaded.

=, . , ?:, ->, new, is, as, sizeof  These operators can't be overloaded

    [ ]                             Can be overloaded but not always!

Source of the information

For bracket:

public Object this[int index]
{

}

BUT

The array indexing operator cannot be overloaded; however, types can define indexers, properties that take one or more parameters. Indexer parameters are enclosed in square brackets, just like array indices, but indexer parameters can be declared to be of any type (unlike array indices, which must be integral).

From MSDN

Dependency injection with Jersey 2.0

You need to define an AbstractBinder and register it in your JAX-RS application. The binder specifies how the dependency injection should create your classes.

public class MyApplicationBinder extends AbstractBinder {
    @Override
    protected void configure() {
        bind(MyService.class).to(MyService.class);
    }
}

When @Inject is detected on a parameter or field of type MyService.class it is instantiated using the class MyService. To use this binder, it need to be registered with the JAX-RS application. In your web.xml, define a JAX-RS application like this:

<servlet>
  <servlet-name>MyApplication</servlet-name>
  <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
  <init-param>
    <param-name>javax.ws.rs.Application</param-name>
    <param-value>com.mypackage.MyApplication</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>MyApplication</servlet-name>
  <url-pattern>/*</url-pattern>
</servlet-mapping>

Implement the MyApplication class (specified above in the init-param).

public class MyApplication extends ResourceConfig {
    public MyApplication() {
        register(new MyApplicationBinder());
        packages(true, "com.mypackage.rest");
    }
}

The binder specifying dependency injection is registered in the constructor of the class, and we also tell the application where to find the REST resources (in your case, MyResource) using the packages() method call.

git - Server host key not cached

For those of you who are setting up MSYS Git on Windows using PuTTY via the standard command prompt, the way to add a host to PuTTY's cache is to run

> plink.exe <host>

For example:

> plink.exe codebasehq.com

The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 2e:db:b6:22:f7:bd:48:f6:da:72:bf:59:d7:75:d7:4e
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n)

Just answer y, and then Ctrl+C the rest.

Do check the fingerprint though. This warning is there for a good reason. Fingerprints for some git services (please edit to add more):

What does #defining WIN32_LEAN_AND_MEAN exclude exactly?

Directly from the Windows.h header file:

#ifndef WIN32_LEAN_AND_MEAN
    #include <cderr.h>
    #include <dde.h>
    #include <ddeml.h>
    #include <dlgs.h>
    #ifndef _MAC
        #include <lzexpand.h>
        #include <mmsystem.h>
        #include <nb30.h>
        #include <rpc.h>
    #endif
    #include <shellapi.h>
    #ifndef _MAC
        #include <winperf.h>
        #include <winsock.h>
    #endif
    #ifndef NOCRYPT
        #include <wincrypt.h>
        #include <winefs.h>
        #include <winscard.h>
    #endif

    #ifndef NOGDI
        #ifndef _MAC
            #include <winspool.h>
            #ifdef INC_OLE1
                #include <ole.h>
            #else
                #include <ole2.h>
            #endif /* !INC_OLE1 */
        #endif /* !MAC */
        #include <commdlg.h>
    #endif /* !NOGDI */
#endif /* WIN32_LEAN_AND_MEAN */

if you want to know what each of the headers actually do, typeing the header names into the search in the MSDN library will usually produce a list of the functions in that header file.

Also, from Microsoft's support page:

To speed the build process, Visual C++ and the Windows Headers provide the following new defines:

VC_EXTRALEAN
WIN32_LEAN_AND_MEAN

You can use them to reduce the size of the Win32 header files.

Finally, if you choose to use either of these preprocessor defines, and something you need is missing, you can just include that specific header file yourself. Typing the name of the function you're after into MSDN will usually produce an entry which will tell you which header to include if you want to use it, at the bottom of the page.

DOS: find a string, if found then run another script

@echo off
cls
MD %homedrive%\TEMPBBDVD\
CLS
TIMEOUT /T 1 >NUL
CLS
systeminfo >%homedrive%\TEMPBBDVD\info.txt
cls
timeout /t 3 >nul
cls
find "x64-based PC" %homedrive%\TEMPBBDVD\info.txt >nul
if %errorlevel% equ 1 goto 32bitsok
goto 64bitsok
cls

:commandlineerror
cls
echo error, command failed or you not are using windows OS.
pause >nul
cls
exit

:64bitsok
cls
echo done, system of 64 bits
pause >nul
cls
del /q /f %homedrive%\TEMPBBDVD\info.txt >nul
cls
timeout /t 1 >nul
cls
RD %homedrive%\TEMPBBDVD\ >nul
cls
exit

:32bitsok
cls
echo done, system of 32 bits
pause >nul
cls
del /q /f %homedrive%\TEMPBBDVD\info.txt >nul
cls
timeout /t 1 >nul
cls
RD %homedrive%\TEMPBBDVD\ >nul
cls
exit

What is Teredo Tunneling Pseudo-Interface?

Is to do with IPv6

All the gory details here: http://www.microsoft.com/technet/network/ipv6/teredo.mspx

Some people have had issues with it, and disabled it, but as a general rule, if it aint broke...

Chrome javascript debugger breakpoints don't do anything?

I'm not sure how it worked, but hitting F1 for settings and at the bottom right, hitting "Restore defaults and reload" worked for me.

How to add composite primary key to table

You don't need to create the table first and then add the keys in subsequent steps. You can add both primary key and foreign key while creating the table:

This example assumes the existence of a table (Codes) that we would want to reference with our foreign key.

CREATE TABLE d (
id [numeric](1),
code [varchar](2),
PRIMARY KEY (id, code),
CONSTRAINT fk_d_codes FOREIGN KEY (code) REFERENCES Codes (code)
)

If you don't have a table that we can reference, add one like this so that the example will work:

CREATE TABLE Codes (
    Code [varchar](2) PRIMARY KEY   
    )

NOTE: you must have a table to reference before creating the foreign key.

Split pandas dataframe in two if it has more than 10 rows

If you have a large data frame and need to divide into a variable number of sub data frames rows, like for example each sub dataframe has a max of 4500 rows, this script could help:

max_rows = 4500
dataframes = []
while len(df) > max_rows:
    top = df[:max_rows]
    dataframes.append(top)
    df = df[max_rows:]
else:
    dataframes.append(df)

You could then save out these data frames:

for _, frame in enumerate(dataframes):
    frame.to_csv(str(_)+'.csv', index=False)

Hope this helps someone!

How do I suspend painting for a control and its children?

Based on ng5000's answer, I like using this extension:

        #region Suspend
        [DllImport("user32.dll")]
        private static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
        private const int WM_SETREDRAW = 11;
        public static IDisposable BeginSuspendlock(this Control ctrl)
        {
            return new suspender(ctrl);
        }
        private class suspender : IDisposable
        {
            private Control _ctrl;
            public suspender(Control ctrl)
            {
                this._ctrl = ctrl;
                SendMessage(this._ctrl.Handle, WM_SETREDRAW, false, 0);
            }
            public void Dispose()
            {
                SendMessage(this._ctrl.Handle, WM_SETREDRAW, true, 0);
                this._ctrl.Refresh();
            }
        }
        #endregion

Use:

using (this.BeginSuspendlock())
{
    //update GUI
}

How to refer to relative paths of resources when working with a code repository

In Python, paths are relative to the current working directory, which in most cases is the directory from which you run your program. The current working directory is very likely not as same as the directory of your module file, so using a path relative to your current module file is always a bad choice.

Using absolute path should be the best solution:

import os
package_dir = os.path.dirname(os.path.abspath(__file__))
thefile = os.path.join(package_dir,'test.cvs')

How to create a file in Android?

I used the following code to create a temporary file for writing bytes. And its working fine.

File file = new File(Environment.getExternalStorageDirectory() + "/" + File.separator + "test.txt");
file.createNewFile();
byte[] data1={1,1,0,0};
//write the bytes in file
if(file.exists())
{
     OutputStream fo = new FileOutputStream(file);              
     fo.write(data1);
     fo.close();
     System.out.println("file created: "+file);
}               

//deleting the file             
file.delete();
System.out.println("file deleted");

How do you read a CSV file and display the results in a grid in Visual Basic 2010?

Consider this snippet of code. Modify as you see fit, or to fit your requirements. You'll need to have Imports statements for System.IO and System.Data.OleDb.

Dim fi As New FileInfo("c:\foo.csv")
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName

Dim conn As New OleDbConnection(connectionString)
conn.Open()

'the SELECT statement is important here, 
'and requires some formatting to pull dates and deal with headers with spaces.
Dim cmdSelect As New OleDbCommand("SELECT Foo, Bar, FORMAT(""SomeDate"",'YYYY/MM/DD') AS SomeDate, ""SOME MULTI WORD COL"", FROM " & fi.Name, conn)

Dim adapter1 As New OleDbDataAdapter
adapter1.SelectCommand = cmdSelect

Dim ds As New DataSet
adapter1.Fill(ds, "DATA")

myDataGridView.DataSource = ds.Tables(0).DefaultView 
myDataGridView.DataBind
conn.Close()

Get selected option from select element

Here's a short version:

$('#ddlCodes').change(function() {
  $('#txtEntry2').text($(this).find(":selected").text());
});

karim79 made a good catch, judging by your element name txtEntry2 may be a textbox, if it's any kind of input, you'll need to use .val() instead or .text() like this:

  $('#txtEntry2').val($(this).find(":selected").text());

For the "what's wrong?" part of the question: .text() doesn't take a selector, it takes text you want it set to, or nothing to return the text already there. So you need to fetch the text you want, then put it in the .text(string) method on the object you want to set, like I have above.

msvcr110.dll is missing from computer error while installing PHP

You need to install the Visual C++ libraries: http://www.microsoft.com/en-us/download/details.aspx?id=30679

As mentioned by Stuart McLaughlin, make sure you get the x86 version even if you use a 64-bits OS because PHP needs some 32-bit libraries.

How to put an image in div with CSS?

With Javascript/Jquery:

  • load image with hidden img
  • when image has been loaded, get width and height
  • dynamically create a div and set width, height and background
  • remove the original img

      $(document).ready(function() {
        var image = $("<img>");
        var div = $("<div>")
        image.load(function() {
          div.css({
            "width": this.width,
            "height": this.height,
            "background-image": "url(" + this.src + ")"
          });
          $("#container").append(div);
        });
        image.attr("src", "test0.png");
      });
    

How to upload files to server using JSP/Servlet?

Simplest way could come up with for files and input controls, w/out a billion libraries:

  <%
  if (request.getContentType()==null) return;
  // for input type=text controls
  String v_Text = 
  (new BufferedReader(new InputStreamReader(request.getPart("Text1").getInputStream()))).readLine();    

  // for input type=file controls
  InputStream inStr = request.getPart("File1").getInputStream();
  char charArray[] = new char[inStr.available()];
  new InputStreamReader(inStr).read(charArray);
  String contents = new String(charArray);
  %>

Set the absolute position of a view

In general, you can add a View in a specific position using a FrameLayout as container by specifying the leftMargin and topMargin attributes.

The following example will place a 20x20px ImageView at position (100,200) using a FrameLayout as fullscreen container:

XML

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:background="#33AAFF"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</FrameLayout>

Activity / Fragment / Custom view

//...
FrameLayout root = (FrameLayout)findViewById(R.id.root);
ImageView img = new ImageView(this);
img.setBackgroundColor(Color.RED);
//..load something inside the ImageView, we just set the background color

FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(20, 20);
params.leftMargin = 100;
params.topMargin  = 200;
root.addView(img, params);
//...

This will do the trick because margins can be used as absolute (X,Y) coordinates without a RelativeLayout:

enter image description here

Center an item with position: relative

Alternatively, you may also use the CSS3 Flexible Box Model. It's a great way to create flexible layouts that can also be applied to center content like so:

#parent {
    -webkit-box-align:center;
    -webkit-box-pack:center;
    display:-webkit-box;
}

Hide axis and gridlines Highcharts

This has always worked well for me:

yAxes: [{
         ticks: {
                 display: false;
                },

Is it possible to have a multi-line comments in R?

R Studio (and Eclipse + StatET): Highlight the text and use CTRL+SHIFT+C to comment multiple lines in Windows. Or, command+SHIFT+C in OS-X.

Regular Expression to match valid dates

I know this does not answer your question, but why don't you use a date handling routine to check if it's a valid date? Even if you modify the regexp with a negative lookahead assertion like (?!31/0?2) (ie, do not match 31/2 or 31/02) you'll still have the problem of accepting 29 02 on non leap years and about a single separator date format.

The problem is not easy if you want to really validate a date, check this forum thread.

For an example or a better way, in C#, check this link

If you are using another platform/language, let us know

How to strip all whitespace from string

Try a regex with re.sub. You can search for all whitespace and replace with an empty string.

\s in your pattern will match whitespace characters - and not just a space (tabs, newlines, etc). You can read more about it in the manual.

nodeJS - How to create and read session with express

I forgot to tell a bug when i use I use req.session.email = req.param('email'), the server error says cannot sett property email of undefined.

The reason of this error is a wrong order of app.use. You must configure express in this order:

app.use(express.cookieParser());
app.use(express.session({ secret: sessionVal }));
app.use(app.route);

Logging levels - Logback - rule-of-thumb to assign log levels

I answer this coming from a component-based architecture, where an organisation may be running many components that may rely on each other. During a propagating failure, logging levels should help to identify both which components are affected and which are a root cause.

  • ERROR - This component has had a failure and the cause is believed to be internal (any internal, unhandled exception, failure of encapsulated dependency... e.g. database, REST example would be it has received a 4xx error from a dependency). Get me (maintainer of this component) out of bed.

  • WARN - This component has had a failure believed to be caused by a dependent component (REST example would be a 5xx status from a dependency). Get the maintainers of THAT component out of bed.

  • INFO - Anything else that we want to get to an operator. If you decide to log happy paths then I recommend limiting to 1 log message per significant operation (e.g. per incoming http request).

For all log messages be sure to log useful context (and prioritise on making messages human readable/useful rather than having reams of "error codes")

  • DEBUG (and below) - Shouldn't be used at all (and certainly not in production). In development I would advise using a combination of TDD and Debugging (where necessary) as opposed to polluting code with log statements. In production, the above INFO logging, combined with other metrics should be sufficient.

A nice way to visualise the above logging levels is to imagine a set of monitoring screens for each component. When all running well they are green, if a component logs a WARNING then it will go orange (amber) if anything logs an ERROR then it will go red.

In the event of an incident you should have one (root cause) component go red and all the affected components should go orange/amber.

SOAP request to WebService with java

When the WSDL is available, it is just two steps you need to follow to invoke that web service.

Step 1: Generate the client side source from a WSDL2Java tool

Step 2: Invoke the operation using:

YourService service = new YourServiceLocator();
Stub stub = service.getYourStub();
stub.operation();

If you look further, you will notice that the Stub class is used to invoke the service deployed at the remote location as a web service. When invoking that, your client actually generates the SOAP request and communicates. Similarly the web service sends the response as a SOAP. With the help of a tool like Wireshark, you can view the SOAP messages exchanged.

However since you have requested more explanation on the basics, I recommend you to refer here and write a web service with it's client to learn it further.

Java: Find .txt files in specified folder

Try:

List<String> textFiles(String directory) {
  List<String> textFiles = new ArrayList<String>();
  File dir = new File(directory);
  for (File file : dir.listFiles()) {
    if (file.getName().endsWith((".txt"))) {
      textFiles.add(file.getName());
    }
  }
  return textFiles;
}

You want to do a case insensitive search in which case:

    if (file.getName().toLowerCase().endsWith((".txt"))) {

If you want to recursively search for through a directory tree for text files, you should be able to adapt the above as either a recursive function or an iterative function using a stack.

How to read PDF files using Java?

with Apache PDFBox it goes like this:

PDDocument document = PDDocument.load(new File("test.pdf"));
if (!document.isEncrypted()) {
    PDFTextStripper stripper = new PDFTextStripper();
    String text = stripper.getText(document);
    System.out.println("Text:" + text);
}
document.close();

How do I create dynamic properties in C#?

Why not use an indexer with the property name as a string value passed to the indexer?

Why do you need to put #!/bin/bash at the beginning of a script file?

The shebang is a directive to the loader to use the program which is specified after the #! as the interpreter for the file in question when you try to execute it. So, if you try to run a file called foo.sh which has #!/bin/bash at the top, the actual command that runs is /bin/bash foo.sh. This is a flexible way of using different interpreters for different programs. This is something implemented at the system level and the user level API is the shebang convention.

It's also worth knowing that the shebang is a magic number - a human readable one that identifies the file as a script for the given interpreter.

Your point about it "working" even without the shebang is only because the program in question is a shell script written for the same shell as the one you are using. For example, you could very well write a javascript file and then put a #! /usr/bin/js (or something similar) to have a javascript "Shell script".

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

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

How to create an empty array in PHP with predefined size?

There is also array_pad. You can use it like this:

$data = array_pad($data,$number_of_items,0);

For initializing with zeros the $number_of_items positions of the array $data.

How to edit .csproj file

For JetBrains Rider:

First Option

  1. Unload Project
  2. Double click the unloaded project

Second option:

  1. Click on the project
  2. Press F4

That's it!

Check that a input to UITextField is numeric only

For integer test it'll be:

- (BOOL) isIntegerNumber: (NSString*)input
{
    return [input integerValue] != 0 || [input isEqualToString:@"0"];
}

relative path in require_once doesn't work

Use

__DIR__

to get the current path of the script and this should fix your problem.

So:

require_once(__DIR__.'/../class/user.php');

This will prevent cases where you can run a PHP script from a different folder and therefore the relatives paths will not work.

Edit: slash problem fixed

JavaScript set object key by variable

You need to make the object first, then use [] to set it.

var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);

UPDATE 2018:

If you're able to use ES6 and Babel, you can use this new feature:

{
    [yourKeyVariable]: someValueArray,
}  

Why are primes important in cryptography?

I think what are important in cryptography are not primes itself, but it is the difficulty of prime factorization problem

Suppose you have very very large integer which is known to be product of two primes m and n, it is not easy to find what are m and n. Algorithm such as RSA depends on this fact.

By the way, there is a published paper on algorithm which can "solve" this prime factorization problem in acceptable time using quantum computer. So newer algorithms in cryptography may not rely on this "difficulty" of prime factorization anymore when quantum computer comes to town :)

How do I find the time difference between two datetime objects in python?

You may find this fast snippet useful in not so much long time intervals:

    from datetime import datetime as dttm
    time_ago = dttm(2017, 3, 1, 1, 1, 1, 1348)
    delta = dttm.now() - time_ago
    days = delta.days # can be converted into years which complicates a bit…
    hours, minutes, seconds = map(int, delta.__format__('').split('.')[0].split(' ')[-1].split(':'))

tested on Python v.3.8.6

javascript how to create a validation error message without using alert

JavaScript

<script language="javascript">
        var flag=0;
        function username()
        {
            user=loginform.username.value;
            if(user=="")
            {
                document.getElementById("error0").innerHTML="Enter UserID";
                flag=1;
            }
        }   
        function password()
        {
            pass=loginform.password.value;
            if(pass=="")
            {
                document.getElementById("error1").innerHTML="Enter password";   
                flag=1;
            }
        }

        function check(form)
        {
            flag=0;
            username();
            password();
            if(flag==1)
                return false;
            else
                return true;
        }

    </script>

HTML

<form name="loginform" action="Login" method="post" class="form-signin" onSubmit="return check(this)">



                    <div id="error0"></div>
                    <input type="text" id="inputEmail" name="username" placeholder="UserID" onBlur="username()">
               controls">
                    <div id="error1"></div>
                    <input type="password" id="inputPassword" name="password" placeholder="Password" onBlur="password()" onclick="make_blank()">

                    <button type="submit" class="btn">Sign in</button>
                </div>
            </div>
        </form>

HashMap: One Key, multiple Values

Try using collections to store the values of a key:

Map<Key, Collection<Value>>

you have to maintain the value list yourself

In c# is there a method to find the max of 3 numbers?

Well, you can just call it twice:

int max3 = Math.Max(x, Math.Max(y, z));

If you find yourself doing this a lot, you could always write your own helper method... I would be happy enough seeing this in my code base once, but not regularly.

(Note that this is likely to be more efficient than Andrew's LINQ-based answer - but obviously the more elements you have the more appealing the LINQ approach is.)

EDIT: A "best of both worlds" approach might be to have a custom set of methods either way:

public static class MoreMath
{
    // This method only exists for consistency, so you can *always* call
    // MoreMath.Max instead of alternating between MoreMath.Max and Math.Max
    // depending on your argument count.
    public static int Max(int x, int y)
    {
        return Math.Max(x, y);
    }

    public static int Max(int x, int y, int z)
    {
        // Or inline it as x < y ? (y < z ? z : y) : (x < z ? z : x);
        // Time it before micro-optimizing though!
        return Math.Max(x, Math.Max(y, z));
    }

    public static int Max(int w, int x, int y, int z)
    {
        return Math.Max(w, Math.Max(x, Math.Max(y, z)));
    }

    public static int Max(params int[] values)
    {
        return Enumerable.Max(values);
    }
}

That way you can write MoreMath.Max(1, 2, 3) or MoreMath.Max(1, 2, 3, 4) without the overhead of array creation, but still write MoreMath.Max(1, 2, 3, 4, 5, 6) for nice readable and consistent code when you don't mind the overhead.

I personally find that more readable than the explicit array creation of the LINQ approach.

How to get the date 7 days earlier date from current date in Java

For all date related functionality, you should consider using Joda Library. Java's date api's are very poorly designed. Joda provides very nice API.

How do I perform HTML decoding/encoding using Python/Django?

Given the Django use case, there are two answers to this. Here is its django.utils.html.escape function, for reference:

def escape(html):
    """Returns the given HTML with ampersands, quotes and carets encoded."""
    return mark_safe(force_unicode(html).replace('&', '&amp;').replace('<', '&l
t;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;'))

To reverse this, the Cheetah function described in Jake's answer should work, but is missing the single-quote. This version includes an updated tuple, with the order of replacement reversed to avoid symmetric problems:

def html_decode(s):
    """
    Returns the ASCII decoded version of the given HTML string. This does
    NOT remove normal HTML tags like <p>.
    """
    htmlCodes = (
            ("'", '&#39;'),
            ('"', '&quot;'),
            ('>', '&gt;'),
            ('<', '&lt;'),
            ('&', '&amp;')
        )
    for code in htmlCodes:
        s = s.replace(code[1], code[0])
    return s

unescaped = html_decode(my_string)

This, however, is not a general solution; it is only appropriate for strings encoded with django.utils.html.escape. More generally, it is a good idea to stick with the standard library:

# Python 2.x:
import HTMLParser
html_parser = HTMLParser.HTMLParser()
unescaped = html_parser.unescape(my_string)

# Python 3.x:
import html.parser
html_parser = html.parser.HTMLParser()
unescaped = html_parser.unescape(my_string)

# >= Python 3.5:
from html import unescape
unescaped = unescape(my_string)

As a suggestion: it may make more sense to store the HTML unescaped in your database. It'd be worth looking into getting unescaped results back from BeautifulSoup if possible, and avoiding this process altogether.

With Django, escaping only occurs during template rendering; so to prevent escaping you just tell the templating engine not to escape your string. To do that, use one of these options in your template:

{{ context_var|safe }}
{% autoescape off %}
    {{ context_var }}
{% endautoescape %}

IndexError: tuple index out of range ----- Python

This is because your row variable/tuple does not contain any value for that index. You can try printing the whole list like print(row) and check how many indexes there exists.

How can I concatenate a string within a loop in JSTL/JSP?

define a String variable using the JSP tags

<%!
String test = new String();
%>

then refer to that variable in your loop as

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
test+= whaterver_value
</c:forEach>

jQuery: How to capture the TAB keypress within a Textbox

$('#textbox').live('keypress', function(e) {
    if (e.keyCode === 9) {
        e.preventDefault();
        // do work
    }
});

Count work days between two dates

My version of the accepted answer as a function using DATEPART, so I don't have to do a string comparison on the line with

DATENAME(dw, @StartDate) = 'Sunday'

Anyway, here's my business datediff function

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION BDATEDIFF
(
    @startdate as DATETIME,
    @enddate as DATETIME
)
RETURNS INT
AS
BEGIN
    DECLARE @res int

SET @res = (DATEDIFF(dd, @startdate, @enddate) + 1)
    -(DATEDIFF(wk, @startdate, @enddate) * 2)
    -(CASE WHEN DATEPART(dw, @startdate) = 1 THEN 1 ELSE 0 END)
    -(CASE WHEN DATEPART(dw, @enddate) = 7 THEN 1 ELSE 0 END)

    RETURN @res
END
GO

Host binding and Host listening

@HostListener is a decorator for the callback/event handler method, so remove the ; at the end of this line:

@HostListener('click', ['$event.target']);

Here's a working plunker that I generated by copying the code from the API docs, but I put the onClick() method on the same line for clarity:

import {Component, HostListener, Directive} from 'angular2/core';

@Directive({selector: 'button[counting]'})
class CountClicks {
  numberOfClicks = 0;
  @HostListener('click', ['$event.target']) onClick(btn) {
    console.log("button", btn, "number of clicks:", this.numberOfClicks++);
  }
}
@Component({
  selector: 'my-app',
  template: `<button counting>Increment</button>`,
  directives: [CountClicks]
})
export class AppComponent {
  constructor() { console.clear(); }
}

Host binding can also be used to listen to global events:

To listen to global events, a target must be added to the event name. The target can be window, document or body (reference)

@HostListener('document:keyup', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }

How to add a margin to a table row <tr>

First of all, don't try to put a margin to a <tr> or a <td> because it won't work in modern rendering.

  • Solution 1

Although margin doesn't work, padding does work :

td{
    padding-bottom: 10px;
    padding-top: 10px;
}

Warning : This will also push the border further away from the element, if your border is visible, you might want to use solution 2 instead.

  • Solution 2

To keep the border close to the element and mimic the margin, put another <tr> between each of your reel table's <tr> like so :

<tr style="height: 20px;"> <!-- Mimic the margin -->
</tr>

Use a JSON array with objects with javascript

By 'JSON array containing objects' I guess you mean a string containing JSON?

If so you can use the safe var myArray = JSON.parse(myJSON) method (either native or included using JSON2), or the usafe var myArray = eval("(" + myJSON + ")"). eval should normally be avoided, but if you are certain that the content is safe, then there is no problem.

After that you just iterate over the array as normal.

for (var i = 0; i < myArray.length; i++) {
    alert(myArray[i].Title);
}

Remove blank attributes from an Object in Javascript

Here is a comprehensive recursive function (originally based on the one by @chickens) that will:

  • recursively remove what you tell it to defaults=[undefined, null, '', NaN]
  • Correctly handle regular objects, arrays and Date objects
const cleanEmpty = function(obj, defaults = [undefined, null, NaN, '']) {
  if (!defaults.length) return obj
  if (defaults.includes(obj)) return

  if (Array.isArray(obj))
    return obj
      .map(v => v && typeof v === 'object' ? cleanEmpty(v, defaults) : v)
      .filter(v => !defaults.includes(v))

  return Object.entries(obj).length 
    ? Object.entries(obj)
        .map(([k, v]) => ([k, v && typeof v === 'object' ? cleanEmpty(v, defaults) : v]))
        .reduce((a, [k, v]) => (defaults.includes(v) ? a : { ...a, [k]: v}), {}) 
    : obj
}

USAGE:

_x000D_
_x000D_
// based off the recursive cleanEmpty function by @chickens. _x000D_
// This one can also handle Date objects correctly _x000D_
// and has a defaults list for values you want stripped._x000D_
_x000D_
const cleanEmpty = function(obj, defaults = [undefined, null, NaN, '']) {_x000D_
  if (!defaults.length) return obj_x000D_
  if (defaults.includes(obj)) return_x000D_
_x000D_
  if (Array.isArray(obj))_x000D_
    return obj_x000D_
      .map(v => v && typeof v === 'object' ? cleanEmpty(v, defaults) : v)_x000D_
      .filter(v => !defaults.includes(v))_x000D_
_x000D_
  return Object.entries(obj).length _x000D_
    ? Object.entries(obj)_x000D_
        .map(([k, v]) => ([k, v && typeof v === 'object' ? cleanEmpty(v, defaults) : v]))_x000D_
        .reduce((a, [k, v]) => (defaults.includes(v) ? a : { ...a, [k]: v}), {}) _x000D_
    : obj_x000D_
}_x000D_
_x000D_
_x000D_
// testing_x000D_
_x000D_
console.log('testing: undefined \n', cleanEmpty(undefined))_x000D_
console.log('testing: null \n',cleanEmpty(null))_x000D_
console.log('testing: NaN \n',cleanEmpty(NaN))_x000D_
console.log('testing: empty string \n',cleanEmpty(''))_x000D_
console.log('testing: empty array \n',cleanEmpty([]))_x000D_
console.log('testing: date object \n',cleanEmpty(new Date(1589339052 * 1000)))_x000D_
console.log('testing: nested empty arr \n',cleanEmpty({ 1: { 2 :null, 3: [] }}))_x000D_
console.log('testing: comprehensive obj \n', cleanEmpty({_x000D_
  a: 5,_x000D_
  b: 0,_x000D_
  c: undefined,_x000D_
  d: {_x000D_
    e: null,_x000D_
    f: [{_x000D_
      a: undefined,_x000D_
      b: new Date(),_x000D_
      c: ''_x000D_
    }]_x000D_
  },_x000D_
  g: NaN,_x000D_
  h: null_x000D_
}))_x000D_
console.log('testing: different defaults \n', cleanEmpty({_x000D_
  a: 5,_x000D_
  b: 0,_x000D_
  c: undefined,_x000D_
  d: {_x000D_
    e: null,_x000D_
    f: [{_x000D_
      a: undefined,_x000D_
      b: '',_x000D_
      c: new Date()_x000D_
    }]_x000D_
  },_x000D_
  g: [0, 1, 2, 3, 4],_x000D_
  h: '',_x000D_
}, [undefined, null]))
_x000D_
_x000D_
_x000D_

Element count of an array in C++

It seems that if you know the type of elements in the array you can also use that to your advantage with sizeof.

int numList[] = { 0, 1, 2, 3, 4 };

cout << sizeof(numList) / sizeof(int);

// => 5

MongoDB: How to find the exact version of installed MongoDB

To check mongodb version use the mongod command with --version option.

To check MongoDB Server version, Open the command line via your terminal program and execute the following command:

Path : C:\Program Files\MongoDB\Server\3.2\bin Open Cmd and execute the following command: mongod --version To Check MongoDB Shell version, Type:

mongo --version

Calling Objective-C method from C++ member function?

You can mix C++ in with Objectiv-C (Objective C++). Write a C++ method in your Objective C++ class that simply calls [context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer*)self.layer]; and call it from your C++.

I haven't tried it before my self, but give it a shot, and share the results with us.

How to display default text "--Select Team --" in combo box on pageload in WPF?

You can do this without any code behind by using a IValueConverter.

<Grid>
   <ComboBox
       x:Name="comboBox1"
       ItemsSource="{Binding MyItemSource}"  />
   <TextBlock
       Visibility="{Binding SelectedItem, ElementName=comboBox1, Converter={StaticResource NullToVisibilityConverter}}"
       IsHitTestVisible="False"
       Text="... Select Team ..." />
</Grid>

Here you have the converter class that you can re-use.

public class NullToVisibilityConverter : IValueConverter
{
    #region Implementation of IValueConverter

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value == null ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

And finally, you need to declare your converter in a resource section.

<Converters:NullToVisibilityConverter x:Key="NullToVisibilityConverter" />

Where Converters is the place you have placed the converter class. An example is:

xmlns:Converters="clr-namespace:MyProject.Resources.Converters"

The very nice thing about this approach is no repetition of code in your code behind.

jQuery map vs. each

The each function iterates over an array, calling the supplied function once per element, and setting this to the active element. This:

function countdown() {
    alert(this + "..");
}

$([5, 4, 3, 2, 1]).each(countdown);

will alert 5.. then 4.. then 3.. then 2.. then 1..

Map on the other hand takes an array, and returns a new array with each element changed by the function. This:

function squared() {
    return this * this;
}

var s = $([5, 4, 3, 2, 1]).map(squared);

would result in s being [25, 16, 9, 4, 1].

Redirecting to a certain route based on condition

A different way of implementing login redirection is to use events and interceptors as described here. The article describes some additional advantages such as detecting when a login is required, queuing the requests, and replaying them once the login is successful.

You can try out a working demo here and view the demo source here.

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

Can You Please try this : Check the web site properties in IIS. Under home directory tab, check the application pool value Verify that all SharePoint services are started. If the application is not started do the following: I think this error might occur because of changing the service account password. You may need to change the new password to application pool
1)Click the stopped application pool 2)click advanced settings 3)Identity ->click the user to retype the user 4) Application Pool Identity dialog 5)click set -> manually type the user name and password. Then restart the server.

is there any alternative for ng-disabled in angular2?

To set the disabled property to true or false use

<button [disabled]="!nextLibAvailable" (click)="showNext('library')" class=" btn btn-info btn-xs" title="Next Lib"> {{libraries.name}}">
    <i class="fa fa-chevron-right fa-fw"></i>
</button>

Bash foreach loop

cat `cat filenames.txt`

will do the trick

Is it possible to set ENV variables for rails development environment in my code?

[Update]

While the solution under "old answer" will work for general problems, this section is to answer your specific question after clarification from your comment.

You should be able to set environment variables exactly like you specify in your question. As an example, I have a Heroku app that uses HTTP basic authentication.

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :authenticate

  def authenticate
    authenticate_or_request_with_http_basic do |username, password|
      username == ENV['HTTP_USER'] && password == ENV['HTTP_PASS']
    end
  end
end

# config/initializers/dev_environment.rb
unless Rails.env.production?
  ENV['HTTP_USER'] = 'testuser'
  ENV['HTTP_PASS'] = 'testpass'
end

So in your case you would use

unless Rails.env.production?
  ENV['admin_password'] = "secret"
end

Don't forget to restart the server so the configuration is reloaded!

[Old Answer]

For app-wide configuration, you might consider a solution like the following:

Create a file config/application.yml with a hash of options you want to be able to access:

admin_password: something_secret
allow_registration: true
facebook:
  app_id: application_id_here
  app_secret: application_secret_here
  api_key: api_key_here

Now, create the file config/initializers/app_config.rb and include the following:

require 'yaml'

yaml_data = YAML::load(ERB.new(IO.read(File.join(Rails.root, 'config', 'application.yml'))).result)
APP_CONFIG = HashWithIndifferentAccess.new(yaml_data)

Now, anywhere in your application, you can access APP_CONFIG[:admin_password], along with all your other data. (Note that since the initializer includes ERB.new, your YAML file can contain ERB markup.)

How to resolve 'unrecognized selector sent to instance'?

Very weird, but. You have to declare the class for your application instance as myApplication: UIApplication instead of myApplication: NSObject . It seems that the UIApplicationDelegate protocol doesn't implement the +registerForSystemEvents message. Crazy Apple APIs, again.

Changing the image source using jQuery

There is no way of changing the image source with CSS.

Only possible way is using Javascript or any Javascript library like jQuery.

Logic-

The images are inside a div and there are no class or id with that image.

So logic will be select the elements inside the div where the images are located.

Then select all the images elements with loop and change the image src with Javascript / jQuery.

Example Code with demo output-

_x000D_
_x000D_
$(document).ready(function()_x000D_
{_x000D_
    $("button").click(function()_x000D_
    {_x000D_
      $("#d1 .c1 a").each(function()_x000D_
      {_x000D_
          $(this).children('img').attr('src', 'https://www.gravatar.com/avatar/e56672acdbce5d9eda58a178ade59ffe');_x000D_
      });_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>_x000D_
_x000D_
<div id="d1">_x000D_
   <div class="c1">_x000D_
            <a href="#"><img src="img1_on.gif"></a>_x000D_
            <a href="#"><img src="img2_on.gif"></a>_x000D_
   </div>_x000D_
</div>_x000D_
_x000D_
<button>Change The Images</button>
_x000D_
_x000D_
_x000D_

How to get the HTML for a DOM element in javascript

First, put on element that wraps the div in question, put an id attribute on the element and then use getElementById on it: once you've got the lement, just do 'e.innerHTML` to retrieve the HTML.

<div><span><b>This is in bold</b></span></div>

=> <div id="wrap"><div><span><b>This is in bold</b></span></div></div>

and then:

var e=document.getElementById("wrap");
var content=e.innerHTML;

Note that outerHTML is not cross-browser compatible.

Dynamic button click event handler

Some code for a variation on this problem. Using the above code got me my click events as needed, but I was then stuck trying to work out which button had been clicked. My scenario is I have a dynamic amount of tab pages. On each tab page are (all dynamically created) 2 charts, 2 DGVs and a pair of radio buttons. Each control has a unique name relative to the tab, but there could be 20 radio buttons with the same name if I had 20 tab pages. The radio buttons switch between which of the 2 graphs and DGVs you get to see. Here is the code for when one of the radio buttons gets checked (There's a nearly identical block that swaps the charts and DGVs back):

   Private Sub radioFit_Components_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

    If sender.name = "radioFit_Components" And sender.visible Then
        If sender.checked Then
            For Each ctrl As Control In TabControl1.SelectedTab.Controls
                Select Case ctrl.Name
                    Case "embChartSSE_Components"
                        ctrl.BringToFront()
                    Case "embChartSSE_Fit_Curve"
                        ctrl.SendToBack()
                    Case "dgvFit_Components"
                        ctrl.BringToFront()
                End Select
            Next

        End If
    End If

End Sub

This code will fire for any of the tab pages and swap the charts and DGVs over on any of the tab pages. The sender.visible check is to stop the code firing when the form is being created.

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

In a MVC application, I got this warning because I was opening a Kendo Window with a method that was returning a View(), instead of a PartialView(). The View() was trying to retrive again all the scripts of the page.

Fluid width with equally spaced DIVs

Other posts have mentioned flexbox, but if more than one row of items is necessary, flexbox's space-between property fails (see the end of the post)

To date, the only clean solution for this is with the

CSS Grid Layout Module (Codepen demo)

Basically the relevant code necessary boils down to this:

ul {
  display: grid; /* (1) */
  grid-template-columns: repeat(auto-fit, 120px); /* (2) */
  grid-gap: 1rem; /* (3) */
  justify-content: space-between; /* (4) */
  align-content: flex-start; /* (5) */
}

1) Make the container element a grid container

2) Set the grid with an 'auto' amount of columns - as necessary. This is done for responsive layouts. The width of each column will be 120px. (Note the use of auto-fit (as apposed to auto-fill) which (for a 1-row layout) collapses empty tracks to 0 - allowing the items to expand to take up the remaining space. (check out this demo to see what I'm talking about) ).

3) Set gaps/gutters for the grid rows and columns - here, since want a 'space-between' layout - the gap will actually be a minimum gap because it will grow as necessary.

4) and 5) - Similar to flexbox.

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
}_x000D_
ul {_x000D_
  display: grid;_x000D_
  grid-template-columns: repeat(auto-fit, 120px);_x000D_
  grid-gap: 1rem;_x000D_
  justify-content: space-between;_x000D_
  align-content: flex-start;_x000D_
  _x000D_
  /* boring properties: */_x000D_
  list-style: none;_x000D_
  width: 90vw;_x000D_
  height: 90vh;_x000D_
  margin: 2vh auto;_x000D_
  border: 5px solid green;_x000D_
  padding: 0;_x000D_
  overflow: auto;_x000D_
}_x000D_
li {_x000D_
  background: tomato;_x000D_
  height: 120px;_x000D_
}
_x000D_
<ul>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Codepen demo (Resize to see the effect)


Browser Support - Caniuse

Currently supported by Chrome (Blink), Firefox, Safari and Edge! ... with partial support from IE (See this post by Rachel Andrew)


NB:

Flexbox's space-between property works great for one row of items, but when applied to a flex container which wraps it's items - (with flex-wrap: wrap) - fails, because you have no control over the alignment of the last row of items; the last row will always be justified (usually not what you want)

To demonstrate:

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
}_x000D_
ul {_x000D_
  _x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  flex-wrap: wrap;_x000D_
  align-content: flex-start;_x000D_
  _x000D_
  list-style: none;_x000D_
  width: 90vw;_x000D_
  height: 90vh;_x000D_
  margin: 2vh auto;_x000D_
  border: 5px solid green;_x000D_
  padding: 0;_x000D_
  overflow: auto;_x000D_
  _x000D_
}_x000D_
li {_x000D_
  background: tomato;_x000D_
  width: 110px;_x000D_
  height: 80px;_x000D_
  margin-bottom: 1rem;_x000D_
}
_x000D_
<ul>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Codepen (Resize to see what i'm talking about)


Further reading on CSS grids:

How do you set up use HttpOnly cookies in PHP

For PHP's own session cookies on Apache:
add this to your Apache configuration or .htaccess

<IfModule php5_module>
    php_flag session.cookie_httponly on
</IfModule>

This can also be set within a script, as long as it is called before session_start().

ini_set( 'session.cookie_httponly', 1 );

ImageMagick security policy 'PDF' blocking conversion

For me on my archlinux system the line was already uncommented. I had to replace "none" by "read | write " to make it work.

Java 6 Unsupported major.minor version 51.0

The problem is because you haven't set JDK version properly.You should use jdk 7 for major number 51. Like this:

JAVA_HOME=/usr/java/jdk1.7.0_79

What is a unix command for deleting the first N characters of a line?

I think awk would be the best tool for this as it can both filter and perform the necessary string manipulation functions on filtered lines:

tail -f logfile | awk '/org.springframework/ {print substr($0, 6)}'

or

tail -f logfile | awk '/org.springframework/ && sub(/^.{5}/,"",$0)'

PHP - Check if the page run on Mobile or Desktop browser

There are many great open source projects that make detection a lot easier. To name two:

  1. PHP mobile detect
  2. WURFL

Convert INT to DATETIME (SQL)

Try this:

select CONVERT(datetime, convert(varchar(10), 20120103))

How can I define a composite primary key in SQL?

CREATE TABLE `voting` (
  `QuestionID` int(10) unsigned NOT NULL,
  `MemberId` int(10) unsigned NOT NULL,
  `vote` int(10) unsigned NOT NULL,
  PRIMARY KEY  (`QuestionID`,`MemberId`)
);

Xcode 7.2 no matching provisioning profiles found

What I did was: created a new provisioning profile and used it. When setup the provisioning profile in the build setting tab, there were the wrong provisioning profile numbers (like "983ff..." as the error message mentioned, that's it!). Corrected to the new provisioning profile, then Xcode 7.2 refreshed itself, and build successfully.

HTML -- two tables side by side

With CSS: table {float:left;}? ?

Get Base64 encode file-data from Input Form

It's entirely possible in browser-side javascript.

The easy way:

The readAsDataURL() method might already encode it as base64 for you. You'll probably need to strip out the beginning stuff (up to the first ,), but that's no biggie. This would take all the fun out though.

The hard way:

If you want to try it the hard way (or it doesn't work), look at readAsArrayBuffer(). This will give you a Uint8Array and you can use the method specified. This is probably only useful if you want to mess with the data itself, such as manipulating image data or doing other voodoo magic before you upload.

There are two methods:

  • Convert to string and use the built-in btoa or similar
    • I haven't tested all cases, but works for me- just get the char-codes
  • Convert directly from a Uint8Array to base64

I recently implemented tar in the browser. As part of that process, I made my own direct Uint8Array->base64 implementation. I don't think you'll need that, but it's here if you want to take a look; it's pretty neat.

What I do now:

The code for converting to string from a Uint8Array is pretty simple (where buf is a Uint8Array):

function uint8ToString(buf) {
    var i, length, out = '';
    for (i = 0, length = buf.length; i < length; i += 1) {
        out += String.fromCharCode(buf[i]);
    }
    return out;
}

From there, just do:

var base64 = btoa(uint8ToString(yourUint8Array));

Base64 will now be a base64-encoded string, and it should upload just peachy. Try this if you want to double check before pushing:

window.open("data:application/octet-stream;base64," + base64);

This will download it as a file.

Other info:

To get the data as a Uint8Array, look at the MDN docs:

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

Just add remove_button_css as class to your button tag. You can verify the code for Link 1

.remove_button_css { 
  outline: none;
  padding: 5px; 
  border: 0px; 
  box-sizing: none; 
  background-color: transparent; 
}

enter image description here

Extra Styles Edit

Add color: #337ab7; and :hover and :focus to match OOTB (bootstrap3)

.remove_button_css:focus,
.remove_button_css:hover {
    color: #23527c;
    text-decoration: underline;
}

SET versus SELECT when assigning variables?

Quote, which summarizes from this article:

  1. SET is the ANSI standard for variable assignment, SELECT is not.
  2. SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  3. If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  4. When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from its previous value)
  5. As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

Run text file as commands in Bash

you can also just run it with a shell, for example:

bash example.txt

sh example.txt

Python: count repeated elements in the list

You can do that using count:

my_dict = {i:MyList.count(i) for i in MyList}

>>> print my_dict     #or print(my_dict) in python-3.x
{'a': 3, 'c': 3, 'b': 1}

Or using collections.Counter:

from collections import Counter

a = dict(Counter(MyList))

>>> print a           #or print(a) in python-3.x
{'a': 3, 'c': 3, 'b': 1}

center aligning a fixed position div

Normal divs should use margin-left: auto and margin-right: auto, but that doesn't work for fixed divs. The way around this is similar to Andrew's answer, but doesn't use the deprecated <center> thing. Basically, just give the fixed div a wrapper.

_x000D_
_x000D_
#wrapper {_x000D_
    width: 100%;_x000D_
    position: fixed;_x000D_
    background: gray;_x000D_
}_x000D_
#fixed_div {_x000D_
    margin-left: auto;_x000D_
    margin-right: auto;_x000D_
    position: relative;_x000D_
    width: 100px;_x000D_
    height: 30px;_x000D_
    text-align: center;_x000D_
    background: lightgreen;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
    <div id="fixed_div"></div>_x000D_
</div
_x000D_
_x000D_
_x000D_

This will center a fixed div within a div while allowing the div to react with the browser. i.e. The div will be centered if there's enough space, but will collide with the edge of the browser if there isn't; similar to how a regular centered div reacts.

Returning Month Name in SQL Server Query

Select SUBSTRING (convert(varchar,S0.OrderDateTime,100),1,3) from your Table Name

Is Visual Studio Community a 30 day trial?

Remember, if you are inside of private red with some proxy, you must be logout and relogin with an external WIFI for example.

Match all elements having class name starting with a specific string

It's not a direct answer to the question, however I would suggest in most cases to simply set multiple classes to each element:

<div class="myclass one"></div>
<div class="myclass two></div>
<div class="myclass three"></div>

In this way you can set rules for all myclass elements and then more specific rules for one, two and three.

.myclass { color: #f00; }

.two { font-weight: bold; }

etc.

Function to close the window in Tkinter

def exit(self):
    self.frame.destroy()
exit_btn=Button(self.frame,text='Exit',command=self.exit,activebackground='grey',activeforeground='#AB78F1',bg='#58F0AB',highlightcolor='red',padx='10px',pady='3px')
exit_btn.place(relx=0.45,rely=0.35)

This worked for me to destroy my Tkinter frame on clicking the exit button.

HTML5 LocalStorage: Checking if a key exists

Update:

if (localStorage.hasOwnProperty("username")) {
    //
}

Another way, relevant when value is not expected to be empty string, null or any other falsy value:

if (localStorage["username"]) {
    //
}

How to handle onchange event on input type=file in jQuery?

Or could be:

$('input[type=file]').change(function () {
    alert("hola");
});

To be specific: $('input[type=file]#fileUpload1').change(...

Java Read Large Text File With 70million line of text

1) I am sure there is no difference speedwise, both use FileInputStream internally and buffering

2) You can take measurements and see for yourself

3) Though there's no performance benefits I like the 1.7 approach

try (BufferedReader br = Files.newBufferedReader(Paths.get("test.txt"), StandardCharsets.UTF_8)) {
    for (String line = null; (line = br.readLine()) != null;) {
        //
    }
}

4) Scanner based version

    try (Scanner sc = new Scanner(new File("test.txt"), "UTF-8")) {
        while (sc.hasNextLine()) {
            String line = sc.nextLine();
        }
        // note that Scanner suppresses exceptions
        if (sc.ioException() != null) {
            throw sc.ioException();
        }
    }

5) This may be faster than the rest

try (SeekableByteChannel ch = Files.newByteChannel(Paths.get("test.txt"))) {
    ByteBuffer bb = ByteBuffer.allocateDirect(1000);
    for(;;) {
        StringBuilder line = new StringBuilder();
        int n = ch.read(bb);
        // add chars to line
        // ...
    }
}

it requires a bit of coding but it can be really faster because of ByteBuffer.allocateDirect. It allows OS to read bytes from file to ByteBuffer directly, without copying

6) Parallel processing would definitely increase speed. Make a big byte buffer, run several tasks that read bytes from file into that buffer in parallel, when ready find first end of line, make a String, find next...

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

I'm using Linux Mint 18.2 of this writing. I had a similar issue; when trying to load myphpadmin, it said: "1045 - Access denied for user 'root'@'localhost' (using password: NO)"

I found the file in the /opt/lampp/phpmyadmin directory. I opened the config.inc.php file with my text editor and typed in the correct password. Saved it, and launched it successfully. Profit!

I was having problems with modifying folders and files, I had to change permission to access all my files in /opt/lampp/ directory. I hope this helps someone in the future.

How to obtain a QuerySet of all rows, with specific fields for each one of them?

In addition to values_list as Daniel mentions you can also use only (or defer for the opposite effect) to get a queryset of objects only having their id and specified fields:

Employees.objects.only('eng_name')

This will run a single query:

SELECT id, eng_name FROM employees

how to use math.pi in java

Here is usage of Math.PI to find circumference of circle and Area First we take Radius as a string in Message Box and convert it into integer

public class circle {

    public static void main(String[] args) {
        // TODO code application logic here

        String rad;

        float radius,area,circum;

       rad = JOptionPane.showInputDialog("Enter the Radius of circle:");

        radius = Integer.parseInt(rad);
        area = (float) (Math.PI*radius*radius);
        circum = (float) (2*Math.PI*radius);

        JOptionPane.showMessageDialog(null, "Area: " + area,"AREA",JOptionPane.INFORMATION_MESSAGE);
        JOptionPane.showMessageDialog(null, "circumference: " + circum, "Circumfernce",JOptionPane.INFORMATION_MESSAGE);
    }

}

How do I find a list of Homebrew's installable packages?

From the man page:

search, -S text|/text/
Perform a substring search of formula names for text. If text is surrounded with slashes,
then it is interpreted as a regular expression. If no search term is given,
all available formula are displayed.

For your purposes, brew search will suffice.

How to hide form code from view code/inspect element browser?

You can use this code -

Block Right Click -

<body oncontextmenu="return false;">

Block Keys - You should use this on the upper of the body tag. (use in the head tag)

<script>

    document.onkeydown = function (e) {
        if (event.keyCode == 123) {
            return false;
        }
        if (e.ctrlKey && e.shiftKey && (e.keyCode == 'I'.charCodeAt(0) || e.keyCode == 'i'.charCodeAt(0))) {
            return false;
        }
        if (e.ctrlKey && e.shiftKey && (e.keyCode == 'C'.charCodeAt(0) || e.keyCode == 'c'.charCodeAt(0))) {
            return false;
        }
        if (e.ctrlKey && e.shiftKey && (e.keyCode == 'J'.charCodeAt(0) || e.keyCode == 'j'.charCodeAt(0))) {
            return false;
        }
        if (e.ctrlKey && (e.keyCode == 'U'.charCodeAt(0) || e.keyCode == 'u'.charCodeAt(0))) {
            return false;
        }
        if (e.ctrlKey && (e.keyCode == 'S'.charCodeAt(0) || e.keyCode == 's'.charCodeAt(0))) {
            return false;
        }
    }
</script>

IIS7 Cache-Control

If you want to set the Cache-Control header, there's nothing in the IIS7 UI to do this, sadly.

You can however drop this web.config in the root of the folder or site where you want to set it:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" />
    </staticContent>
  </system.webServer>
</configuration>

That will inform the client to cache content for 7 days in that folder and all subfolders.

You can also do this by editing the IIS7 metabase via appcmd.exe, like so:

\Windows\system32\inetsrv\appcmd.exe 
  set config "Default Web Site/folder" 
  -section:system.webServer/staticContent 
  -clientCache.cacheControlMode:UseMaxAge

\Windows\system32\inetsrv\appcmd.exe 
  set config "Default Web Site/folder" 
  -section:system.webServer/staticContent 
  -clientCache.cacheControlMaxAge:"7.00:00:00"

Use of Custom Data Types in VBA

It looks like you want to define Truck as a Class with properties NumberOfAxles, AxleWeights & AxleSpacings.

This can be defined in a CLASS MODULE (here named clsTrucks)

Option Explicit

Private tID As String
Private tNumberOfAxles As Double
Private tAxleSpacings As Double


Public Property Get truckID() As String
    truckID = tID
End Property

Public Property Let truckID(value As String)
    tID = value
End Property

Public Property Get truckNumberOfAxles() As Double
    truckNumberOfAxles = tNumberOfAxles
End Property

Public Property Let truckNumberOfAxles(value As Double)
    tNumberOfAxles = value
End Property

Public Property Get truckAxleSpacings() As Double
    truckAxleSpacings = tAxleSpacings
End Property

Public Property Let truckAxleSpacings(value As Double)
    tAxleSpacings = value
End Property

then in a MODULE the following defines a new truck and it's properties and adds it to a collection of trucks and then retrieves the collection.

Option Explicit

Public TruckCollection As New Collection

Sub DefineNewTruck()
Dim tempTruck As clsTrucks
Dim i As Long

    'Add 5 trucks
    For i = 1 To 5
        Set tempTruck = New clsTrucks
        'Random data
        tempTruck.truckID = "Truck" & i
        tempTruck.truckAxleSpacings = 13.5 + i
        tempTruck.truckNumberOfAxles = 20.5 + i

        'tempTruck.truckID is the collection key
        TruckCollection.Add tempTruck, tempTruck.truckID
    Next i

    'retrieve 5 trucks
    For i = 1 To 5
        'retrieve by collection index
        Debug.Print TruckCollection(i).truckAxleSpacings
        'retrieve by key
        Debug.Print TruckCollection("Truck" & i).truckAxleSpacings

    Next i

End Sub

There are several ways of doing this so it really depends on how you intend to use the data as to whether an a class/collection is the best setup or arrays/dictionaries etc.

Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes

you need to create a new ssh key by typing the following - ssh-keygen -t rsa

Then you need to add: - heroku keys:add

Then if you type - heroku open

The problem has been solved.

It worked for me anyway, you could give it a try...

Numpy first occurrence of value greater than existing value

Arrays that have a constant step between elements

In case of a range or any other linearly increasing array you can simply calculate the index programmatically, no need to actually iterate over the array at all:

def first_index_calculate_range_like(val, arr):
    if len(arr) == 0:
        raise ValueError('no value greater than {}'.format(val))
    elif len(arr) == 1:
        if arr[0] > val:
            return 0
        else:
            raise ValueError('no value greater than {}'.format(val))

    first_value = arr[0]
    step = arr[1] - first_value
    # For linearly decreasing arrays or constant arrays we only need to check
    # the first element, because if that does not satisfy the condition
    # no other element will.
    if step <= 0:
        if first_value > val:
            return 0
        else:
            raise ValueError('no value greater than {}'.format(val))

    calculated_position = (val - first_value) / step

    if calculated_position < 0:
        return 0
    elif calculated_position > len(arr) - 1:
        raise ValueError('no value greater than {}'.format(val))

    return int(calculated_position) + 1

One could probably improve that a bit. I have made sure it works correctly for a few sample arrays and values but that doesn't mean there couldn't be mistakes in there, especially considering that it uses floats...

>>> import numpy as np
>>> first_index_calculate_range_like(5, np.arange(-10, 10))
16
>>> np.arange(-10, 10)[16]  # double check
6

>>> first_index_calculate_range_like(4.8, np.arange(-10, 10))
15

Given that it can calculate the position without any iteration it will be constant time (O(1)) and can probably beat all other mentioned approaches. However it requires a constant step in the array, otherwise it will produce wrong results.

General solution using numba

A more general approach would be using a numba function:

@nb.njit
def first_index_numba(val, arr):
    for idx in range(len(arr)):
        if arr[idx] > val:
            return idx
    return -1

That will work for any array but it has to iterate over the array, so in the average case it will be O(n):

>>> first_index_numba(4.8, np.arange(-10, 10))
15
>>> first_index_numba(5, np.arange(-10, 10))
16

Benchmark

Even though Nico Schlömer already provided some benchmarks I thought it might be useful to include my new solutions and to test for different "values".

The test setup:

import numpy as np
import math
import numba as nb

def first_index_using_argmax(val, arr):
    return np.argmax(arr > val)

def first_index_using_where(val, arr):
    return np.where(arr > val)[0][0]

def first_index_using_nonzero(val, arr):
    return np.nonzero(arr > val)[0][0]

def first_index_using_searchsorted(val, arr):
    return np.searchsorted(arr, val) + 1

def first_index_using_min(val, arr):
    return np.min(np.where(arr > val))

def first_index_calculate_range_like(val, arr):
    if len(arr) == 0:
        raise ValueError('empty array')
    elif len(arr) == 1:
        if arr[0] > val:
            return 0
        else:
            raise ValueError('no value greater than {}'.format(val))

    first_value = arr[0]
    step = arr[1] - first_value
    if step <= 0:
        if first_value > val:
            return 0
        else:
            raise ValueError('no value greater than {}'.format(val))

    calculated_position = (val - first_value) / step

    if calculated_position < 0:
        return 0
    elif calculated_position > len(arr) - 1:
        raise ValueError('no value greater than {}'.format(val))

    return int(calculated_position) + 1

@nb.njit
def first_index_numba(val, arr):
    for idx in range(len(arr)):
        if arr[idx] > val:
            return idx
    return -1

funcs = [
    first_index_using_argmax, 
    first_index_using_min, 
    first_index_using_nonzero,
    first_index_calculate_range_like, 
    first_index_numba, 
    first_index_using_searchsorted, 
    first_index_using_where
]

from simple_benchmark import benchmark, MultiArgument

and the plots were generated using:

%matplotlib notebook
b.plot()

item is at the beginning

b = benchmark(
    funcs,
    {2**i: MultiArgument([0, np.arange(2**i)]) for i in range(2, 20)},
    argument_name="array size")

enter image description here

The numba function performs best followed by the calculate-function and the searchsorted function. The other solutions perform much worse.

item is at the end

b = benchmark(
    funcs,
    {2**i: MultiArgument([2**i-2, np.arange(2**i)]) for i in range(2, 20)},
    argument_name="array size")

enter image description here

For small arrays the numba function performs amazingly fast, however for bigger arrays it's outperformed by the calculate-function and the searchsorted function.

item is at sqrt(len)

b = benchmark(
    funcs,
    {2**i: MultiArgument([np.sqrt(2**i), np.arange(2**i)]) for i in range(2, 20)},
    argument_name="array size")

enter image description here

This is more interesting. Again numba and the calculate function perform great, however this is actually triggering the worst case of searchsorted which really doesn't work well in this case.

Comparison of the functions when no value satisfies the condition

Another interesting point is how these function behave if there is no value whose index should be returned:

arr = np.ones(100)
value = 2

for func in funcs:
    print(func.__name__)
    try:
        print('-->', func(value, arr))
    except Exception as e:
        print('-->', e)

With this result:

first_index_using_argmax
--> 0
first_index_using_min
--> zero-size array to reduction operation minimum which has no identity
first_index_using_nonzero
--> index 0 is out of bounds for axis 0 with size 0
first_index_calculate_range_like
--> no value greater than 2
first_index_numba
--> -1
first_index_using_searchsorted
--> 101
first_index_using_where
--> index 0 is out of bounds for axis 0 with size 0

Searchsorted, argmax, and numba simply return a wrong value. However searchsorted and numba return an index that is not a valid index for the array.

The functions where, min, nonzero and calculate throw an exception. However only the exception for calculate actually says anything helpful.

That means one actually has to wrap these calls in an appropriate wrapper function that catches exceptions or invalid return values and handle appropriately, at least if you aren't sure if the value could be in the array.


Note: The calculate and searchsorted options only work in special conditions. The "calculate" function requires a constant step and the searchsorted requires the array to be sorted. So these could be useful in the right circumstances but aren't general solutions for this problem. In case you're dealing with sorted Python lists you might want to take a look at the bisect module instead of using Numpys searchsorted.

How to stop IIS asking authentication for default website on localhost

It is easier to remove the "Default Web Site" and create a new one if you do not have any limitations.

I did it and my problem solved.

Filter object properties by key in ES6

Simple Way! To do this.

_x000D_
_x000D_
const myData = {_x000D_
  item1: { key: 'sdfd', value:'sdfd' },_x000D_
  item2: { key: 'sdfd', value:'sdfd' },_x000D_
  item3: { key: 'sdfd', value:'sdfd' }_x000D_
};_x000D_
const{item1,item3}=myData_x000D_
const result =({item1,item3})
_x000D_
_x000D_
_x000D_

grant remote access of MySQL database from any IP address

Just create the user to some database like

GRANT ALL PRIVILEGES ON <database_name>.* TO '<username>'@'%' IDENTIFIED BY '<password>'

Then go to

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf and change the line bind-address = 127.0.0.1 to bind-address = 0.0.0.0

After that you may connect to that database from any IP.

How to get IP address of running docker container

Use --format option to get only the IP address instead whole container info:

sudo docker inspect --format '{{ .NetworkSettings.IPAddress }}' <CONTAINER ID>

jQuery UI - Draggable is not a function?

You can import these js Files. It worked fine for me.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>  
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js" ></script>

What is the scope of variables in JavaScript?

Just to add to the other answers, scope is a look-up list of all the declared identifiers (variables), and enforces a strict set of rules as to how these are accessible to currently executing code. This look-up may be for the purposes of assigning to the variable, which is an LHS (lefthand-side) reference, or it may be for the purposes of retrieving its value, which is an RHS (righthand-side) reference. These look-ups are what the JavaScript engine is doing internally when it's compiling and executing the code.

So from this perspective, I think that a picture would help that I found in the Scopes and Closures ebook by Kyle Simpson:

image

Quoting from his ebook:

The building represents our program’s nested scope ruleset. The first floor of the building represents your currently executing scope, wherever you are. The top level of the building is the global scope. You resolve LHS and RHS references by looking on your current floor, and if you don’t find it, taking the elevator to the next floor, looking there, then the next, and so on. Once you get to the top floor (the global scope), you either find what you’re looking for, or you don’t. But you have to stop regardless.

One thing of note that is worth mentioning, "Scope look-up stops once it finds the first match".

This idea of "scope levels" explains why "this" can be changed with a newly created scope, if it's being looked up in a nested function. Here is a link that goes into all these details, Everything you wanted to know about javascript scope

Key Value Pair List

Using one of the subsets method in this question

var list = new List<KeyValuePair<string, int>>() { 
    new KeyValuePair<string, int>("A", 1),
    new KeyValuePair<string, int>("B", 0),
    new KeyValuePair<string, int>("C", 0),
    new KeyValuePair<string, int>("D", 2),
    new KeyValuePair<string, int>("E", 8),
};

int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);

EDIT

a full console application:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<KeyValuePair<string, int>>() { 
                new KeyValuePair<string, int>("A", 1),
                new KeyValuePair<string, int>("B", 2),
                new KeyValuePair<string, int>("C", 3),
                new KeyValuePair<string, int>("D", 4),
                new KeyValuePair<string, int>("E", 5),
                new KeyValuePair<string, int>("F", 6),
            };

            int input = 12;
            var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);

            foreach (var res in alternatives)
            {
                Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
            }
            Console.WriteLine("END");
            Console.ReadLine();
        }
    }

    public static class Extenions
    {
        public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
        {
            List<T> list = enumerable.ToList();
            ulong upper = (ulong)1 << list.Count;

            for (ulong i = 0; i < upper; i++)
            {
                List<T> l = new List<T>(list.Count);
                for (int j = 0; j < sizeof(ulong) * 8; j++)
                {
                    if (((ulong)1 << j) >= upper) break;

                    if (((i >> j) & 1) == 1)
                    {
                        l.Add(list[j]);
                    }
                }

                yield return l;
            }
        }
    }
}

AngularJS - Building a dynamic table based on a json

TGrid is another option that people don't usually find in a google search. If the other grids you find don't suit your needs, you can give it a try, its free

How to color System.out.println output?

Here is a solution for Win32 Console.

1) Get JavaNativeAccess libraries here: https://github.com/twall/jna/

2) These two Java classes will do the trick.

Enjoy.

package com.stackoverflow.util;

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.Structure;

public class Win32 {
    public static final int STD_INPUT_HANDLE = -10;
    public static final int STD_OUTPUT_HANDLE = -11;
    public static final int STD_ERROR_HANDLE = -12;

    public static final short CONSOLE_FOREGROUND_COLOR_BLACK        = 0x00;
    public static final short CONSOLE_FOREGROUND_COLOR_BLUE         = 0x01;
    public static final short CONSOLE_FOREGROUND_COLOR_GREEN        = 0x02;
    public static final short CONSOLE_FOREGROUND_COLOR_AQUA         = 0x03;
    public static final short CONSOLE_FOREGROUND_COLOR_RED          = 0x04;
    public static final short CONSOLE_FOREGROUND_COLOR_PURPLE       = 0x05;
    public static final short CONSOLE_FOREGROUND_COLOR_YELLOW       = 0x06;
    public static final short CONSOLE_FOREGROUND_COLOR_WHITE        = 0x07;
    public static final short CONSOLE_FOREGROUND_COLOR_GRAY         = 0x08;
    public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_BLUE   = 0x09;
    public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_GREEN  = 0x0A;
    public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_AQUA   = 0x0B;
    public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_RED    = 0x0C;
    public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_PURPLE = 0x0D;
    public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_YELLOW = 0x0E;
    public static final short CONSOLE_FOREGROUND_COLOR_BRIGHT_WHITE = 0x0F;

    public static final short CONSOLE_BACKGROUND_COLOR_BLACK        = 0x00;
    public static final short CONSOLE_BACKGROUND_COLOR_BLUE         = 0x10;
    public static final short CONSOLE_BACKGROUND_COLOR_GREEN        = 0x20;
    public static final short CONSOLE_BACKGROUND_COLOR_AQUA         = 0x30;
    public static final short CONSOLE_BACKGROUND_COLOR_RED          = 0x40;
    public static final short CONSOLE_BACKGROUND_COLOR_PURPLE       = 0x50;
    public static final short CONSOLE_BACKGROUND_COLOR_YELLOW       = 0x60;
    public static final short CONSOLE_BACKGROUND_COLOR_WHITE        = 0x70;
    public static final short CONSOLE_BACKGROUND_COLOR_GRAY         = 0x80;
    public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_BLUE   = 0x90;
    public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_GREEN  = 0xA0;
    public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_AQUA   = 0xB0;
    public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_RED    = 0xC0;
    public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_PURPLE = 0xD0;
    public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_YELLOW = 0xE0;
    public static final short CONSOLE_BACKGROUND_COLOR_BRIGHT_WHITE = 0xF0;

    // typedef struct _COORD {
    //    SHORT X;
    //    SHORT Y;
    //  } COORD, *PCOORD;
    public static class COORD extends Structure {
        public short X;
        public short Y;
    }

    // typedef struct _SMALL_RECT {
    //    SHORT Left;
    //    SHORT Top;
    //    SHORT Right;
    //    SHORT Bottom;
    //  } SMALL_RECT;
    public static class SMALL_RECT extends Structure {
        public short Left;
        public short Top;
        public short Right;
        public short Bottom;
    }

    // typedef struct _CONSOLE_SCREEN_BUFFER_INFO {
    //    COORD      dwSize;
    //    COORD      dwCursorPosition;
    //    WORD       wAttributes;
    //    SMALL_RECT srWindow;
    //    COORD      dwMaximumWindowSize;
    //  } CONSOLE_SCREEN_BUFFER_INFO;
    public static class CONSOLE_SCREEN_BUFFER_INFO extends Structure {
        public COORD dwSize;
        public COORD dwCursorPosition;
        public short wAttributes;
        public SMALL_RECT srWindow;
        public COORD dwMaximumWindowSize;
    }

    // Source: https://github.com/twall/jna/nonav/javadoc/index.html
    public interface Kernel32 extends Library {
        Kernel32 DLL = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);

        // HANDLE WINAPI GetStdHandle(
        //        __in  DWORD nStdHandle
        //      );
        public int GetStdHandle(
                int nStdHandle);

        // BOOL WINAPI SetConsoleTextAttribute(
        //        __in  HANDLE hConsoleOutput,
        //        __in  WORD wAttributes
        //      );
        public boolean SetConsoleTextAttribute(
                int in_hConsoleOutput, 
                short in_wAttributes);

        // BOOL WINAPI GetConsoleScreenBufferInfo(
        //        __in   HANDLE hConsoleOutput,
        //        __out  PCONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo
        //      );
        public boolean GetConsoleScreenBufferInfo(
                int in_hConsoleOutput,
                CONSOLE_SCREEN_BUFFER_INFO out_lpConsoleScreenBufferInfo);

        // DWORD WINAPI GetLastError(void);
        public int GetLastError();
    }
}
package com.stackoverflow.util;

import java.io.PrintStream;

import com.stackoverflow.util.Win32.Kernel32;

public class ConsoleUtil {
    public static void main(String[] args)
    throws Exception {
        System.out.print("abc");
        static_color_print(
                System.out, 
                "def", 
                Win32.CONSOLE_BACKGROUND_COLOR_RED, 
                Win32.CONSOLE_FOREGROUND_COLOR_BRIGHT_WHITE);
        System.out.print("def");
        System.out.println();
    }

    private static Win32.CONSOLE_SCREEN_BUFFER_INFO _static_console_screen_buffer_info = null; 

    public static void static_save_settings() {
        if (null == _static_console_screen_buffer_info) {
            _static_console_screen_buffer_info = new Win32.CONSOLE_SCREEN_BUFFER_INFO();
        }
        int stdout_handle = Kernel32.DLL.GetStdHandle(Win32.STD_OUTPUT_HANDLE);
        Kernel32.DLL.GetConsoleScreenBufferInfo(stdout_handle, _static_console_screen_buffer_info);
    }

    public static void static_restore_color()
    throws Exception {
        if (null == _static_console_screen_buffer_info) {
            throw new Exception("Internal error: Must save settings before restore");
        }
        int stdout_handle = Kernel32.DLL.GetStdHandle(Win32.STD_OUTPUT_HANDLE);
        Kernel32.DLL.SetConsoleTextAttribute(
                stdout_handle, 
                _static_console_screen_buffer_info.wAttributes);
    }

    public static void static_set_color(Short background_color, Short foreground_color) {
        int stdout_handle = Kernel32.DLL.GetStdHandle(Win32.STD_OUTPUT_HANDLE);
        if (null == background_color || null == foreground_color) {
            Win32.CONSOLE_SCREEN_BUFFER_INFO console_screen_buffer_info = 
                new Win32.CONSOLE_SCREEN_BUFFER_INFO();
            Kernel32.DLL.GetConsoleScreenBufferInfo(stdout_handle, console_screen_buffer_info);
            short current_bg_and_fg_color = console_screen_buffer_info.wAttributes;
            if (null == background_color) {
                short current_bg_color = (short) (current_bg_and_fg_color / 0x10);
                background_color = new Short(current_bg_color);
            }
            if (null == foreground_color) {
                short current_fg_color = (short) (current_bg_and_fg_color % 0x10);
                foreground_color = new Short(current_fg_color);
            }
        }
        short bg_and_fg_color = 
            (short) (background_color.shortValue() | foreground_color.shortValue());
        Kernel32.DLL.SetConsoleTextAttribute(stdout_handle, bg_and_fg_color);
    }

    public static<T> void static_color_print(
            PrintStream ostream, 
            T value, 
            Short background_color, 
            Short foreground_color)
    throws Exception {
        static_save_settings();
        try {
            static_set_color(background_color, foreground_color);
            ostream.print(value);
        }
        finally {
            static_restore_color();
        }
    }

    public static<T> void static_color_println(
            PrintStream ostream, 
            T value, 
            Short background_color, 
            Short foreground_color)
    throws Exception {
        static_save_settings();
        try {
            static_set_color(background_color, foreground_color);
            ostream.println(value);
        }
        finally {
            static_restore_color();
        }
    }
}

Spark: subtract two DataFrames

According to the api docs, doing:

dataFrame1.except(dataFrame2)

will return a new DataFrame containing rows in dataFrame1 but not in dataframe2.

Plot a line graph, error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ

plot(t) is in this case the same as

plot(t[[1]], t[[2]])

As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1:

> length(t)
[1] 4
> length(1)
[1] 1

In your second example you plot a list with elements named x and y, both vectors of length 2, so plot plots these two vectors.

Edit:

If you want to plot lines use

plot(t, type="l")

How do I output lists as a table in Jupyter notebook?

You could try to use the following function

def tableIt(data):
    for lin in data:
        print("+---"*len(lin)+"+")
        for inlin in lin:
            print("|",str(inlin),"", end="")
        print("|")
    print("+---"*len(lin)+"+")

data = [[1,2,3,2,3],[1,2,3,2,3],[1,2,3,2,3],[1,2,3,2,3]]

tableIt(data)

How to set all elements of an array to zero or any same value?

You could use memset, if you sure about the length.

memset(ptr, 0x00, length)

sudo in php exec()

The best secure method is to use the crontab. ie Save all your commands in a database say, mysql table and create a cronjob to read these mysql entreis and execute via exec() or shell_exec(). Please read this link for more detailed information.

          • killProcess.php

How do I configure HikariCP in my Spring Boot app in my application.properties files?

@Configuration
@ConfigurationProperties(prefix = "params.datasource")
public class JpaConfig extends HikariConfig {

    @Bean
    public DataSource dataSource() throws SQLException {
        return new HikariDataSource(this);
    }

}

application.yml

params:
  datasource:
    driverClassName: com.mysql.jdbc.Driver
    jdbcUrl: jdbc:mysql://localhost:3306/myDb
    username: login
    password: password
    maximumPoolSize: 5

UPDATED! Since version Spring Boot 1.3.0 :

  1. Just add HikariCP to dependencies
  2. Configure application.yml

application.yml

spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    url: jdbc:h2:mem:TEST
    driver-class-name: org.h2.Driver
    username: username
    password: password
    hikari:
      idle-timeout: 10000

UPDATED! Since version Spring Boot 2.0.0 :

The default connection pool has changed from Tomcat to Hikari :)

What is console.log?

I really feel web programming easy when i start console.log for debugging.

var i;

If i want to check value of i runtime..

console.log(i);

you can check current value of i in firebug's console tab. It is specially used for debugging.

How to trigger a click on a link using jQuery

Shortest answer:

$('#titlee a').click();

Retrieve specific commit from a remote Git repository

You only clone once, so if you already have a clone of the remote repository, pulling from it won't download everything again. Just indicate what branch you want to pull, or fetch the changes and checkout the commit you want.

Fetching from a new repository is very cheap in bandwidth, as it will only download the changes you don't have. Think in terms of Git making the right thing, with minimum load.

Git stores everything in .git folder. A commit can't be fetched and stored in isolation, it needs all its ancestors. They are interrelated.


To reduce download size you can however ask git to fetch only objects related to a specific branch or commit:

git fetch origin refs/heads/branch:refs/remotes/origin/branch

This will download only commits contained in remote branch branch (and only the ones that you miss), and store it in origin/branch. You can then merge or checkout.

You can also specify only a SHA1 commit:

git fetch origin 96de5297df870:refs/remotes/origin/foo-commit

This will download only the commit of the specified SHA-1 96de5297df870 (and its ancestors that you miss), and store it as (non-existing) remote branch origin/foo-commit.

Bootstrap select dropdown list placeholder

  1. in bootstrap-select.js Find title: null, and remove it.
  2. add title="YOUR TEXT" in <select> element.
  3. Fine :)

Example:

<select title="Please Choose one item">
    <option value="">A</option>
    <option value="">B</option>
    <option value="">C</option>
</select>

Disabling of EditText in Android

android:editable="false"

is now deprecated and use

 YourEditText.setInputType(InputType.TYPE_NULL);

LF will be replaced by CRLF in git - What is that and is it important?

If you want, you can deactivate this feature in your git core config using

git config core.autocrlf false

But it would be better to just get rid of the warnings using

git config core.autocrlf true

Propagation Delay vs Transmission delay

The transmission delay is the amount of time required for the router to push out the packet.

The propagation delay, is the time it takes a bit to propagate from one router to the next.

the transmission and propagation delay are completely different! if denote the length of the packet by L bits, and denote the transmission rate of the link from first router to second router by R bits/sec. then transmission delay will be L/R. and this is depended to transmission rate of link and the length of packet.

then if denote the distance between two routers d and denote the propagation speed s, the propagation delay will be d/s. it is a function of the Distance between the two routers, but has no dependence to the packet's length or the transmission rate of the link.

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

JAD Decomplier plug-in for Eclipse version 3.x and 4.x.

update site: http://feeling.sourceforge.net/update

Steps:

  1. Open Eclipse IDE.
  2. Click Help->Install New software
  3. Paste above URL and give name as JAD.
  4. Select the Eclipse Class Decompiler
  5. Click on Next and accept agreements
  6. Install it.
  7. Restart Eclipse and check now.

How to hide the title bar for an Activity in XML with existing custom theme

You just need to change AppTheme style in Style.xml if you replace the definition from DarkActionBar

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

to NoActionBar

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

the AppTheme defined in AndroidManifast.xml

String Concatenation in EL

it also can be a great idea using concat for EL + MAP + JSON problem like in this example :

#{myMap[''.concat(myid)].content}

How to return JSon object

First of all, there's no such thing as a JSON object. What you've got in your question is a JavaScript object literal (see here for a great discussion on the difference). Here's how you would go about serializing what you've got to JSON though:

I would use an anonymous type filled with your results type:

string json = JsonConvert.SerializeObject(new
{
    results = new List<Result>()
    {
        new Result { id = 1, value = "ABC", info = "ABC" },
        new Result { id = 2, value = "JKL", info = "JKL" }
    }
});

Also, note that the generated JSON has result items with ids of type Number instead of strings. I doubt this will be a problem, but it would be easy enough to change the type of id to string in the C#.

I'd also tweak your results type and get rid of the backing fields:

public class Result
{
    public int id { get ;set; }
    public string value { get; set; }
    public string info { get; set; }
}

Furthermore, classes conventionally are PascalCased and not camelCased.

Here's the generated JSON from the code above:

{
  "results": [
    {
      "id": 1,
      "value": "ABC",
      "info": "ABC"
    },
    {
      "id": 2,
      "value": "JKL",
      "info": "JKL"
    }
  ]
}

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

Using if-else in JSP

You may try this example:

_x000D_
_x000D_
<form>_x000D_
  <h1>Hello! I'm duke! What's you name?</h1>_x000D_
  <input type="text" name="user">_x000D_
  <br>_x000D_
  <br>_x000D_
  <input type="submit" value="submit">&nbsp;&nbsp;&nbsp;&nbsp;_x000D_
  <input type="reset">_x000D_
</form>_x000D_
<h1>Hello ${param.user}</h1> _x000D_
<!-- its Expression Language -->
_x000D_
_x000D_
_x000D_

How can I implement a tree in Python?

I've implemented trees using nested dicts. It is quite easy to do, and it has worked for me with pretty large data sets. I've posted a sample below, and you can see more at Google code

  def addBallotToTree(self, tree, ballotIndex, ballot=""):
    """Add one ballot to the tree.

    The root of the tree is a dictionary that has as keys the indicies of all 
    continuing and winning candidates.  For each candidate, the value is also
    a dictionary, and the keys of that dictionary include "n" and "bi".
    tree[c]["n"] is the number of ballots that rank candidate c first.
    tree[c]["bi"] is a list of ballot indices where the ballots rank c first.

    If candidate c is a winning candidate, then that portion of the tree is
    expanded to indicate the breakdown of the subsequently ranked candidates.
    In this situation, additional keys are added to the tree[c] dictionary
    corresponding to subsequently ranked candidates.
    tree[c]["n"] is the number of ballots that rank candidate c first.
    tree[c]["bi"] is a list of ballot indices where the ballots rank c first.
    tree[c][d]["n"] is the number of ballots that rank c first and d second.
    tree[c][d]["bi"] is a list of the corresponding ballot indices.

    Where the second ranked candidates is also a winner, then the tree is 
    expanded to the next level.  

    Losing candidates are ignored and treated as if they do not appear on the 
    ballots.  For example, tree[c][d]["n"] is the total number of ballots
    where candidate c is the first non-losing candidate, c is a winner, and
    d is the next non-losing candidate.  This will include the following
    ballots, where x represents a losing candidate:
    [c d]
    [x c d]
    [c x d]
    [x c x x d]

    During the count, the tree is dynamically updated as candidates change
    their status.  The parameter "tree" to this method may be the root of the
    tree or may be a sub-tree.
    """

    if ballot == "":
      # Add the complete ballot to the tree
      weight, ballot = self.b.getWeightedBallot(ballotIndex)
    else:
      # When ballot is not "", we are adding a truncated ballot to the tree,
      # because a higher-ranked candidate is a winner.
      weight = self.b.getWeight(ballotIndex)

    # Get the top choice among candidates still in the running
    # Note that we can't use Ballots.getTopChoiceFromWeightedBallot since
    # we are looking for the top choice over a truncated ballot.
    for c in ballot:
      if c in self.continuing | self.winners:
        break # c is the top choice so stop
    else:
      c = None # no candidates left on this ballot

    if c is None:
      # This will happen if the ballot contains only winning and losing
      # candidates.  The ballot index will not need to be transferred
      # again so it can be thrown away.
      return

    # Create space if necessary.
    if not tree.has_key(c):
      tree[c] = {}
      tree[c]["n"] = 0
      tree[c]["bi"] = []

    tree[c]["n"] += weight

    if c in self.winners:
      # Because candidate is a winner, a portion of the ballot goes to
      # the next candidate.  Pass on a truncated ballot so that the same
      # candidate doesn't get counted twice.
      i = ballot.index(c)
      ballot2 = ballot[i+1:]
      self.addBallotToTree(tree[c], ballotIndex, ballot2)
    else:
      # Candidate is in continuing so we stop here.
      tree[c]["bi"].append(ballotIndex)

Populate XDocument from String

You can use XDocument.Parse(string) instead of Load(string).

How to create a connection string in asp.net c#

Demo :

<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>

Based on your question:

<connectionStrings>
    <add name="itmall" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />
    </connectionStrings>

Refer links:

http://www.connectionstrings.com/store-connection-string-in-webconfig/

Retrive connection string from web.config file:

write the below code in your file where you want;

string connstring=ConfigurationManager.ConnectionStrings["itmall"].ConnectionString;

SqlConnection con = new SqlConnection(connstring);

or you can go in your way like

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["itmall"].ConnectionString);

Note:

The "name" which you gave in web.config file and name which you used in connection string must be same(like "itmall" in this solution.)

How can I convert a string to a float in mysql?

It turns out I was just missing DECIMAL on the CAST() description:

DECIMAL[(M[,D])]

Converts a value to DECIMAL data type. The optional arguments M and D specify the precision (M specifies the total number of digits) and the scale (D specifies the number of digits after the decimal point) of the decimal value. The default precision is two digits after the decimal point.

Thus, the following query worked:

UPDATE table SET
latitude = CAST(old_latitude AS DECIMAL(10,6)),
longitude = CAST(old_longitude AS DECIMAL(10,6));

Why is my asynchronous function returning Promise { <pending> } instead of a value?

I had the same issue earlier, but my situation was a bit different in the front-end. I'll share my scenario anyway, maybe someone might find it useful.

I had an api call to /api/user/register in the frontend with email, password and username as request body. On submitting the form(register form), a handler function is called which initiates the fetch call to /api/user/register. I used the event.preventDefault() in the beginning line of this handler function, all other lines,like forming the request body as well the fetch call was written after the event.preventDefault(). This returned a pending promise.

But when I put the request body formation code above the event.preventDefault(), it returned the real promise. Like this:

event.preventDefault();
    const data = {
        'email': email,
        'password': password
    }
    fetch(...)
     ...

instead of :

     const data = {
            'email': email,
            'password': password
        }
     event.preventDefault();
     fetch(...)
     ...

Java: How to get input from System.console()

There are few ways to read input string from your console/keyboard. The following sample code shows how to read a string from the console/keyboard by using Java.

public class ConsoleReadingDemo {

public static void main(String[] args) {

    // ====
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Please enter user name : ");
    String username = null;
    try {
        username = reader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("You entered : " + username);

    // ===== In Java 5, Java.util,Scanner is used for this purpose.
    Scanner in = new Scanner(System.in);
    System.out.print("Please enter user name : ");
    username = in.nextLine();      
    System.out.println("You entered : " + username);


    // ====== Java 6
    Console console = System.console();
    username = console.readLine("Please enter user name : ");   
    System.out.println("You entered : " + username);

}
}

The last part of code used java.io.Console class. you can not get Console instance from System.console() when running the demo code through Eclipse. Because eclipse runs your application as a background process and not as a top-level process with a system console.

git remote add with other SSH port

Best answer doesn't work for me. I needed ssh:// from the beggining.

# does not work
git remote set-url origin [email protected]:10000/aaa/bbbb/ccc.git
# work
git remote set-url origin ssh://[email protected]:10000/aaa/bbbb/ccc.git

command to remove row from a data frame

eldNew <- eld[-14,]

See ?"[" for a start ...

For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.

(emphasis added)

edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?

edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame ...

Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame

Compile to a stand-alone executable (.exe) in Visual Studio

Anything using the managed environment (which includes anything written in C# and VB.NET) requires the .NET framework. You can simply redistribute your .EXE in that scenario, but they'll need to install the appropriate framework if they don't already have it.

How to do date/time comparison

For comparison between two times use time.Sub()

// utc life
loc, _ := time.LoadLocation("UTC")

// setup a start and end time
createdAt := time.Now().In(loc).Add(1 * time.Hour)
expiresAt := time.Now().In(loc).Add(4 * time.Hour)

// get the diff
diff := expiresAt.Sub(createdAt)
fmt.Printf("Lifespan is %+v", diff)

The program outputs:

Lifespan is 3h0m0s

http://play.golang.org/p/bbxeTtd4L6

In PHP with PDO, how to check the final SQL parametrized query?

The easiest way it can be done is by reading mysql execution log file and you can do that in runtime.

There is a nice explanation here:

How to show the last queries executed on MySQL?

Identifier not found error on function call

You have to define void swapCase before the main definition.

jQuery access input hidden value

To get value, use:

$.each($('input'),function(i,val){
    if($(this).attr("type")=="hidden"){
        var valueOfHidFiled=$(this).val();
        alert(valueOfHidFiled);
    }
});

or:

var valueOfHidFiled=$('input[type=hidden]').val();
alert(valueOfHidFiled);

To set value, use:

$('input[type=hidden]').attr('value',newValue);

How to make JQuery-AJAX request synchronous

The below is a working example. Add async:false.

const response = $.ajax({
                    type:"POST",
                    dataType:"json",
                    async:false, 
                    url:"your-url",
                    data:{"data":"data"}                        
                });                   
 console.log("response: ", response);

VBA (Excel) Initialize Entire Array without Looping

You can initialize the array by specifying the dimensions. For example

Dim myArray(10) As Integer
Dim myArray(1 to 10) As Integer

If you are working with arrays and if this is your first time then I would recommend visiting Chip Pearson's WEBSITE.

What does this initialize to? For example, what if I want to initialize the entire array to 13?

When you want to initailize the array of 13 elements then you can do it in two ways

Dim myArray(12) As Integer
Dim myArray(1 to 13) As Integer

In the first the lower bound of the array would start with 0 so you can store 13 elements in array. For example

myArray(0) = 1
myArray(1) = 2
'
'
'
myArray(12) = 13

In the second example you have specified the lower bounds as 1 so your array starts with 1 and can again store 13 values

myArray(1) = 1
myArray(2) = 2
'
'
'
myArray(13) = 13

Wnen you initialize an array using any of the above methods, the value of each element in the array is equal to 0. To check that try this code.

Sub Sample()
    Dim myArray(12) As Integer
    Dim i As Integer

    For i = LBound(myArray) To UBound(myArray)
        Debug.Print myArray(i)
    Next i
End Sub

or

Sub Sample()
    Dim myArray(1 to 13) As Integer
    Dim i As Integer

    For i = LBound(myArray) To UBound(myArray)
        Debug.Print myArray(i)
    Next i
End Sub

FOLLOWUP FROM COMMENTS

So, in this example every value would be 13. So if I had an array Dim myArray(300) As Integer, all 300 elements would hold the value 13

Like I mentioned, AFAIK, there is no direct way of achieving what you want. Having said that here is one way which uses worksheet function Rept to create a repetitive string of 13's. Once we have that string, we can use SPLIT using "," as a delimiter. But note this creates a variant array but can be used in calculations.

Note also, that in the following examples myArray will actually hold 301 values of which the last one is empty - you would have to account for that by additionally initializing this value or removing the last "," from sNum before the Split operation.

Sub Sample()
    Dim sNum As String
    Dim i As Integer
    Dim myArray

    '~~> Create a string with 13 three hundred times separated by comma
    '~~> 13,13,13,13...13,13 (300 times)
    sNum = WorksheetFunction.Rept("13,", 300)
    sNum = Left(sNum, Len(sNum) - 1)

    myArray = Split(sNum, ",")

    For i = LBound(myArray) To UBound(myArray)
        Debug.Print myArray(i)
    Next i
End Sub

Using the variant array in calculations

Sub Sample()
    Dim sNum As String
    Dim i As Integer
    Dim myArray

    '~~> Create a string with 13 three hundred times separated by comma
    sNum = WorksheetFunction.Rept("13,", 300)
    sNum = Left(sNum, Len(sNum) - 1)

    myArray = Split(sNum, ",")

    For i = LBound(myArray) To UBound(myArray)
        Debug.Print Val(myArray(i)) + Val(myArray(i))
    Next i
End Sub

What's the difference between KeyDown and KeyPress in .NET?

From MSDN:

Key events occur in the following order:

  1. KeyDown

  2. KeyPress

  3. KeyUp

Furthermore, KeyPress gives you a chance to declare the action as "handled" to prevent it from doing anything.

Remove a file from a Git repository without deleting it from the local filesystem

If you want to just untrack a file and not delete from local and remote repo then use this command:

git update-index --assume-unchanged  file_name_with_path

What is a callback in java

Callbacks are most easily described in terms of the telephone system. A function call is analogous to calling someone on a telephone, asking her a question, getting an answer, and hanging up; adding a callback changes the analogy so that after asking her a question, you also give her your name and number so she can call you back with the answer.

Paul Jakubik, Callback Implementations in C++.

Understanding the map function

map doesn't relate to a Cartesian product at all, although I imagine someone well versed in functional programming could come up with some impossible to understand way of generating a one using map.

map in Python 3 is equivalent to this:

def map(func, iterable):
    for i in iterable:
        yield func(i)

and the only difference in Python 2 is that it will build up a full list of results to return all at once instead of yielding.

Although Python convention usually prefers list comprehensions (or generator expressions) to achieve the same result as a call to map, particularly if you're using a lambda expression as the first argument:

[func(i) for i in iterable]

As an example of what you asked for in the comments on the question - "turn a string into an array", by 'array' you probably want either a tuple or a list (both of them behave a little like arrays from other languages) -

 >>> a = "hello, world"
 >>> list(a)
['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> tuple(a)
('h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd')

A use of map here would be if you start with a list of strings instead of a single string - map can listify all of them individually:

>>> a = ["foo", "bar", "baz"]
>>> list(map(list, a))
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]

Note that map(list, a) is equivalent in Python 2, but in Python 3 you need the list call if you want to do anything other than feed it into a for loop (or a processing function such as sum that only needs an iterable, and not a sequence). But also note again that a list comprehension is usually preferred:

>>> [list(b) for b in a]
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]

How to add hours to current time in python

Import datetime and timedelta:

>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'

But the better way is:

>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'

You can refer strptime and strftime behavior to better understand how python processes dates and time field

PHP Echo text Color

this works for me every time try this.

echo "<font color='blue'>".$myvariable."</font>";

since font is not supported in html5 you can do this

echo "<p class="variablecolor">".$myvariable."</p>";

then in css do

.variablecolor{
color: blue;}

Regular Expression to get a string between parentheses in Javascript

Simple: (?<value>(?<=\().*(?=\)))

I hope I've helped.

Get response from PHP file using AJAX

var data="your data";//ex data="id="+id;
      $.ajax({
       method : "POST",
       url : "file name",  //url: "demo.php"
       data : "data",
       success : function(result){
               //set result to div or target 
              //ex $("#divid).html(result)
        }
   });

How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

You can define foreign key by:

public class Parent
{
   public int Id { get; set; }
   public virtual ICollection<Child> Childs { get; set; }
}

public class Child
{
   public int Id { get; set; }
   // This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
   public int ParentId { get; set; } 
   public virtual Parent Parent { get; set; }
}

Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.

If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation

Data annotation:

// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }

Fluent API:

modelBuilder.Entity<Child>()
            .HasRequired(c => c.Parent)
            .WithMany(p => p.Childs)
            .HasForeignKey(c => c.ParentId);

Other types of constraints can be enforced by data annotations and model validation.

Edit:

You will get an exception if you don't set ParentId. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.

MVC 4 Data Annotations "Display" Attribute

Also internationalization.

I fooled around with this some a while back. Did this in my model:

[Display(Name = "XXX", ResourceType = typeof(Labels))]

I had a separate class library for all the resources, so I had Labels.resx, Labels.culture.resx, etc.

In there I had key = XXX, value = "meaningful string in that culture."

Regex to extract URLs from href attribute in HTML with Python

The best answer is...

Don't use a regex

The expression in the accepted answer misses many cases. Among other things, URLs can have unicode characters in them. The regex you want is here, and after looking at it, you may conclude that you don't really want it after all. The most correct version is ten-thousand characters long.

Admittedly, if you were starting with plain, unstructured text with a bunch of URLs in it, then you might need that ten-thousand-character-long regex. But if your input is structured, use the structure. Your stated aim is to "extract the url, inside the anchor tag's href." Why use a ten-thousand-character-long regex when you can do something much simpler?

Parse the HTML instead

For many tasks, using Beautiful Soup will be far faster and easier to use:

>>> from bs4 import BeautifulSoup as Soup
>>> html = Soup(s, 'html.parser')           # Soup(s, 'lxml') if lxml is installed
>>> [a['href'] for a in html.find_all('a')]
['http://example.com', 'http://example2.com']

If you prefer not to use external tools, you can also directly use Python's own built-in HTML parsing library. Here's a really simple subclass of HTMLParser that does exactly what you want:

from html.parser import HTMLParser

class MyParser(HTMLParser):
    def __init__(self, output_list=None):
        HTMLParser.__init__(self)
        if output_list is None:
            self.output_list = []
        else:
            self.output_list = output_list
    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            self.output_list.append(dict(attrs).get('href'))

Test:

>>> p = MyParser()
>>> p.feed(s)
>>> p.output_list
['http://example.com', 'http://example2.com']

You could even create a new method that accepts a string, calls feed, and returns output_list. This is a vastly more powerful and extensible way than regular expressions to extract information from html.

Days between two dates?

Try:

(b-a).days

I tried with b and a of type datetime.date.

ssl.SSLError: tlsv1 alert protocol version

For python2 users on MacOS (python@2 formula won't be found), as brew stopped support of python2 you need to use such command! But don't forget to unlink old python if it was pre-installed.

brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/86a44a0a552c673a05f11018459c9f5faae3becc/Formula/[email protected]

If you've done some mistake, simply brew uninstall python@2 old way, and try again.

thank you hyperknot (answer here)

How to name an object within a PowerPoint slide?

Yes. Click on the object (textbox, shape, etc.) to select the object and in the Drawing Tools | Format tab, click on Selection Pane in the Arrange group. From there, you'll see names of objects - you can double click (or press F2) on any name and rename it. By deselecting it, it becomes renamed. You can also get to this from the Home tab -> Drawing group -> Arrange drop-down -> Selection pane or by pressing ALT + F10.

How to update parent's state in React?

If this same scenario is not spread everywhere you can use React's context, specially if you don't want to introduce all the overhead that state management libraries introduce. Plus, it's easier to learn. But be careful, you could overuse it and start writing bad code. Basically you define a Container component (that will hold and keep that piece of state for you) making all the components interested in writing/reading that piece of data its children (not necessarily direct children)

https://reactjs.org/docs/context.html

You could also use plain React properly instead.

<Component5 onSomethingHappenedIn5={this.props.doSomethingAbout5} />

pass doSomethingAbout5 up to Component 1

    <Component1>
        <Component2 onSomethingHappenedIn5={somethingAbout5 => this.setState({somethingAbout5})}/>
        <Component5 propThatDependsOn5={this.state.somethingAbout5}/>
    <Component1/>

If this a common problem you should starting thinking moving the whole state of the application to someplace else. You have a few options, the most common are:

https://redux.js.org/

https://facebook.github.io/flux/

Basically, instead of managing the application state in your component you send commands when something happens to get the state updated. Components pull the state from this container as well so all the data is centralized. This doesn't mean can't use local state anymore, but that's a more advanced topic.

Difference between MongoDB and Mongoose

Mongodb and Mongoose are two different drivers to interact with MongoDB database.

Mongoose : object data modeling (ODM) library that provides a rigorous modeling environment for your data. Used to interact with MongoDB, it makes life easier by providing convenience in managing data.

Mongodb: native driver in Node.js to interact with MongoDB.

Accessing a resource via codebehind in WPF

Not exactly direct answer, but strongly related:

In case the resources are in a different file - for example ResourceDictionary.xaml

You can simply add x:Class to it:

<ResourceDictionary x:Class="Namespace.NewClassName"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
    <ds:MyCollection x:Key="myKey" x:Name="myName" />
</ResourceDictionary>

And then use it in code behind:

var res = new Namespace.NewClassName();
var col = res["myKey"];

Bundler: Command not found

Make sure you do rbenv rehash when installing different rubies

What characters are forbidden in Windows and Linux directory names?

Let's keep it simple and answer the question, first.

  1. The forbidden printable ASCII characters are:

    • Linux/Unix:

      / (forward slash)
      
    • Windows:

      < (less than)
      > (greater than)
      : (colon - sometimes works, but is actually NTFS Alternate Data Streams)
      " (double quote)
      / (forward slash)
      \ (backslash)
      | (vertical bar or pipe)
      ? (question mark)
      * (asterisk)
      
  2. Non-printable characters

    If your data comes from a source that would permit non-printable characters then there is more to check for.

    • Linux/Unix:

      0 (NULL byte)
      
    • Windows:

      0-31 (ASCII control characters)
      

    Note: While it is legal under Linux/Unix file systems to create files with control characters in the filename, it might be a nightmare for the users to deal with such files.

  3. Reserved file names

    The following filenames are reserved:

    • Windows:

      CON, PRN, AUX, NUL 
      COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9
      LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9
      

      (both on their own and with arbitrary file extensions, e.g. LPT1.txt).

  4. Other rules

    • Windows:

      Filenames cannot end in a space or dot.

Android WebView style background-color:transparent ignored on android 2.2

You can user BindingAdapter like this:

Java

@BindingAdapter("setBackground")
public static void setBackground(WebView view,@ColorRes int resId) {
        view.setBackgroundColor(view.getContext().getResources().getColor(resId));
        view.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
}

XML:

<layout >

    <data>

        <import type="com.tdk.sekini.R" />


    </data>

       <WebView
            ...
            app:setBackground="@{R.color.grey_10_transparent}"/>

</layout>

Resources

<color name="grey_10_transparent">#11e6e6e6</color>

Wait some seconds without blocking UI execution

If possible, the preferred approach should be using an asynchronous way or a second thread.

If this isn't possible or wanted, using any implementation of DoEvents() is a bad idea, since it may cause problems Possible problems with DoEvents. This is mostly about DoEvents with Winforms but the possible pitfalls in WPF are the same.

Then putting a frame on the Dispatcher with the wanted sleep time can be used:

using System;
using System.Threading;
using System.Windows.Threading;

public static void NonBlockingSleep(int timeInMilliseconds)
{
    DispatcherFrame df = new DispatcherFrame();

    new Thread((ThreadStart)(() =>
    {
        Thread.Sleep(TimeSpan.FromMilliseconds(timeInMilliseconds));
        df.Continue = false;

    })).Start();

    Dispatcher.PushFrame(df);
}

how to parse JSON file with GSON

In case you need to parse it from a file, I find the best solution to use a HashMap<String, String> to use it inside your java code for better manipultion.

Try out this code:

public HashMap<String, String> myMethodName() throws FileNotFoundException
{
    String path = "absolute path to your file";
    BufferedReader bufferedReader = new BufferedReader(new FileReader(path));

    Gson gson = new Gson();
    HashMap<String, String> json = gson.fromJson(bufferedReader, HashMap.class);
    return json;
}

How do I test which class an object is in Objective-C?

if you want to get the name of the class simply call:-

id yourObject= [AnotherClass returningObject];

NSString *className=[yourObject className];

NSLog(@"Class name is : %@",className);

COPY with docker but with exclusion

Create file .dockerignore in your docker build context directory (so in this case, most likely a directory that is a parent to node_modules) with one line in it:

**/node_modules

although you probably just want:

node_modules

Info about dockerignore: https://docs.docker.com/engine/reference/builder/#dockerignore-file

How can I make Flexbox children 100% height of their parent?

An idea would be that display:flex; with flex-direction: row; is filling the container div with .flex-1 and .flex-2, but that does not mean that .flex-2 has a default height:100%;, even if it is extended to full height.

And to have a child element (.flex-2-child) with height:100%;, you'll need to set the parent to height:100%; or use display:flex; with flex-direction: row; on the .flex-2 div too.

From what I know, display:flex will not extend all your child elements height to 100%.

A small demo, removed the height from .flex-2-child and used display:flex; on .flex-2: http://jsfiddle.net/2ZDuE/3/

Best way to stress test a website

I have used WebLOAD for this kind of project. It's easy to create scripts, and it has built in support for monitoring ASP.NET stats

Not able to start Genymotion device

I think you should configure your VirtualBox network adapter:

The adapter's IP address has to be in the same network (192.168.56.0/24 by default) as DHCP server's IP address and DHCP's IP address bounds. If all those addresses are not in the same network, then your Genymotion virtual device might not be able to start.

https://cloud.genymotion.com/page/faq/#collapse-blank

Or check log files to get a clue:

For each platform, the log files are stored here:
Windows Vista/7/8: C:\Users\USER\AppData\Local\Genymobile
Windows XP: C:\Documents and Settings\USER\Local settings\Application Data\Genymobile
Linux: /home/USER/.Genymobile
Mac: /Users/USER/.Genymobile

https://cloud.genymotion.com/page/faq/#collapse-logs

Check whether a table contains rows or not sql server 2005

For what purpose?

  • Quickest for an IF would be IF EXISTS (SELECT * FROM Table)...
  • For a result set, SELECT TOP 1 1 FROM Table returns either zero or one rows
  • For exactly one row with a count (0 or non-zero), SELECT COUNT(*) FROM Table

Iterating through all nodes in XML file

This is what I quickly wrote for myself:

public static class XmlDocumentExtensions
{
    public static void IterateThroughAllNodes(
        this XmlDocument doc, 
        Action<XmlNode> elementVisitor)
    {
        if (doc != null && elementVisitor != null)
        {
            foreach (XmlNode node in doc.ChildNodes)
            {
                doIterateNode(node, elementVisitor);
            }
        }
    }

    private static void doIterateNode(
        XmlNode node, 
        Action<XmlNode> elementVisitor)
    {
        elementVisitor(node);

        foreach (XmlNode childNode in node.ChildNodes)
        {
            doIterateNode(childNode, elementVisitor);
        }
    }
}

To use it, I've used something like:

var doc = new XmlDocument();
doc.Load(somePath);

doc.IterateThroughAllNodes(
    delegate(XmlNode node)
    {
        // ...Do something with the node...
    });

Maybe it helps someone out there.

Python IndentationError: unexpected indent

Check if you mixed tabs and spaces, that is a frequent source of indentation errors.

Correct file permissions for WordPress

When you setup WP you (the webserver) may need write access to the files. So the access rights may need to be loose.

chown www-data:www-data  -R * # Let Apache be owner
find . -type d -exec chmod 755 {} \;  # Change directory permissions rwxr-xr-x
find . -type f -exec chmod 644 {} \;  # Change file permissions rw-r--r--

After the setup you should tighten the access rights, according to Hardening WordPress all files except for wp-content should be writable by your user account only. wp-content must be writable by www-data too.

chown <username>:<username>  -R * # Let your useraccount be owner
chown www-data:www-data wp-content # Let apache be owner of wp-content

Maybe you want to change the contents in wp-content later on. In this case you could

  • temporarily change to the user to www-data with su,
  • give wp-content group write access 775 and join the group www-data or
  • give your user the access rights to the folder using ACLs.

Whatever you do, make sure the files have rw permissions for www-data.

Date difference in minutes in Python

If you are trying to find the difference between timestamps that are in pandas columns, the the answer is fairly simple. If you need it in days or seconds then

# For difference in days:
df['diff_in_days']=(df['timestamp2'] - df['timestamp1']).dt.days
# For difference in seconds
df['diff_in_seconds']=(df['timestamp2'] - df['timestamp1']).dt.seconds

Now minute is tricky as dt.minute works only on datetime64[ns] dtype. whereas the column generated from subtracting two datetimes has format

AttributeError: 'TimedeltaProperties' object has no attribute 'm8'

So like mentioned by many above to get the actual value of the difference in minute you have to do:

df['diff_in_min']=df['diff_in_seconds']/60

But if just want the difference between the minute parts of the two timestamps then do the following

#convert the timedelta to datetime and then extract minute
df['diff_in_min']=(pd.to_datetime(df['timestamp2']-df['timestamp1'])).dt.minute

You can also read the article https://docs.python.org/3.4/library/datetime.html and see section 8.1.2 you'll see the read only attributes are only seconds,days and milliseconds. And this settles why the minute function doesn't work directly.

How to send email to multiple address using System.Net.Mail

My code to solve this problem:

private void sendMail()
{   
    //This list can be a parameter of metothd
    List<MailAddress> lst = new List<MailAddress>();

    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));


    try
    {


        MailMessage objeto_mail = new MailMessage();
        SmtpClient client = new SmtpClient();
        client.Port = 25;
        client.Host = "10.15.130.28"; //or SMTP name
        client.Timeout = 10000;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
        objeto_mail.From = new MailAddress("[email protected]");

        //add each email adress
        foreach (MailAddress m in lst)
        {
            objeto_mail.To.Add(m);
        }


        objeto_mail.Subject = "Sending mail test";
        objeto_mail.Body = "Functional test for automatic mail :-)";
        client.Send(objeto_mail);


    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

How to create a directory using Ansible

to create directory

ansible host_name -m file -a "dest=/home/ansible/vndir state=directory"

Get started with Latex on Linux

First you'll need to Install it:

  • If you're using a distro which packages LaTeX (almost all will do) then look for texlive or tetex. TeX Live is the newer of the two, and is replacing tetex on most distributions now.

If you're using Debian or Ubuntu, something like:

<code>apt-get install texlive</code>

..will get it installed.

RedHat or CentOS need:

<code>yum install tetex</code>

Note : This needs root permissions, so either use su to switch user to root, or prefix the commands with sudo, if you aren't already logged in as the root user.

Next you'll need to get a text editor. Any editor will do, so whatever you are comfortable with. You'll find that advanced editors like Emacs (and vim) add a lot of functionality and so will help with ensuring that your syntax is correct before you try and build your document output.

Create a file called test.tex and put some content in it, say the example from the LaTeX primer:

\documentclass[a4paper,12pt]{article}
\begin{document}

The foundations of the rigorous study of \emph{analysis}
were laid in the nineteenth century, notably by the
mathematicians Cauchy and Weierstrass. Central to the
study of this subject are the formal definitions of
\emph{limits} and \emph{continuity}.

Let $D$ be a subset of $\bf R$ and let
$f \colon D \to \mathbf{R}$ be a real-valued function on
$D$. The function $f$ is said to be \emph{continuous} on
$D$ if, for all $\epsilon > 0$ and for all $x \in D$,
there exists some $\delta > 0$ (which may depend on $x$)
such that if $y \in D$ satisfies
\[ |y - x| < \delta \]
then
\[ |f(y) - f(x)| < \epsilon. \]

One may readily verify that if $f$ and $g$ are continuous
functions on $D$ then the functions $f+g$, $f-g$ and
$f.g$ are continuous. If in addition $g$ is everywhere
non-zero then $f/g$ is continuous.

\end{document}

Once you've got this file you'll need to run latex on it to produce some output (as a .dvi file to start with, which is possible to convert to many other formats):

latex test.tex

This will print a bunch of output, something like this:

=> latex test.tex

This is pdfeTeX, Version 3.141592-1.21a-2.2 (Web2C 7.5.4)
entering extended mode
(./test.tex
LaTeX2e &lt;2003/12/01&gt;
Babel &lt;v3.8d&gt; and hyphenation patterns for american, french, german, ngerman, b
ahasa, basque, bulgarian, catalan, croatian, czech, danish, dutch, esperanto, e
stonian, finnish, greek, icelandic, irish, italian, latin, magyar, norsk, polis
h, portuges, romanian, russian, serbian, slovak, slovene, spanish, swedish, tur
kish, ukrainian, nohyphenation, loaded.
(/usr/share/texmf/tex/latex/base/article.cls
Document Class: article 2004/02/16 v1.4f Standard LaTeX document class
(/usr/share/texmf/tex/latex/base/size12.clo))
No file test.aux.
[1] (./test.aux) )
Output written on test.dvi (1 page, 1508 bytes).
Transcript written on test.log.

..don't worry about most of this output -- the important part is the Output written on test.dvi line, which says that it was successful.

Now you need to view the output file with xdvi:

xdvi test.dvi &

This will pop up a window with the beautifully formatted output in it. Hit `q' to quit this, or you can leave it open and it will automatically update when the test.dvi file is modified (so whenever you run latex to update the output).

To produce a PDF of this you simply run pdflatex instead of latex:

pdflatex test.tex

..and you'll have a test.pdf file created instead of the test.dvi file.

After this is all working fine, I would suggest going to the LaTeX primer page and running through the items on there as you need features for documents you want to write.

Future things to consider include:

  • Use tools such as xfig or dia to create diagrams. These can be easily inserted into your documents in a variety of formats. Note that if you are creating PDFs then you shouldn't use EPS (encapsulated postscript) for images -- use pdf exported from your diagram editor if possible, or you can use the epstopdf package to automatically convert from (e)ps to pdf for figures included with \includegraphics.

  • Start using version control on your documents. This seems excessive at first, but being able to go back and look at earlier versions when you are writing something large can be extremely useful.

  • Use make to run latex for you. When you start on having bibliographies, images and other more complex uses of latex you'll find that you need to run it over multiple files or multiple times (the first time updates the references, and the second puts references into the document, so they can be out-of-date unless you run latex twice...). Abstracting this into a makefile can save a lot of time and effort.

  • Use a better editor. Something like Emacs + AUCTeX is highly competent. This is of course a highly subjective subject, so I'll leave it at that (that and that Emacs is clearly the best option :)

How to disable "prevent this page from creating additional dialogs"?

You should better use jquery-confirm rather than trying to remove that checkbox.

$.confirm({
    title: 'Confirm!',
    content: 'Are you sure you want to refund invoice ?',
    confirm: function(){
       //do something 
    },
    cancel: function(){
       //do something
    }
}); 

What is the default scope of a method in Java?

Java 8 now allows implementation of methods inside an interface itself with default scope (and static only).

How do I loop through a list by twos?

You can use for in range with a step size of 2:

Python 2

for i in xrange(0,10,2):
  print(i)

Python 3

for i in range(0,10,2):
  print(i)

Note: Use xrange in Python 2 instead of range because it is more efficient as it generates an iterable object, and not the whole list.

Psql could not connect to server: No such file or directory, 5432 error?

WARNING: This will remove the database

Use command:

rm -rf /usr/local/var/postgres && initdb /usr/local/var/postgres -E utf8

How to remove the querystring and get only the url?

To remove the query string from the request URI, replace the query string with an empty string:

function request_uri_without_query() {
    $result = $_SERVER['REQUEST_URI'];
    $query = $_SERVER['QUERY_STRING'];
    if(!empty($query)) {
        $result = str_replace('?' . $query, '', $result);
    }
    return $result;
}

Capturing TAB key in text box

In Chrome on the Mac, alt-tab inserts a tab character into a <textarea> field.

Here’s one: . Wee!

find all unchecked checkbox in jquery

$("input[type='checkbox']:not(:checked):not('\#chkAll\')").map(function () { 
   var a = ""; 
   if (this.name != "chkAll") { 
      a = this.name + "|off"; 
   } 
   return a; 
}).get().join();

This will retrieve all unchecked checkboxes and exclude the "chkAll" checkbox that I use to check|uncheck all checkboxes. Since I want to know what value I'm passing to the database I set these to off, since the checkboxes give me a value of on.

//looking for unchecked checkboxes, but don’t include the checkbox all that checks or unchecks all checkboxes
//.map - Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

//.get - Retrieve the DOM elements matched by the jQuery object.
//.join - (javascript) joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).

Using :before and :after CSS selector to insert Html

content doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.

Another problem with your code is " inside a " block. You should mix ' and " (class='headingDetail').

If content did support HTML you could end up in an infinite loop where content is added inside content.

Difference between StringBuilder and StringBuffer

But needed to get the clear difference with the help of an example?

StringBuffer or StringBuilder

Simply use StringBuilder unless you really are trying to share a buffer between threads. StringBuilder is the unsynchronized (less overhead = more efficient) younger brother of the original synchronized StringBuffer class.

StringBuffer came first. Sun was concerned with correctness under all conditions, so they made it synchronized to make it thread-safe just in case.

StringBuilder came later. Most of the uses of StringBuffer were single-thread and unnecessarily paying the cost of the synchronization.

Since StringBuilder is a drop-in replacement for StringBuffer without the synchronization, there would not be differences between any examples.

If you are trying to share between threads, you can use StringBuffer, but consider whether higher-level synchronization is necessary, e.g. perhaps instead of using StringBuffer, should you synchronize the methods that use the StringBuilder.