Programs & Examples On #Force.com

A Platform-as-a-Service development environment created by Salesforce.com, which underlies the core Salesforce CRM functionality and is available as a platform via database.com, as well as via Heroku, a Ruby-on-Rails environment.

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

If you need to go a step further than @alon's detailed steps and also create a self signed ca:

https.createServer({
  key: fs.readFileSync(NODE_SSL_KEY),
  cert: fs.readFileSync(NODE_SSL_CERT),
  ca: fs.readFileSync(NODE_SSL_CA),
}, app).listen(PORT, () => {});

package.json

"setup:https": "openssl genrsa -out src/server/ssl/localhost.key 2048
&& openssl req -new -x509 -key src/server/ssl/localhost.key -out src/server/ssl/localhost.crt -config src/server/ssl/localhost.cnf
&& openssl req -new -out src/server/ssl/localhost.csr -config src/server/ssl/localhost.cnf
&& openssl x509 -req -in src/server/ssl/localhost.csr -CA src/server/ssl/localhost.crt -CAkey src/server/ssl/localhost.key -CAcreateserial -out src/server/ssl/ca.crt",

Using the localhost.cnf as described:

[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = UK
ST = State
L = Location
O = Organization Name
OU = Organizational Unit 
CN = www.localhost.com
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = www.localhost.com
DNS.2 = localhost.com
DNS.3 = localhost

Run batch file from Java code

Following is worked for me

File dir = new File("E:\\test");
        ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "Start","test.bat");
        pb.directory(dir);
        Process p = pb.start();

How to generate access token using refresh token through google drive API?

POST /oauth2/v4/token

Host: www.googleapis.com

Headers

Content-length: 163

content-type: application/x-www-form-urlencoded

RequestBody

client_secret=************&grant_type=refresh_token&refresh_token=sasasdsa1312dsfsdf&client_id=************

What's the best three-way merge tool?

Kdiff3 conflict resolution algorithm is really impressive.

Even when subversion indicates a conflict, Kdiff3 solves it automatically. There's versions for Windows and Linux with the same interface. It is possible to integrate it with Tortoise and with your linux shell.

It is in the list of my favorite open source software. One of the first tools I install in any machine.

You can configure it as the default diff tool in Subversion, Git, Mercurial, and ClearCase. It also solves almost all the ClearCase conflicts. In Windows, it has a nice integration with windows explorer: select two files and right click to compare them, or right click to 'save to later' a file, and then select another one to compare.

The merged file is editable. Has slick keyboard shortcuts.

You can also use it compare and merge directories. See: Kdiff3 Comparing directories

An advanced feature is to use regular expressions for defining automatic merges.

My only annoyance is that it is a little difficult to compile if it isn't present in your favorite distro repository.

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

socket connect() vs bind()

The one liner : bind() to own address, connect() to remote address.

Quoting from the man page of bind()

bind() assigns the address specified by addr to the socket referred to by the file descriptor sockfd. addrlen specifies the size, in bytes, of the address structure pointed to by addr. Traditionally, this operation is called "assigning a name to a socket".

and, from the same for connect()

The connect() system call connects the socket referred to by the file descriptor sockfd to the address specified by addr.

To clarify,

  • bind() associates the socket with its local address [that's why server side binds, so that clients can use that address to connect to server.]
  • connect() is used to connect to a remote [server] address, that's why is client side, connect [read as: connect to server] is used.

List all of the possible goals in Maven 2?

The goal you indicate in the command line is linked to the lifecycle of Maven. For example, the build lifecycle (you also have the clean and site lifecycles which are different) is composed of the following phases:

  • validate: validate the project is correct and all necessary information is available.
  • compile: compile the source code of the project.
  • test: test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed.
  • package: take the compiled code and package it in its distributable format, such as a JAR.
  • integration-test: process and deploy the package if necessary into an environment where integration tests can be run.
  • verify: run any checks to verify the package is valid and meets quality criteria
  • install: install the package into the local repository, for use as a dependency in other projects locally.
  • deploy: done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

You can find the list of "core" plugins here, but there are plenty of others plugins, such as the codehaus ones, here.

How Do I Make Glyphicons Bigger? (Change Size?)

Increase the font-size of glyphicon to increase all icons size.

.glyphicon {
    font-size: 50px;
}

To target only one icon,

.glyphicon.glyphicon-globe {
    font-size: 75px;
}

disable horizontal scroll on mobile web

I've found this answer over here on stackoverflow which works perfectly for me:

use this in style

body {
    overflow-x: hidden;
    width: 100%;
}

Use this in head tag

<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes" />

A slight addition of mine in case your body has padding (to prevent the device from scaling to the body content-box, and thus still adding a horizontal scrollbar):

body {
    overflow-x: hidden;
    width: 100%;
    -webkit-box-sizing: border-box;
       -moz-box-sizing: border-box;
            box-sizing: border-box;
}

Maximum execution time in phpMyadmin

ini_set('max_execution_time', 0); or create file name called php.ini and enter the first line max_execution_time=0 then save it and put the file in your root folder of your application.

That's it. Good luck.

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

You are right that this has long since been implemented in .NET Core.

At the time of writing (September 2019), the project.json file of NuGet 3.x+ has been superseded by PackageReference (as explained at https://docs.microsoft.com/en-us/nuget/archive/project-json).

To get access to the *Async methods of the HttpClient class, your .csproj file must be correctly configured.

Open your .csproj file in a plain text editor, and make sure the first line is
<Project Sdk="Microsoft.NET.Sdk.Web">
(as pointed out at https://docs.microsoft.com/en-us/dotnet/core/tools/project-json-to-csproj#the-csproj-format).

To get access to the *Async methods of the HttpClient class, you also need to have the correct package reference in your .csproj file, like so:

<ItemGroup>
    <!-- ... -->
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <!-- ... -->
</ItemGroup>

(See https://docs.microsoft.com/en-us/nuget/consume-packages/package-references-in-project-files#adding-a-packagereference. Also: We recommend applications targeting ASP.NET Core 2.1 and later use the Microsoft.AspNetCore.App metapackage, https://docs.microsoft.com/en-us/aspnet/core/fundamentals/metapackage)

Methods such as PostAsJsonAsync, ReadAsAsync, PutAsJsonAsync and DeleteAsync should now work out of the box. (No using directive needed.)

Update: The PackageReference tag is no longer needed in .NET Core 3.0.

ASP.NET MVC View Engine Comparison

ASP.NET MVC View Engines (Community Wiki)

Since a comprehensive list does not appear to exist, let's start one here on SO. This can be of great value to the ASP.NET MVC community if people add their experience (esp. anyone who contributed to one of these). Anything implementing IViewEngine (e.g. VirtualPathProviderViewEngine) is fair game here. Just alphabetize new View Engines (leaving WebFormViewEngine and Razor at the top), and try to be objective in comparisons.


System.Web.Mvc.WebFormViewEngine

Design Goals:

A view engine that is used to render a Web Forms page to the response.

Pros:

  • ubiquitous since it ships with ASP.NET MVC
  • familiar experience for ASP.NET developers
  • IntelliSense
  • can choose any language with a CodeDom provider (e.g. C#, VB.NET, F#, Boo, Nemerle)
  • on-demand compilation or precompiled views

Cons:

  • usage is confused by existence of "classic ASP.NET" patterns which no longer apply in MVC (e.g. ViewState PostBack)
  • can contribute to anti-pattern of "tag soup"
  • code-block syntax and strong-typing can get in the way
  • IntelliSense enforces style not always appropriate for inline code blocks
  • can be noisy when designing simple templates

Example:

<%@ Control Inherits="System.Web.Mvc.ViewPage<IEnumerable<Product>>" %>
<% if(model.Any()) { %>
<ul>
    <% foreach(var p in model){%>
    <li><%=p.Name%></li>
    <%}%>
</ul>
<%}else{%>
    <p>No products available</p>
<%}%>

System.Web.Razor

Design Goals:

Pros:

  • Compact, Expressive, and Fluid
  • Easy to Learn
  • Is not a new language
  • Has great Intellisense
  • Unit Testable
  • Ubiquitous, ships with ASP.NET MVC

Cons:

  • Creates a slightly different problem from "tag soup" referenced above. Where the server tags actually provide structure around server and non-server code, Razor confuses HTML and server code, making pure HTML or JS development challenging (see Con Example #1) as you end up having to "escape" HTML and / or JavaScript tags under certain very common conditions.
  • Poor encapsulation+reuseability: It's impractical to call a razor template as if it were a normal method - in practice razor can call code but not vice versa, which can encourage mixing of code and presentation.
  • Syntax is very html-oriented; generating non-html content can be tricky. Despite this, razor's data model is essentially just string-concatenation, so syntax and nesting errors are neither statically nor dynamically detected, though VS.NET design-time help mitigates this somewhat. Maintainability and refactorability can suffer due to this.
  • No documented API, http://msdn.microsoft.com/en-us/library/system.web.razor.aspx

Con Example #1 (notice the placement of "string[]..."):

@{
    <h3>Team Members</h3> string[] teamMembers = {"Matt", "Joanne", "Robert"};
    foreach (var person in teamMembers)
    {
        <p>@person</p>
    }
}

Bellevue

Design goals:

  • Respect HTML as first-class language as opposed to treating it as "just text".
  • Don't mess with my HTML! The data binding code (Bellevue code) should be separate from HTML.
  • Enforce strict Model-View separation

Brail

Design Goals:

The Brail view engine has been ported from MonoRail to work with the Microsoft ASP.NET MVC Framework. For an introduction to Brail, see the documentation on the Castle project website.

Pros:

  • modeled after "wrist-friendly python syntax"
  • On-demand compiled views (but no precompilation available)

Cons:

  • designed to be written in the language Boo

Example:

<html>    
<head>        
<title>${title}</title>
</head>    
<body>        
     <p>The following items are in the list:</p>  
     <ul><%for element in list:    output "<li>${element}</li>"%></ul>
     <p>I hope that you would like Brail</p>    
</body>
</html>

Hasic

Hasic uses VB.NET's XML literals instead of strings like most other view engines.

Pros:

  • Compile-time checking of valid XML
  • Syntax colouring
  • Full intellisense
  • Compiled views
  • Extensibility using regular CLR classes, functions, etc
  • Seamless composability and manipulation since it's regular VB.NET code
  • Unit testable

Cons:

  • Performance: Builds the whole DOM before sending it to client.

Example:

Protected Overrides Function Body() As XElement
    Return _
    <body>
        <h1>Hello, World</h1>
    </body>
End Function

NDjango

Design Goals:

NDjango is an implementation of the Django Template Language on the .NET platform, using the F# language.

Pros:


NHaml

Design Goals:

.NET port of Rails Haml view engine. From the Haml website:

Haml is a markup language that's used to cleanly and simply describe the XHTML of any web document, without the use of inline code... Haml avoids the need for explicitly coding XHTML into the template, because it is actually an abstract description of the XHTML, with some code to generate dynamic content.

Pros:

  • terse structure (i.e. D.R.Y.)
  • well indented
  • clear structure
  • C# Intellisense (for VS2008 without ReSharper)

Cons:

  • an abstraction from XHTML rather than leveraging familiarity of the markup
  • No Intellisense for VS2010

Example:

@type=IEnumerable<Product>
- if(model.Any())
  %ul
    - foreach (var p in model)
      %li= p.Name
- else
  %p No products available

NVelocityViewEngine (MvcContrib)

Design Goals:

A view engine based upon NVelocity which is a .NET port of the popular Java project Velocity.

Pros:

  • easy to read/write
  • concise view code

Cons:

  • limited number of helper methods available on the view
  • does not automatically have Visual Studio integration (IntelliSense, compile-time checking of views, or refactoring)

Example:

#foreach ($p in $viewdata.Model)
#beforeall
    <ul>
#each
    <li>$p.Name</li>
#afterall
    </ul>
#nodata 
    <p>No products available</p>
#end

SharpTiles

Design Goals:

SharpTiles is a partial port of JSTL combined with concept behind the Tiles framework (as of Mile stone 1).

Pros:

  • familiar to Java developers
  • XML-style code blocks

Cons:

  • ...

Example:

<c:if test="${not fn:empty(Page.Tiles)}">
  <p class="note">
    <fmt:message key="page.tilesSupport"/>
  </p>
</c:if>

Spark View Engine

Design Goals:

The idea is to allow the html to dominate the flow and the code to fit seamlessly.

Pros:

  • Produces more readable templates
  • C# Intellisense (for VS2008 without ReSharper)
  • SparkSense plug-in for VS2010 (works with ReSharper)
  • Provides a powerful Bindings feature to get rid of all code in your views and allows you to easily invent your own HTML tags

Cons:

  • No clear separation of template logic from literal markup (this can be mitigated by namespace prefixes)

Example:

<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
    <li each="var p in products">${p.Name}</li>
</ul>
<else>
    <p>No products available</p>
</else>

<Form style="background-color:olive;">
    <Label For="username" />
    <TextBox For="username" />
    <ValidationMessage For="username" Message="Please type a valid username." />
</Form>

StringTemplate View Engine MVC

Design Goals:

  • Lightweight. No page classes are created.
  • Fast. Templates are written to the Response Output stream.
  • Cached. Templates are cached, but utilize a FileSystemWatcher to detect file changes.
  • Dynamic. Templates can be generated on the fly in code.
  • Flexible. Templates can be nested to any level.
  • In line with MVC principles. Promotes separation of UI and Business Logic. All data is created ahead of time, and passed down to the template.

Pros:

  • familiar to StringTemplate Java developers

Cons:

  • simplistic template syntax can interfere with intended output (e.g. jQuery conflict)

Wing Beats

Wing Beats is an internal DSL for creating XHTML. It is based on F# and includes an ASP.NET MVC view engine, but can also be used solely for its capability of creating XHTML.

Pros:

  • Compile-time checking of valid XML
  • Syntax colouring
  • Full intellisense
  • Compiled views
  • Extensibility using regular CLR classes, functions, etc
  • Seamless composability and manipulation since it's regular F# code
  • Unit testable

Cons:

  • You don't really write HTML but code that represents HTML in a DSL.

XsltViewEngine (MvcContrib)

Design Goals:

Builds views from familiar XSLT

Pros:

  • widely ubiquitous
  • familiar template language for XML developers
  • XML-based
  • time-tested
  • Syntax and element nesting errors can be statically detected.

Cons:

  • functional language style makes flow control difficult
  • XSLT 2.0 is (probably?) not supported. (XSLT 1.0 is much less practical).

How to save and extract session data in codeigniter

You can set data to session simply like this in Codeigniter:

$this->load->library('session');
$this->session->set_userdata(array(
    'user_id'  => $user->uid,
    'username' => $user->username,
    'groupid'  => $user->groupid,
    'date'     => $user->date_cr,
    'serial'   => $user->serial,
    'rec_id'   => $user->rec_id,
    'status'   => TRUE
));

and you can get it like this:

$u_rec_id = $this->session->userdata('rec_id');
$serial = $this->session->userdata('serial');

Intellisense and code suggestion not working in Visual Studio 2012 Ultimate RC

Look at this post here.

This worked for me:

Delete the files in this folder. vs2010:

 %AppData%\Microsoft\VisualStudio\10.0\ReflectedSchemas

vs2012;

%AppData%\Microsoft\VisualStudio\11.0\ReflectedSchemas

VS Ultimate 2013;

%AppData%\Microsoft\VisualStudio\12.0\ReflectedSchemas

VS Professional 2015;

%AppData%\Microsoft\VisualStudio\14.0\ReflectedSchemas

cell format round and display 2 decimal places

Input: 0 0.1 1000

=FIXED(E5,2)

Output: 0.00 0.10 1,000.00

=TEXT(E5,"0.00")

Output: 0.00 0.10 1000.00

Note: As you can see FIXED add a coma after a thousand, where TEXT does not.

Linker error: "linker input file unused because linking not done", undefined reference to a function in that file

I think you are confused about how the compiler puts things together. When you use -c flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o files thus don't mix with -c, and compiler warns you about that. Symbols from object file are not moved to other object files like that.

All object files should be on the final linker invocation, which is not the case here, so linker (called via g++ front-end) complains about missing symbols.

Here's a small example (calling g++ explicitly for clarity):

PROG ?= myprog
OBJS = worker.o main.o

all: $(PROG)

.cpp.o:
        g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<

$(PROG): $(OBJS)
        g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)

There's also makedepend utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M gcc option for building make rules.

How to overcome the CORS issue in ReactJS

The ideal way would be to add CORS support to your server.

You could also try using a separate jsonp module. As far as I know axios does not support jsonp. So I am not sure if the method you are using would qualify as a valid jsonp request.

There is another hackish work around for the CORS problem. You will have to deploy your code with an nginx server serving as a proxy for both your server and your client. The thing that will do the trick us the proxy_pass directive. Configure your nginx server in such a way that the location block handling your particular request will proxy_pass or redirect your request to your actual server. CORS problems usually occur because of change in the website domain. When you have a singly proxy serving as the face of you client and you server, the browser is fooled into thinking that the server and client reside in the same domain. Ergo no CORS.

Consider this example.

Your server is my-server.com and your client is my-client.com Configure nginx as follows:

// nginx.conf

upstream server {
    server my-server.com;
}

upstream client {
    server my-client.com;
}

server {
    listen 80;

    server_name my-website.com;
    access_log /path/to/access/log/access.log;
    error_log /path/to/error/log/error.log;

    location / {
        proxy_pass http://client;
    }

    location ~ /server/(?<section>.*) {
        rewrite ^/server/(.*)$ /$1 break;
        proxy_pass http://server;
    }
}

Here my-website.com will be the resultant name of the website where the code will be accessible (name of the proxy website). Once nginx is configured this way. You will need to modify the requests such that:

  • All API calls change from my-server.com/<API-path> to my-website.com/server/<API-path>

In case you are not familiar with nginx I would advise you to go through the documentation.

To explain what is happening in the configuration above in brief:

  • The upstreams define the actual servers to whom the requests will be redirected
  • The server block is used to define the actual behaviour of the nginx server.
  • In case there are multiple server blocks the server_name is used to identify the block which will be used to handle the current request.
  • The error_log and access_log directives are used to define the locations of the log files (used for debugging)
  • The location blocks define the handling of different types of requests:
    1. The first location block handles all requests starting with / all these requests are redirected to the client
    2. The second location block handles all requests starting with /server/<API-path>. We will be redirecting all such requests to the server.

Note: /server here is being used to distinguish the client side requests from the server side requests. Since the domain is the same there is no other way of distinguishing requests. Keep in mind there is no such convention that compels you to add /server in all such use cases. It can be changed to any other string eg. /my-server/<API-path>, /abc/<API-path>, etc.

Even though this technique should do the trick, I would highly advise you to add CORS support to the server as this is the ideal way situations like these should be handled.

If you wish to avoid doing all this while developing you could for this chrome extension. It should allow you to perform cross domain requests during development.

How does #include <bits/stdc++.h> work in C++?

Unfortunately that approach is not portable C++ (so far).

All standard names are in namespace std and moreover you cannot know which names are NOT defined by including and header (in other words it's perfectly legal for an implementation to declare the name std::string directly or indirectly when using #include <vector>).

Despite this however you are required by the language to know and tell the compiler which standard header includes which part of the standard library. This is a source of portability bugs because if you forget for example #include <map> but use std::map it's possible that the program compiles anyway silently and without warnings on a specific version of a specific compiler, and you may get errors only later when porting to another compiler or version.

In my opinion there are no valid technical excuses because this is necessary for the general user: the compiler binary could have all standard namespace built in and this could actually increase the performance even more than precompiled headers (e.g. using perfect hashing for lookups, removing standard headers parsing or loading/demarshalling and so on).

The use of standard headers simplifies the life of who builds compilers or standard libraries and that's all. It's not something to help users.

However this is the way the language is defined and you need to know which header defines which names so plan for some extra neurons to be burnt in pointless configurations to remember that (or try to find and IDE that automatically adds the standard headers you use and removes the ones you don't... a reasonable alternative).

How to disable text selection using jQuery?

This is actually very simple. To disable text selection (and also click+drag-ing text (e.g a link in Chrome)), just use the following jQuery code:

$('body, html').mousedown(function(event) {
    event.preventDefault();
});

All this does is prevent the default from happening when you click with your mouse (mousedown()) in the body and html tags. You can very easily change the element just by changing the text in-between the two quotes (e.g change $('body, html') to $('#myUnselectableDiv') to make the myUnselectableDiv div to be, well, unselectable.

A quick snippet to show/prove this to you:

_x000D_
_x000D_
$('#no-select').mousedown(function(event) {_x000D_
  event.preventDefault();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<span id="no-select">I bet you can't select this text, or drag <a href="#">this link</a>, </span>_x000D_
<br/><span>but that you can select this text, and drag <a href="#">this link</a>!</span>
_x000D_
_x000D_
_x000D_

Please note that this effect is not perfect, and performs the best while making the whole window not selectable. You might also want to add

the cancellation of some of the hot keys (such as Ctrl+a and Ctrl+c. Test: Cmd+a and Cmd+c)

as well, by using that section of Vladimir's answer above. (get to his post here)

Remove all subviews?

view.subviews.forEach { $0.removeFromSuperview() }

Android layout replacing a view with another view on run time

private void replaceView(View oldV,View newV){
        ViewGroup par = (ViewGroup)oldV.getParent();
        if(par == null){return;}
        int i1 = par.indexOfChild(oldV);
        par.removeViewAt(i1);
        par.addView(newV,i1);
    }

What is the difference between 'protected' and 'protected internal'?

Protected Member

Protected Member of a class in only available in the contained class (in which it has been declared) and in the derived class within the assembly and also outside the assembly.

Means if a class that resides outside the assembly can use the protected member of the other assembly by inherited that class only.

We can exposed the Protected member outside the assembly by inherited that class and use it in the derived class only.

Note: Protected members are not accessible using the object in the derived class.

Internal Member

Internal Member of a class is available or access within the assembly either creating object or in a derived class or you can say it is accessible across all the classes within the assembly.

Note: Internal members not accessible outside the assembly either using object creating or in a derived class.

Protected Internal

Protected Internal access modifier is combination Protected or Internal.

Protected Internal Member can be available within the entire assembly in which it declared either creating object or by inherited that class. And can be accessible outside the assembly in a derived class only.

Note: Protected Internal member works as Internal within the same assembly and works as Protected for outside the assembly.

Why is &#65279; appearing in my HTML?

yeah, its so simple to fix that, just open that file by notepad++ and step follow --> Encoding\ encoding UTF-8 without BOM. then save that. It work for me as well!

Merge (Concat) Multiple JSONObjects in Java

I used string to concatenate new object to an existing object.


private static void concatJSON() throws IOException, InterruptedException {

    JSONParser parser = new JSONParser();
    Object obj = parser.parse(new FileReader(new File(Main.class.getResource("/file/user.json").toURI())));


    JSONObject jsonObj = (JSONObject) obj; //usernameJsonObj

    String [] values = {"0.9" , Date.from(Calendar.getInstance().toInstant()).toLocaleString()},
            innermost = {"Accomplished", "LatestDate"}, 
            inner = {"Lesson1", "Lesson2", "Lesson3", "Lesson4"};
    String in = "Jayvee Villa";

    JSONObject jo1 = new JSONObject();
    for (int i = 0; i < innermost.length; i++)
        jo1.put(innermost[i], values[i]);

    JSONObject jo2 = new JSONObject();
    for (int i = 0; i < inner.length; i++)
        jo2.put(inner[i], jo1);

    JSONObject jo3 = new JSONObject();
    jo3.put(in, jo2);

    String merger = jsonObj.toString().substring(0, jsonObj.toString().length()-1) + "," +jo3.toString().substring(1);

    System.out.println(merger);
    FileWriter pr = new FileWriter(file);
    pr.write(merger);
    pr.flush();
    pr.close();
}

How to create a TextArea in Android

Its really simple, write this code in XML:

<EditText
    android:id="@+id/fname"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="First Name"
/>

How to get all table names from a database?

In your example problem is passed table name pattern in getTables function of DatabaseMetaData.

Some database supports Uppercase identifier, some support lower case identifiers. For example oracle fetches the table name in upper case, while postgreSQL fetch it in lower case.

DatabaseMetaDeta provides a method to determine how the database stores identifiers, can be mixed case, uppercase, lowercase see:http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html#storesMixedCaseIdentifiers()

From below example, you can get all tables and view of providing table name pattern, if you want only tables then remove "VIEW" from TYPES array.

public class DBUtility {
    private static final String[] TYPES = {"TABLE", "VIEW"};
    public static void getTableMetadata(Connection jdbcConnection, String tableNamePattern, String schema, String catalog, boolean isQuoted) throws HibernateException {
            try {
                DatabaseMetaData meta = jdbcConnection.getMetaData();
                ResultSet rs = null;
                try {
                    if ( (isQuoted && meta.storesMixedCaseQuotedIdentifiers())) {
                        rs = meta.getTables(catalog, schema, tableNamePattern, TYPES);
                    } else if ( (isQuoted && meta.storesUpperCaseQuotedIdentifiers())
                        || (!isQuoted && meta.storesUpperCaseIdentifiers() )) {
                        rs = meta.getTables(
                                StringHelper.toUpperCase(catalog),
                                StringHelper.toUpperCase(schema),
                                StringHelper.toUpperCase(tableNamePattern),
                                TYPES
                            );
                    }
                    else if ( (isQuoted && meta.storesLowerCaseQuotedIdentifiers())
                            || (!isQuoted && meta.storesLowerCaseIdentifiers() )) {
                        rs = meta.getTables( 
                                StringHelper.toLowerCase( catalog ),
                                StringHelper.toLowerCase(schema), 
                                StringHelper.toLowerCase(tableNamePattern), 
                                TYPES 
                            );
                    }
                    else {
                        rs = meta.getTables(catalog, schema, tableNamePattern, TYPES);
                    }

                    while ( rs.next() ) {
                        String tableName = rs.getString("TABLE_NAME");
                        System.out.println("table = " + tableName);
                    }



                }
                finally {
                    if (rs!=null) rs.close();
                }
            }
            catch (SQLException sqlException) {
                // TODO 
                sqlException.printStackTrace();
            }

    }

    public static void main(String[] args) {
        Connection jdbcConnection;
        try {
            jdbcConnection = DriverManager.getConnection("", "", "");
            getTableMetadata(jdbcConnection, "tbl%", null, null, false);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

C#: Looping through lines of multiline string

I know this has been answered, but I'd like to add my own answer:

using (var reader = new StringReader(multiLineString))
{
    for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
    {
        // Do something with the line
    }
}

Breaking/exit nested for in vb.net

For i As Integer = 0 To 100
    bool = False
    For j As Integer = 0 To 100
        If check condition Then
            'if condition match
            bool = True
            Exit For 'Continue For
        End If
    Next
    If bool = True Then Continue For
Next

How does one make random number between range for arc4random_uniform()?

Probably one find useful this a bit updated version of Range extension from Ted van Gaalen's answer using Swift 4/Xcode 9+:

extension CountableClosedRange where Bound == Int {
    var randomFromRange: Bound {
        get {
            var offset = 0
            if lowerBound < 0 {
                offset = abs(lowerBound)
            }
            let mini = UInt32(lowerBound + offset)
            let maxi = UInt32(upperBound + offset)
            return Int(mini + arc4random_uniform(maxi - mini)) - offset
        }
    }
}

let n = (-1000 ... 1000).randomFromRange
print(n)

Or this a bit "hacky" solution to support open and closed intervals:

extension CountableRange where Bound == Int {
    var randomFromRange: Bound {
        return uniformRandom(from: lowerBound, to: upperBound)
    }
}

extension CountableClosedRange where Bound == Int {
    var randomFromRange: Bound {
        return uniformRandom(from: lowerBound, to: upperBound - 1)
    }
}

func uniformRandom(from: Int, to: Int) -> Int {
    var offset = 0
    if from < 0 {
        offset = abs(from)
    }
    let mini = UInt32(from + offset)
    let maxi = UInt32(to + offset)
    return Int(mini + arc4random_uniform(maxi - mini)) - offset
}

Not sure if there is a way to add property to both types of intervals simultaneously.

How to link an image and target a new window

If you use script to navigate to the page, use the open method with the target _blank to open a new window / tab:

<img src="..." alt="..." onclick="window.open('anotherpage.html', '_blank');" />

However, if you want search engines to find the page, you should just wrap the image in a regular link instead.

How to select data from 30 days?

You should be using DATEADD is Sql server so if try this simple select you will see the affect

Select DATEADD(Month, -1, getdate())

Result

2013-04-20 14:08:07.177

in your case try this query

SELECT name
FROM (
SELECT name FROM 
Hist_answer
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
UNION ALL
SELECT name FROM 
Hist_internet
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
) x
GROUP BY name ORDER BY name

What is the difference between precision and scale?

Precision is the number of significant digits. Oracle guarantees the portability of numbers with precision ranging from 1 to 38.

Scale is the number of digits to the right (positive) or left (negative) of the decimal point. The scale can range from -84 to 127.

In your case, ID with precision 6 means it won't accept a number with 7 or more significant digits.

Reference:

http://download.oracle.com/docs/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT1832

That page also has some examples that will make you understand precision and scale.

Do you (really) write exception safe code?

Writing exception-safe code in C++ is not so much about using lots of try { } catch { } blocks. It's about documenting what kind of guarantees your code provides.

I recommend reading Herb Sutter's Guru Of The Week series, in particular installments 59, 60 and 61.

To summarize, there are three levels of exception safety you can provide:

  • Basic: When your code throws an exception, your code does not leak resources, and objects remain destructible.
  • Strong: When your code throws an exception, it leaves the state of the application unchanged.
  • No throw: Your code never throws exceptions.

Personally, I discovered these articles quite late, so much of my C++ code is definitely not exception-safe.

Trigger event on body load complete js/jquery

When the page loads totally (dom, images, ...)

$(window).load(function(){
    // full load
});

When DOM elements load (not necessary all images will be loaded)

$(function(){
    // DOM Ready
});

Then you can trigger any event

$("element").trigger("event");

Making a WinForms TextBox behave like your browser's address bar

The below seems to work. The enter event handles the tabbing to the control and the MouseDown works when the control is clicked.

    private ########### void textBox1_Enter(object sender, EventArgs e)
    {
        textBox1.SelectAll();
    }

    private void textBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (textBox1.Focused)
            textBox1.SelectAll();
    }

CSS – why doesn’t percentage height work?

You need to give it a container with a height. width uses the viewport as the default width

How to access the content of an iframe with jQuery?

If iframe's source is an external domain, browsers will hide the iframe contents (Same Origin Policy). A workaround is saving the external contents in a file, for example (in PHP):

<?php
    $contents = file_get_contents($external_url);
    $res = file_put_contents($filename, $contents);
?>

then, get the new file content (string) and parse it to html, for example (in jquery):

$.get(file_url, function(string){
    var html = $.parseHTML(string);
    var contents = $(html).contents();
},'html');

notifyDataSetChange not working from custom adapter

I have the same problem, and i realize that. When we create adapter and set it to listview, listview will point to object somewhere in memory which adapter hold, data in this object will show in listview.

adapter = new CustomAdapter(data);
listview.setadapter(adapter);

if we create an object for adapter with another data again and notifydatasetchanged():

adapter = new CustomAdapter(anotherdata);
adapter.notifyDataSetChanged();

this will do not affect to data in listview because the list is pointing to different object, this object does not know anything about new object in adapter, and notifyDataSetChanged() affect nothing. So we should change data in object and avoid to create a new object again for adapter

substring of an entire column in pandas dataframe

Use the str accessor with square brackets:

df['col'] = df['col'].str[:9]

Or str.slice:

df['col'] = df['col'].str.slice(0, 9)

Is it possible to decompile an Android .apk file?

First, an apk file is just a modified jar file. So the real question is can they decompile the dex files inside. The answer is sort of. There are already disassemblers, such as dedexer and smali. You can expect these to only get better, and theoretically it should eventually be possible to decompile to actual Java source (at least sometimes). See the previous question decompiling DEX into Java sourcecode.

What you should remember is obfuscation never works. Choose a good license and do your best to enforce it through the law. Don't waste time with unreliable technical measures.

How to convert a Drawable to a Bitmap?

Use this code.it will help you for achieving your goal.

 Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.profileimage);
    if (bmp!=null) {
        Bitmap bitmap_round=getRoundedShape(bmp);
        if (bitmap_round!=null) {
            profileimage.setImageBitmap(bitmap_round);
        }
    }

  public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
    int targetWidth = 100;
    int targetHeight = 100;
    Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, 
            targetHeight,Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(targetBitmap);
    Path path = new Path();
    path.addCircle(((float) targetWidth - 1) / 2,
            ((float) targetHeight - 1) / 2,
            (Math.min(((float) targetWidth), 
                    ((float) targetHeight)) / 2),
                    Path.Direction.CCW);

    canvas.clipPath(path);
    Bitmap sourceBitmap = scaleBitmapImage;
    canvas.drawBitmap(sourceBitmap, 
            new Rect(0, 0, sourceBitmap.getWidth(),
                    sourceBitmap.getHeight()), 
                    new Rect(0, 0, targetWidth, targetHeight), new Paint(Paint.FILTER_BITMAP_FLAG));
    return targetBitmap;
}

Write values in app.config file

On Framework 4.5 the AppSettings.Settings["key"] part of ConfigurationManager is read only so I had to first Remove the key then Add it again using the following:

Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);

config.AppSettings.Settings.Remove("MySetting");
config.AppSettings.Settings.Add("MySetting", "some value");

config.Save(ConfigurationSaveMode.Modified);

Don't worry, you won't get an exception if you try to Remove a key that doesn't exist.

This post gives some good advice

How do I get an animated gif to work in WPF?

I am not sure if this has been solved but the best way is to use the WpfAnimatedGid library. It is very easy, simple and straight forward to use. It only requires 2lines of XAML code and about 5 lines of C# Code in the code behind.

You will see all the necessary details of how this can be used there. This is what I also used instead of re-inventing the wheel

Php header location redirect not working

Pekka answered my question in the comments. He didn't post an answer, so I am now. Use the exit() method after the header redirect. For some reason the rest of the code of the page continues to execute after the header() method redirect. When the rest of the code executes, the echo statement is outputted to the page. And you can't redirect using the header function after you output to the page. To avoid rest of the code from executing, use exit(). Thanks Pekka.

UPDATE: When using the web browser Internet Explorer, I have noticed that $_POST['cancel'] is not reliable. I am not exactly sure why this is, but I suspect IE posts additional variables on a form submit, specifically the variable 'cancel' is posted. I solved this by using a variable name other than 'cancel'. The combination of using exit() and a unique variable name is working for me.

Javascript to sort contents of select element

This will do the trick. Just pass it your select element a la: document.getElementById('lstALL') when you need your list sorted.

function sortSelect(selElem) {
    var tmpAry = new Array();
    for (var i=0;i<selElem.options.length;i++) {
        tmpAry[i] = new Array();
        tmpAry[i][0] = selElem.options[i].text;
        tmpAry[i][1] = selElem.options[i].value;
    }
    tmpAry.sort();
    while (selElem.options.length > 0) {
        selElem.options[0] = null;
    }
    for (var i=0;i<tmpAry.length;i++) {
        var op = new Option(tmpAry[i][0], tmpAry[i][1]);
        selElem.options[i] = op;
    }
    return;
}

How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

I know It's been a while since this question was asked but I just run into the same issue of inconsistency with onMouseLeave() What I did is to use onMouseOut() for the drop-list and on mouse leave for the whole menu, it is reliable and works every time I've tested it. I saw the events here in the docs: https://facebook.github.io/react/docs/events.html#mouse-events here is an example using https://www.w3schools.com/bootstrap/bootstrap_dropdowns.asp:

handleHoverOff(event){
  //do what ever, for example I use it to collapse the dropdown
  let collapsing = true;
  this.setState({dropDownCollapsed : collapsing });
}

render{
  return(
    <div class="dropdown" onMouseLeave={this.handleHoverOff.bind(this)}>
      <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
      <span class="caret"></span></button>
      <ul class="dropdown-menu" onMouseOut={this.handleHoverOff.bind(this)}>
        <li><a href="#">bla bla 1</a></li>
        <li><a href="#">bla bla 2</a></li>
        <li><a href="#">bla bla 3</a></li>
      </ul>
    </div>
  )
}

How do I set up a private Git repository on GitHub? Is it even possible?

GitHub is a great tool in-all for making repositories. However, it does not do good with private repositories.

You're forced to pay for private repositories unless you get some sort of plan. I have a couple of projects so far, and if GitHub doesn't do what I want I just go to Bitbucket. It's a bit harder to work with than GitHub, however it's unlimited free repositories.

Count the cells with same color in google spreadsheet

here is a working version :

function countbackgrounds() {
 var book = SpreadsheetApp.getActiveSpreadsheet();
 var range_input = book.getRange("B3:B4");
 var range_output = book.getRange("B6");
 var cell_colors = range_input.getBackgroundColors();
 var color = "#58FA58";
 var count = 0;

 for( var i in cell_colors ){
 Logger.log(cell_colors[i][0])
  if( cell_colors[i][0] == color ){ ++count }
  }
range_output.setValue(count);
 }  

How do I declare a global variable in VBA?

To use global variables, Insert New Module from VBA Project UI and declare variables using Global

Global iRaw As Integer
Global iColumn As Integer

Test method is inconclusive: Test wasn't run. Error?

In my case my test method was private I changed it to public and it worked.

How to remove a class from elements in pure JavaScript?

elements is an array of DOM objects. You should do something like this

for (var i = 0; i < elements.length; i++) {
   elements[i].classList.remove('hover');
}

ie: enumerate the elements collection, and for each element inside the collection call the remove method

iPhone SDK:How do you play video inside a view? Rather than fullscreen

The best way is to use layers insted of views:

AVPlayer *player = [AVPlayer playerWithURL:[NSURL url...]]; // 

AVPlayerLayer *layer = [AVPlayerLayer layer];

[layer setPlayer:player];
[layer setFrame:CGRectMake(10, 10, 300, 200)];
[layer setBackgroundColor:[UIColor redColor].CGColor];
[layer setVideoGravity:AVLayerVideoGravityResizeAspectFill];

[self.view.layer addSublayer:layer];

[player play];

Don't forget to add frameworks:

#import <QuartzCore/QuartzCore.h>
#import "AVFoundation/AVFoundation.h"

Reading InputStream as UTF-8

Solved my own problem. This line:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

needs to be:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));

or since Java 7:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));

SQL How to Select the most recent date item

Select * 
FROM test_table 
WHERE user_id = value 
AND date_added = (select max(date_added) 
   from test_table 
   where user_id = value)

How do I concatenate multiple C++ strings on one line?

auto s = string("one").append("two").append("three")

SSIS Text was truncated with status value 4

One possible reason for this error is that your delimiter character (comma, semi-colon, pipe, whatever) actually appears in the data in one column. This can give very misleading error messages, often with the name of a totally different column.

One way to check this is to redirect the 'bad' rows to a separate file and then inspect them manually. Here's a brief explanation of how to do that:

http://redmondmag.com/articles/2010/04/12/log-error-rows-ssis.aspx

If that is indeed your problem, then the best solution is to fix the files at the source to quote the data values and/or use a different delimeter that isn't in the data.

Java: Convert String to TimeStamp

first convert your date string to date then convert it to timestamp by using following set of line

Date date=new Date();
Timestamp timestamp = new Timestamp(date.getTime());//instead of date put your converted date
Timestamp myTimeStamp= timestamp;

How can I use the MS JDBC driver with MS SQL Server 2008 Express?

If your databaseName value is correct, then use this: DriverManger.getconnection("jdbc:sqlserver://ServerIp:1433;user=myuser;password=mypassword;databaseName=databaseName;")

Import cycle not allowed

You may have imported,

project/controllers/base

inside the

project/controllers/routes

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

Using Google Translate in C#

If you want to translate your resources, just download MAT (Multilingual App Toolkit) for Visual Studio. https://marketplace.visualstudio.com/items?itemName=MultilingualAppToolkit.MultilingualAppToolkit-18308 This is the way to go to translate your projects in Visual Studio. https://blogs.msdn.microsoft.com/matdev/

Android: Cancel Async Task

I spent a while figuring this out, all I wanted was a simple example of how to do it, so I thought I'd post how I did it. This is some code that updates a library and has a progress dialog showing how many books have been updated and cancels when a user dismisses the dialog:

private class UpdateLibrary extends AsyncTask<Void, Integer, Boolean>{
    private ProgressDialog dialog = new ProgressDialog(Library.this);
    private int total = Library.instance.appState.getAvailableText().length;
    private int count = 0;

    //Used as handler to cancel task if back button is pressed
    private AsyncTask<Void, Integer, Boolean> updateTask = null;

    @Override
    protected void onPreExecute(){
        updateTask = this;
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setOnDismissListener(new OnDismissListener() {               
            @Override
            public void onDismiss(DialogInterface dialog) {
                updateTask.cancel(true);
            }
        });
        dialog.setMessage("Updating Library...");
        dialog.setMax(total);
        dialog.show();
    }

    @Override
    protected Boolean doInBackground(Void... arg0) {
            for (int i = 0; i < appState.getAvailableText().length;i++){
                if(isCancelled()){
                    break;
                }
                //Do your updating stuff here
            }
        }

    @Override
    protected void onProgressUpdate(Integer... progress){
        count += progress[0];
        dialog.setProgress(count);
    }

    @Override
    protected void onPostExecute(Boolean finished){
        dialog.dismiss();
        if (finished)
            DialogHelper.showMessage(Str.TEXT_UPDATELIBRARY, Str.TEXT_UPDATECOMPLETED, Library.instance);
        else 
            DialogHelper.showMessage(Str.TEXT_UPDATELIBRARY,Str.TEXT_NOUPDATE , Library.instance);
    }
}

C# HttpClient 4.5 multipart/form-data upload

public async Task<object> PassImageWithText(IFormFile files)
{
    byte[] data;
    string result = "";
    ByteArrayContent bytes;

    MultipartFormDataContent multiForm = new MultipartFormDataContent();

    try
    {
        using (var client = new HttpClient())
        {
            using (var br = new BinaryReader(files.OpenReadStream()))
            {
                data = br.ReadBytes((int)files.OpenReadStream().Length);
            }

            bytes = new ByteArrayContent(data);
            multiForm.Add(bytes, "files", files.FileName);
            multiForm.Add(new StringContent("value1"), "key1");
            multiForm.Add(new StringContent("value2"), "key2");

            var res = await client.PostAsync(_MEDIA_ADD_IMG_URL, multiForm);
        }
    }
    catch (Exception e)
    {
        throw new Exception(e.ToString());
    }

    return result;
}

How can I add an empty directory to a Git repository?

Sometimes I have repositories with folders that will only ever contain files considered to be "content"—that is, they are not files that I care about being versioned, and therefore should never be committed. With Git's .gitignore file, you can ignore entire directories. But there are times when having the folder in the repo would be beneficial. Here's a excellent solution for accomplishing this need.

What I've done in the past is put a .gitignore file at the root of my repo, and then exclude the folder, like so:

/app/some-folder-to-exclude
/another-folder-to-exclude/*

However, these folders then don't become part of the repo. You could add something like a README file in there. But then you have to tell your application not to worry about processing any README files.

If your app depends on the folders being there (though empty), you can simply add a .gitignore file to the folder in question, and use it to accomplish two goals:

Tell Git there's a file in the folder, which makes Git add it to the repo. Tell Git to ignore the contents of this folder, minus this file itself. Here is the .gitignore file to put inside your empty directories:

*
!.gitignore

The first line (*) tells Git to ignore everything in this directory. The second line tells Git not to ignore the .gitignore file. You can stuff this file into every empty folder you want added to the repository.

Cannot find java. Please use the --jdkhome switch

In my case, I had installed *ahem* OpenJDK, but the bin folder was full of symlinks to the bundled JRE and the actual JDK was nowhere to be found.

When I see a directory structure with bin and jre subdirectories I expect this to be the JDK installation, because JRE installations on Windows looked different. But in this case it was the JRE installation as found out by apt search. After installing openjdk-8-jre the simlinks were replaced and the directory structure otherwise stayed the same.

How to get URL parameters with Javascript?

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

So you can use:

myvar = getURLParameter('myvar');

How to implement a custom AlertDialog View

The android documents have been edited to correct the errors.

The view inside the AlertDialog is called android.R.id.custom

http://developer.android.com/reference/android/app/AlertDialog.html

Can I do Android Programming in C++, C?

You should look at MoSync too, MoSync gives you standard C/C++, easy-to-use well-documented APIs, and a full-featured Eclipse-based IDE. Its now a open sourced IDE still pretty cool but not maintained anymore.

How to change row color in datagridview?

I had trouble changing the text color as well - I never saw the color change.

Until I added the code to change the text color to the event DataBindingsComplete for DataGridView. After that it worked.

I hope this will help people who face the same problem.

C++ sorting and keeping track of indexes

If it's possible, you can build the position array using find function, and then sort the array.

Or maybe you can use a map where the key would be the element, and the values a list of its position in the upcoming arrays (A, B and C)

It depends on later uses of those arrays.

Remove the last character from a string

You can use substr:

echo substr('a,b,c,d,e,', 0, -1);
# => 'a,b,c,d,e'

Looping Over Result Sets in MySQL

Use cursors.

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

How to right align widget in horizontal linear layout Android?

Use match_parent and gravity to set the TextView text to right, like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <TextView android:text="TextView" android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="right">
    </TextView>

</LinearLayout>

How are parameters sent in an HTTP POST request?

First of all, let's differentiate between GET and POST

Get: It is the default HTTP request that is made to the server and is used to retrieve the data from the server and query string that comes after ? in a URI is used to retrieve a unique resource.

this is the format

GET /someweb.asp?data=value HTTP/1.0

here data=value is the query string value passed.

POST: It is used to send data to the server safely so anything that is needed, this is the format of a POST request

POST /somweb.aspHTTP/1.0
Host: localhost
Content-Type: application/x-www-form-urlencoded //you can put any format here
Content-Length: 11 //it depends
Name= somename

Why POST over GET?

In GET the value being sent to the servers are usually appended to the base URL in the query string,now there are 2 consequences of this

  • The GET requests are saved in browser history with the parameters. So your passwords remain un-encrypted in browser history. This was a real issue for Facebook back in the days.
  • Usually servers have a limit on how long a URI can be. If have too many parameters being sent you might receive 414 Error - URI too long

In case of post request your data from the fields are added to the body instead. Length of request params is calculated, and added to the header for content-length and no important data is directly appended to the URL.

You can use the Google Developer Tools' network section to see basic information about how requests are made to the servers.

and you can always add more values in your Request Headers like Cache-Control , Origin , Accept.

How to fire AJAX request Periodically?

As others have pointed out setInterval and setTimeout will do the trick. I wanted to highlight a bit more advanced technique that I learned from this excellent video by Paul Irish: http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/

For periodic tasks that might end up taking longer than the repeat interval (like an HTTP request on a slow connection) it's best not to use setInterval(). If the first request hasn't completed and you start another one, you could end up in a situation where you have multiple requests that consume shared resources and starve each other. You can avoid this problem by waiting to schedule the next request until the last one has completed:

// Use a named immediately-invoked function expression.
(function worker() {
  $.get('ajax/test.html', function(data) {
    // Now that we've completed the request schedule the next one.
    $('.result').html(data);
    setTimeout(worker, 5000);
  });
})();

For simplicity I used the success callback for scheduling. The down side of this is one failed request will stop updates. To avoid this you could use the complete callback instead:

(function worker() {
  $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
      $('.result').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 5000);
    }
  });
})();

How do I create a user with the same privileges as root in MySQL/MariaDB?

% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;

DateTime.Now.ToShortDateString(); replace month and day

Little addition to Jason's answer:

  1. The ToShortDateString() is culture-sensitive.

From MSDN:

The string returned by the ToShortDateString method is culture-sensitive. It reflects the pattern defined by the current culture's DateTimeFormatInfo object. For example, for the en-US culture, the standard short date pattern is "M/d/yyyy"; for the de-DE culture, it is "dd.MM.yyyy"; for the ja-JP culture, it is "yyyy/M/d". The specific format string on a particular computer can also be customized so that it differs from the standard short date format string.

That's mean it's better to use the ToString() method and define format explicitly (as Jason said). Although if this string appeas in UI the ToShortDateString() is a good solution because it returns string which is familiar to a user.

  1. If you need just today's date you can use DateTime.Today.

Bootstrap 3 with remote Modal

Regarding the remote option for modals, from the docs:

If a remote URL is provided, content will be loaded via jQuery's load method and injected into the root of the modal element.

That means your remote file should provide the complete modal structure, not just what you want to display on the body.

Bootstrap 3.1 Update:

In v3.1 the above behavior was changed and now the remote content is loaded into .modal-content

See this Demo fiddle

Boostrap 3.3 Update:

This option is deprecated since v3.3.0 and has been removed in v4. We recommend instead using client-side templating or a data binding framework, or calling jQuery.load yourself.

how to check if object already exists in a list

Simply use Contains method. Note that it works based on the equality function Equals

bool alreadyExist = list.Contains(item);

Android Service Stops When App Is Closed

Running an intent service will be easier. Service in creating a thread in the application but it's still in the application.

Get connection status on Socket.io client

Track the state of the connection yourself. With a boolean. Set it to false at declaration. Use the various events (connect, disconnect, reconnect, etc.) to reassign the current boolean value. Note: Using undocumented API features (e.g., socket.connected), is not a good idea; the feature could get removed in a subsequent version without the removal being mentioned.

How to show text on image when hovering?

This is what I use to make the text appear on hover:

_x000D_
_x000D_
* {_x000D_
  box-sizing: border-box_x000D_
}_x000D_
_x000D_
div {_x000D_
  position: relative;_x000D_
  top: 0px;_x000D_
  left: 0px;_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  border-radius: 50%;_x000D_
  overflow: hidden;_x000D_
  text-align: center_x000D_
}_x000D_
_x000D_
img {_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  position: absolute;_x000D_
  border-radius: 50%_x000D_
}_x000D_
_x000D_
img:hover {_x000D_
  opacity: 0;_x000D_
  transition:opacity 2s;_x000D_
}_x000D_
_x000D_
heading {_x000D_
  line-height: 40px;_x000D_
  font-weight: bold;_x000D_
  font-family: "Trebuchet MS";_x000D_
  text-align: center;_x000D_
  position: absolute;_x000D_
  display: block_x000D_
}_x000D_
_x000D_
div p {_x000D_
  z-index: -1;_x000D_
  width: 420px;_x000D_
  line-height: 20px;_x000D_
  display: inline-block;_x000D_
  padding: 200px 0px;_x000D_
  vertical-align: middle;_x000D_
  font-family: "Trebuchet MS";_x000D_
  height: 450px_x000D_
}
_x000D_
<div>_x000D_
  <img src="https://68.media.tumblr.com/20b34e8d12d4230f9b362d7feb148c57/tumblr_oiwytz4dh41tf8vylo1_1280.png">_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing <br>elit. Reiciendis temporibus iure dolores aspernatur excepturi <br> corporis nihil in suscipit, repudiandae. Totam._x000D_
  </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Set Label Text with JQuery

The checkbox is in a td, so need to get the parent first:

$("input:checkbox").on("change", function() {
    $(this).parent().next().find("label").text("TESTTTT");
});

Alternatively, find a label which has a for with the same id (perhaps more performant than reverse traversal) :

$("input:checkbox").on("change", function() {
    $("label[for='" + $(this).attr('id') + "']").text("TESTTTT");
});

Or, to be more succinct just this.id:

$("input:checkbox").on("change", function() {
    $("label[for='" + this.id + "']").text("TESTTTT");
});

PHP GuzzleHttp. How to make a post request with params?

$client = new \GuzzleHttp\Client();
$request = $client->post('http://demo.website.com/api', [
    'body' => json_encode($dataArray)
]);
$response = $request->getBody();

Add

openssl.cafile in php.ini file

Getting Lat/Lng from Google marker

try this

var latlng = new google.maps.LatLng(51.4975941, -0.0803232);
var map = new google.maps.Map(document.getElementById('map'), {
    center: latlng,
    zoom: 11,
    mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
    position: latlng,
    map: map,
    title: 'Set lat/lon values for this property',
    draggable: true
});

google.maps.event.addListener(marker, 'dragend', function (event) {
    document.getElementById("latbox").value = this.getPosition().lat();
    document.getElementById("lngbox").value = this.getPosition().lng();
});

shell init issue when click tab, what's wrong with getcwd?

This usually occurs when your current directory does not exist anymore. Most likely, from another terminal you remove that directory (from within a script or whatever). To get rid of this, in case your current directory was recreated in the meantime, just cd to another (existing) directory and then cd back; the simplest would be: cd; cd -.

Cannot find name 'require' after upgrading to Angular4

Still not sure the answer, but a possible workaround is

import * as Chart from 'chart.js';

How to check if smtp is working from commandline (Linux)

Syntax for establishing a raw network connection using telnet is this:

telnet {domain_name} {port_number}

So telnet to your smtp server like

telnet smtp.mydomain.com 25

And copy and paste the below

helo client.mydomain.com
mail from:<[email protected]>
rcpt to:<[email protected]>
data
From: [email protected]
Subject: test mail from command line

this is test number 1
sent from linux box
.
quit

Note : Do not forgot the "." at the end which represents the end of the message. The "quit" line exits ends the session.

How to capture Enter key press?

Use event.key instead of event.keyCode!

function onEvent(event) {
    if (event.key === "Enter") {
        // Submit form
    }
};

Mozilla Docs

Supported Browsers

Convert XML to JSON (and back) using Javascript

The best way to do it using server side as client side doesn't work well in all scenarios. I was trying to build online json to xml and xml to json converter using javascript and I felt almost impossible as it was not working in all scenarios. Ultimately I ended up doing it server side using Newtonsoft in ASP.MVC. Here is the online converter http://techfunda.com/Tools/XmlToJson

Add another class to a div

I use below function to animate UiKit gear icon using Just JavaScript

_x000D_
_x000D_
document.getElementById("spin_it").onmouseover=function(e){_x000D_
var el = document.getElementById("spin_it");_x000D_
var Classes = el.className;_x000D_
var NewClass = Classes+" uk-icon-spin";_x000D_
el.className = NewClass;_x000D_
console.log(e);_x000D_
}
_x000D_
<span class="uk-icon uk-icon-small uk-icon-gear" id="spin_it"></span>
_x000D_
_x000D_
_x000D_

This code not work here...you must add UIKit Style to it

How to check type of variable in Java?

You can check it easily using Java.lang.Class.getSimpleName() Method Only if variable has non-primitive type. It doesnt work with primitive types int ,long etc.

reference - Here is the Oracle docs link

regular expression for DOT

Use String.Replace() if you just want to replace the dots from string. Alternative would be to use Pattern-Matcher with StringBuilder, this gives you more flexibility as you can find groups that are between dots. If using the latter, i would recommend that you ignore empty entries with "\\.+".

public static int count(String str, String regex) {
    int i = 0;
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(str);
    while (m.find()) {
        m.group();
        i++;
    }
    return i;
}

public static void main(String[] args) {
    int i = 0, j = 0, k = 0;
    String str = "-.-..-...-.-.--..-k....k...k..k.k-.-";

    // this will just remove dots
    System.out.println(str.replaceAll("\\.", ""));
    // this will just remove sequences of ".." dots
    System.out.println(str.replaceAll("\\.{2}", ""));
    // this will just remove sequences of dots, and gets
    // multiple of dots as 1
    System.out.println(str.replaceAll("\\.+", ""));

    /* for this to be more obvious, consider following */
    System.out.println(count(str, "\\."));
    System.out.println(count(str, "\\.{2}"));
    System.out.println(count(str, "\\.+"));
}

The output will be:

--------kkkkk--
-.--.-.-.---kk.kk.k-.-
--------kkkkk--
21
7
11

Get the last day of the month in SQL

---Start/End of previous Month 
Declare @StartDate datetime, @EndDate datetime

set @StartDate = DATEADD(month, DATEDIFF(month, 0, GETDATE())-1,0) 
set @EndDate = EOMONTH (DATEADD(month, DATEDIFF(month, 0, GETDATE())-1,0)) 

SELECT @StartDate,@EndDate

Doctrine2: Best way to handle many-to-many with extra columns in reference table

Nothing beats a nice example

For people looking for a clean coding example of an one-to-many/many-to-one associations between the 3 participating classes to store extra attributes in the relation check this site out:

nice example of one-to-many/many-to-one associations between the 3 participating classes

Think about your primary keys

Also think about your primary key. You can often use composite keys for relationships like this. Doctrine natively supports this. You can make your referenced entities into ids. Check the documentation on composite keys here

What does "restore purchases" in In-App purchases mean?

Is it as optional functionality.

If you won't provide it when user will try to purchase non-consumable product AppStore will restore old transaction. But your app will think that this is new transaction.

If you will provide restore mechanism then your purchase manager will see restored transaction.

If app should distinguish this options then you should provide functionality for restoring previously purchased products.

Give column name when read csv file pandas

If we are directly use data from csv it will give combine data based on comma separation value as it is .csv file.

user1 = pd.read_csv('dataset/1.csv')

If you want to add column names using pandas, you have to do something like this. But below code will not show separate header for your columns.

col_names=['TIME', 'X', 'Y', 'Z'] 
user1 = pd.read_csv('dataset/1.csv', names=col_names)

To solve above problem we have to add extra filled which is supported by pandas, It is header=None

user1 = pd.read_csv('dataset/1.csv', names=col_names, header=None)

Get img src with PHP

You would be better off using a DOM parser for this kind of HTML parsing. Consider this code:

$html = '<img id="12" border="0" src="/images/image.jpg"
         alt="Image" width="100" height="100" />';
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html); // loads your html
$xpath = new DOMXPath($doc);
$nodelist = $xpath->query("//img"); // find your image
$node = $nodelist->item(0); // gets the 1st image
$value = $node->attributes->getNamedItem('src')->nodeValue;
echo "src=$value\n"; // prints src of image

OUTPUT:

src=/images/image.jpg

Substring in VBA

You can first find the position of the string in this case ":"

'position = InStr(StringToSearch, StringToFind)
position = InStr(StringToSearch, ":")

Then use Left(StringToCut, NumberOfCharacterToCut)

Result = Left(StringToSearch, position -1)

Grep for beginning and end of line?

It looks like you were on the right track... The ^ character matches beginning-of-line, and $ matches end-of-line. Jonathan's pattern will work for you... just wanted to give you the explanation behind it

What is the purpose of Node.js module.exports and how do you use it?

the module.exports property or the exports object allows a module to select what should be shared with the application

enter image description here

I have a video on module_export available here

php error: Class 'Imagick' not found

On an EC2 at AWS, I did this:

 yum list | grep imagick

Then found a list of ones I could install...

 php -v

told me which version of php I had and thus which version of imagick

yum install php56-pecl-imagick.x86_64

Did the trick. Enjoy!

Access files stored on Amazon S3 through web browser

I had the same problem and I fixed it by using the

  1. new context menu "Make Public".
  2. Go to https://console.aws.amazon.com/s3/home,
  3. select the bucket and then for each Folder or File (or multiple selects) right click and
  4. "make public"

concatenate char array in C

First copy the current string to a larger array with strcpy, then use strcat.

For example you can do:

char* str = "Hello";
char dest[12];

strcpy( dest, str );
strcat( dest, ".txt" );

No space left on device

You can execute the following commands

lsof / |grep deleted

kill the process id's, which free up the disk space.

Python: How to get stdout after running os.system?

commands also works.

import commands
batcmd = "dir"
result = commands.getoutput(batcmd)
print result

It works on linux, python 2.7.

Remove a file from the list that will be committed

Use stash; like this:

git add .
git reset Files/I/Want/To/Keep
git stash --keep-index
git commit -a -m "Done!"
git stash pop

If you accidentally commit a file, and want to rewrite your git history, use:

git reset HEAD~1 path/to/file
git commit -a -m "rollback"
git rebase -i HEAD~2

and squash to the two leading commits. You can write a helper script to do either of these if you have a known set of files you prefer not to automatically commit.

What does the percentage sign mean in Python

While this is slightly off-topic, since people will find this by searching for "percentage sign in Python" (as I did), I wanted to note that the % sign is also used to prefix a "magic" function in iPython: https://ipython.org/ipython-doc/3/interactive/tutorial.html#magic-functions

How can I create a keystore?

Create keystore file from command line :

  1. Open Command line:

    Microsoft Windows [Version 6.1.7601]
    Copyright (c) 2009 Microsoft Corporation.  All rights reserved
    
    // (if you want to store keystore file at C:/ open command line with RUN AS ADMINISTRATOR)
    
    C:\Windows\system32> keytool -genkey -v -keystore [your keystore file path]{C:/index.keystore} -alias [your_alias_name]{index} -keyalg RSA -keysize 2048 -validity 10000[in days]
    
  2. Enter > It will prompt you for password > enter password (it will be invisible)

    Enter keystore password:
    Re-enter new password:
    
  3. Enter > It will ask your detail.

    What is your first and last name?
     [Unknown]:  {AB} // [Your Name / Name of Signer] 
    What is the name of your organizational unit?
     [Unknown]:  {Self} // [Your Unit Name] 
    What is the name of your organization?
     [Unknown]:  {Self} // [Your Organization Name] 
    What is the name of your City or Locality?
     [Unknown]:  {INDORE} // [Your City Name] 
    What is the name of your State or Province?
     [Unknown]:  {MP} //[Your State] 
    What is the two-letter country code for this unit?
     [Unknown]:  91
    
  4. Enter > Enter Y

    Is CN=AB, OU=Self, O=Self, L=INDORE, ST=MP, C=91 correct?
    [no]:  Y
    
  5. Enter > Enter password again.

    Generating 2,048 bit RSA key pair and self-signed certificate    (SHA256withRSA) with a validity of 10,000 days
        for: CN=AB, OU=Self, O=Self, L=INDORE, ST=MP, C=91
    Enter key password for <index> (RETURN if same as keystore password):
    Re-enter new password:
    

[ Storing C:/index.keystore ]

  1. And your are DONE!!!

Export In Eclipse :

Export your android package to .apk with your created keystore file

  1. Right click on Package you want to export and select export enter image description here

  2. Select Export Android Application > Next enter image description here

  3. Next
    enter image description here

  4. Select Use Existing Keystore > Browse .keystore file > enter password > Next enter image description here

  5. Select Alias > enter password > Next enter image description here

  6. Browse APK Destination > Finish enter image description here

In Android Studio:

Create keystore [.keystore/.jks] in studio...

  1. Click Build (ALT+B) > Generate Signed APK...
    enter image description here

  2. Click Create new..(ALT+C)
    enter image description here

  3. Browse Key store path (SHIFT+ENTER) > Select Path > Enter name > OK enter image description here

  4. Fill the detail about your .jks/keystore file enter image description here

  5. Next
    enter image description here

  6. Your file
    enter image description here

  7. Enter Studio Master Password (You can RESET if you don't know) > OK enter image description here

  8. Select *Destination Folder * > Build Type

    release : for publish on app store
    debug : for debugging your application
    

    Click Finish

    enter image description here

Done !!!

String.equals() with multiple conditions (and one action on result)

No,its check like if string is "john" OR "mary" OR "peter" OR "etc."

you should check using ||

Like.,,if(str.equals("john") || str.equals("mary") || str.equals("peter"))

Can anyone recommend a simple Java web-app framework?

I really don't see what is the big deal with getting maven + eclipse to work, as long as you don't have to change the pom.xml too much :)

Most frameworks that user maven have maven archetypes that can generate stub project.

So basically the steps should be:

  1. Install maven
  2. Add M2_REPO class path variable to eclipse
  3. Generate project with the archetype
  4. Import project to eclipse

As for Wicket, there is no reason why you couldn't use it without maven. The nice thing about maven is that it takes care of all the dependencies so you don't have to. On the other hand, if the only thing you want to do is to prototype couple of pages than Wicket can be overkill. But, should your application grow, eventually, the benefits of Wicket would keep showing with each added form, link or page :)

Regex pattern to match at least 1 number and 1 character in a string

This solution accepts at least 1 number and at least 1 character:

[^\w\d]*(([0-9]+.*[A-Za-z]+.*)|[A-Za-z]+.*([0-9]+.*))

Which rows are returned when using LIMIT with OFFSET in MySQL?

You will get output from column value 9 to 26 as you have mentioned OFFSET as 8

Check difference in seconds between two times

I use this to avoid negative interval.

var seconds = (date1< date2)? (date2- date1).TotalSeconds: (date1 - date2).TotalSeconds;

How to select all checkboxes with jQuery?

One checkbox to rule them all

For people still looking for plugin to control checkboxes through one that's lightweight, has out-of-the-box support for UniformJS and iCheck and gets unchecked when at least one of controlled checkboxes is unchecked (and gets checked when all controlled checkboxes are checked of course) I've created a jQuery checkAll plugin.

Feel free to check the examples on documentation page.


For this question example all you need to do is:

$( '#select_all' ).checkall({
    target: 'input[type="checkbox"][name="select"]'
});

Isn't that clear and simple?

Default behavior of "git push" without a branch specified

Here is a very handy and helpful information about Git Push: Git Push: Just the Tip

The most common use of git push is to push your local changes to your public upstream repository. Assuming that the upstream is a remote named "origin" (the default remote name if your repository is a clone) and the branch to be updated to/from is named "master" (the default branch name), this is done with: git push origin master

git push origin will push changes from all local branches to matching branches the origin remote.

git push origin master will push changes from the local master branch to the remote master branch.

git push origin master:staging will push changes from the local master branch to the remote staging branch if it exists.

Tomcat: How to find out running tomcat version

Using the release notes

In the main Tomcat folder you can find the RELEASE-NOTES file which contains the following lines (~line 20-21):

                Apache Tomcat Version 8.0.22
                        Release Notes

Or you can get the same information using command line:

  • Windows:

    type RELEASE-NOTES | find "Apache Tomcat Version"
    

    Output:

                 Apache Tomcat Version 8.0.22
    
  • Linux:

    cat RELEASE-NOTES | grep "Apache Tomcat Version"
    

    Output:

                 Apache Tomcat Version 8.0.22
    

Python sys.argv lists and indexes

sys.argv is the list of arguments passed to the Python program. The first argument, sys.argv[0], is actually the name of the program as it was invoked. That's not a Python thing, but how most operating systems work. The reason sys.argv[0] exists is so you can change your program's behaviour depending on how it was invoked. sys.argv[1] is thus the first argument you actually pass to the program.

Because lists (like most sequences) in Python start indexing at 0, and because indexing past the end of the list is an error, you need to check if the list has length 2 or longer before you can access sys.argv[1].

Trim Cells using VBA in Excel

If you have a non-printing character at the front of the string try this


Option Explicit
Sub DoTrim()
    Dim cell As Range
    Dim str As String
    Dim nAscii As Integer
    For Each cell In Selection.Cells
        If cell.HasFormula = False Then
            str = Trim(CStr(cell))
            If Len(str) > 0 Then
                nAscii = Asc(Left(str, 1))
                If nAscii < 33 Or nAscii = 160 Then
                    If Len(str) > 1 Then
                        str = Right(str, Len(str) - 1)
                    Else
                        strl = ""
                    End If
                End If
            End If
            cell=str
        End If
    Next
End Sub

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

Swift 3 Bonus: Why didn't anyone mention the short form?

CGRect(origin: .zero, size: size)

.zero instead of CGPoint.zero

When the type is defined, you can safely omit it.

When should I use h:outputLink instead of h:commandLink?

The <h:outputLink> renders a fullworthy HTML <a> element with the proper URL in the href attribute which fires a bookmarkable GET request. It cannot directly invoke a managed bean action method.

<h:outputLink value="destination.xhtml">link text</h:outputLink>

The <h:commandLink> renders a HTML <a> element with an onclick script which submits a (hidden) POST form and can invoke a managed bean action method. It's also required to be placed inside a <h:form>.

<h:form>
    <h:commandLink value="link text" action="destination" />
</h:form>

The ?faces-redirect=true parameter on the <h:commandLink>, which triggers a redirect after the POST (as per the Post-Redirect-Get pattern), only improves bookmarkability of the target page when the link is actually clicked (the URL won't be "one behind" anymore), but it doesn't change the href of the <a> element to be a fullworthy URL. It still remains #.

<h:form>
    <h:commandLink value="link text" action="destination?faces-redirect=true" />
</h:form>

Since JSF 2.0, there's also the <h:link> which can take a view ID (a navigation case outcome) instead of an URL. It will generate a HTML <a> element as well with the proper URL in href.

<h:link value="link text" outcome="destination" />

So, if it's for pure and bookmarkable page-to-page navigation like the SO username link, then use <h:outputLink> or <h:link>. That's also better for SEO since bots usually doesn't cipher POST forms nor JS code. Also, UX will be improved as the pages are now bookmarkable and the URL is not "one behind" anymore.

When necessary, you can do the preprocessing job in the constructor or @PostConstruct of a @RequestScoped or @ViewScoped @ManagedBean which is attached to the destination page in question. You can make use of @ManagedProperty or <f:viewParam> to set GET parameters as bean properties.

See also:

How to identify and switch to the frame in selenium webdriver when frame does not have id

Easiest way of doing this is like this. If its a frame you can right click on the field and if you see the choice of "open frame in a tab" do it.

Then take the URL of the frame and that is what you put in your Python script using "driver.get (http://blah blah..)

Then Selenium can find your named element. This saved me hours of trying all the suggestions here which was learning about but didn't work. Problem with mine was it was in a frame.

I'm using Linux which gives me the right-click option of opening the frame, on its own, in another tab. I don't use Windows so don't know if you would get that option in you right-click menu.

Ganzarola

CSS how to make scrollable list

As per your question vertical listing have a scrollbar effect.

CSS / HTML :

_x000D_
_x000D_
nav ul{height:200px; width:18%;}_x000D_
nav ul{overflow:hidden; overflow-y:scroll;}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <head>_x000D_
        <meta charset="utf-8">_x000D_
        <title>JS Bin</title>_x000D_
    </head>_x000D_
    <body>_x000D_
        <header>header area</header>_x000D_
        <nav>_x000D_
            <ul>_x000D_
                <li>Link 1</li>_x000D_
                <li>Link 2</li>_x000D_
                <li>Link 3</li>_x000D_
                <li>Link 4</li>_x000D_
                <li>Link 5</li>_x000D_
                <li>Link 6</li> _x000D_
                <li>Link 7</li> _x000D_
                <li>Link 8</li>_x000D_
                <li>Link 9</li>_x000D_
                <li>Link 10</li>_x000D_
                <li>Link 11</li>_x000D_
                <li>Link 13</li>_x000D_
                <li>Link 13</li>_x000D_
_x000D_
            </ul>_x000D_
        </nav>_x000D_
        _x000D_
        <footer>footer area</footer>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

get UTC time in PHP

with string GMT/UTC +/-0400 or GMT/UTC +/-1000 based on local timings

Your custom format is just missing O to give you the timezone offsets from local time.

Difference to Greenwich time (GMT) in hours Example: +0200

date_default_timezone_set('America/La_Paz');
echo date('Y-m-d H:i:s O');

2018-01-12 12:10:11 -0400

However, for maximized portability/interoperability, I would recommend using the ISO8601 date format c

date_default_timezone_set('America/La_Paz');
echo date('c');

2018-01-12T12:10:11-04:00

date_default_timezone_set('Australia/Brisbane');
echo date('c');

2018-01-13T02:10:11+10:00

You can use also gmdate and the timezone offset string will always be +00:00

date_default_timezone_set('America/La_Paz');
echo gmdate('c');

2018-01-12T16:10:11+00:00

date_default_timezone_set('Australia/Brisbane');
echo gmdate('c');

2018-01-12T16:10:11+00:00

crudrepository findBy method signature with multiple in operators?

The following signature will do:

List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);

Spring Data JPA supports a large number of keywords to build a query. IN and AND are among them.

Background image jumps when address bar hides iOS/Android/Mobile Chrome

I found that Jason's answer wasn't quite working for me and I was still getting a jump. The Javascript ensured there was no gap at the top of the page but the background was still jumping whenever the address bar disappeared/reappeared. So as well as the Javascript fix, I applied transition: height 999999s to the div. This creates a transition with a duration so long that it virtually freezes the element.

Make child div stretch across width of page

...............In HTML Format

<div id="a">Full Width</div>

...............In CSS Format

#a { background-color: green;width: 100%;height: 80px;border: 1px solid;margin: 0 auto;} 

    body { padding: 0;margin: 0}

Deserialize from string instead TextReader

1-liner, takes a XML string text and YourType as the expected object type. not very different from other answers, just compressed to 1 line:

var result =  (YourType)new XmlSerializer(typeof(YourType)).Deserialize(new StringReader(text));

How to set downloading file name in ASP.NET Web API

EDIT: As mentioned in a comment, My answer doesn't account for characters that need to be escaped like a ;. You should use the accepted answer Darin made if your file name could contain a semi-colon.

Add a Response.AddHeader to set the file name

Response.AddHeader("Content-Disposition", "attachment; filename=*FILE_NAME*");

Just change FILE_NAME to the name of the file.

Create a root password for PHPMyAdmin

I believe the command you are looking for is passwd

How do I read an attribute on a class at runtime?

There is already an extension to do this.

namespace System.Reflection
{
    // Summary:
    //     Contains static methods for retrieving custom attributes.
    public static class CustomAttributeExtensions
    {
        public static T GetCustomAttribute<T>(this MemberInfo element, bool inherit) where T : Attribute;
    }
}

So:

var attr = typeof(MyClass).GetCustomAttribute<DomainNameAttribute>(false);
return attr != null ? attr.DomainName : "";

Viewing all defined variables

a bit more smart (python 3) way:

def printvars():

   tmp = globals().copy()
   [print(k,'  :  ',v,' type:' , type(v)) for k,v in tmp.items() if not k.startswith('_') and k!='tmp' and k!='In' and k!='Out' and not hasattr(v, '__call__')]

How to include External CSS and JS file in Laravel 5

In laravel 5.1,

 <link rel="stylesheet" href="{{URL::asset('assets/css/bootstrap.min.css')}}">
 <script type="text/javascript" src="{{URL::asset('assets/js/jquery.min.js')}}"></script>

Where assets folder location is inside public folder

How to sort in mongoose?

UPDATE:

Post.find().sort({'updatedAt': -1}).all((posts) => {
  // do something with the array of posts
});

Try:

Post.find().sort([['updatedAt', 'descending']]).all((posts) => {
  // do something with the array of posts
});

Html.fromHtml deprecated in Android N

I had a lot of these warnings and I always use FROM_HTML_MODE_LEGACY so I made a helper class called HtmlCompat containing the following:

   @SuppressWarnings("deprecation")
   public static Spanned fromHtml(String source) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return Html.fromHtml(source, Html.FROM_HTML_MODE_LEGACY);
        } else {
            return Html.fromHtml(source);
        }
    }

Setting HTTP headers

I know this is a different twist on the answer, but isn't this more of a concern for a web server? For example, nginx, could help.

The ngx_http_headers_module module allows adding the “Expires” and “Cache-Control” header fields, and arbitrary fields, to a response header

...

location ~ ^<REGXP MATCHING CORS ROUTES> {
    add_header Access-Control-Allow-Methods POST
    ...
}
...

Adding nginx in front of your go service in production seems wise. It provides a lot more feature for authorizing, logging,and modifying requests. Also, it gives the ability to control who has access to your service and not only that but one can specify different behavior for specific locations in your app, as demonstrated above.

I could go on about why to use a web server with your go api, but I think that's a topic for another discussion.

Upload video files via PHP and save them in appropriate folder and have a database entry

sample code:

<em><b>
<h2>Upload,Save and Download video </h2>
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="video"/>
<input type="submit" name="submit" value="Upload"/></b>
</form></em>

<?php>
include("connect.php");
$errors=1;
//Targeting Folder
$target="videos/";
if(isset($_POST['submit'])){
//Targeting Folder 
$target=$target.basename($_FILES['video']['name']);
//Getting Selected video Type
$type=pathinfo($target,PATHINFO_EXTENSION);
 //Allow Certain File Format To Upload
 if($type!='mp4' && $type!='3gp' && $type!='avi'){
  echo "Only mp4,3gp,avi file format are allowed to Upload";
  $errors=0;
 }
 //checking for Exsisting video Files
  if(file_exists($target)){
   echo "File Exist";
   $errors=0;
   }
  $filesize=$_FILES['video']['size'];
  if($filesize>250*2000000){
  echo 'You Can not Upload Large File(more than 500MB) by Default ini setting..<a     href="http://www.codenair.com/2018/03/how-to-upload-large-file-in-php.html">How to   upload large file in php</a>'; 
    $errors=0;
    }
   if($errors == 0){
   echo ' Your File Not Uploaded';
    }else{
 //Moving The video file to Desired Directory
  $uplaod_success=move_uploaded_file($_FILES['video']['tmp_name'],$target);
  if($uplaod_success){
  //Getting Selected video Information
    $name=$_FILES['video']['name'];
    $size=$_FILES['video']['size'];
    $result=mysqli_query($con,"INSERT INTO VIdeos           (name,size,type)VALUES('".$name."','".$size."','".$type."')");
    if($result==TRUE){
    echo "Your video '$name' Successfully Upload and Information Saved Our  Database";
    }
   }
  }
  }
 ?>

How to run docker-compose up -d at system start up?

When we use crontab or the deprecated /etc/rc.local file, we need a delay (e.g. sleep 10, depending on the machine) to make sure that system services are available. Usually, systemd (or upstart) is used to manage which services start when the system boots. You can try use the similar configuration for this:

# /etc/systemd/system/docker-compose-app.service

[Unit]
Description=Docker Compose Application Service
Requires=docker.service
After=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/srv/docker
ExecStart=/usr/local/bin/docker-compose up -d
ExecStop=/usr/local/bin/docker-compose down
TimeoutStartSec=0

[Install]
WantedBy=multi-user.target

Or, if you want run without the -d flag:

# /etc/systemd/system/docker-compose-app.service

[Unit]
Description=Docker Compose Application Service
Requires=docker.service
After=docker.service

[Service]
WorkingDirectory=/srv/docker
ExecStart=/usr/local/bin/docker-compose up
ExecStop=/usr/local/bin/docker-compose down
TimeoutStartSec=0
Restart=on-failure
StartLimitIntervalSec=60
StartLimitBurst=3

[Install]
WantedBy=multi-user.target

Change the WorkingDirectory parameter with your dockerized project path. And enable the service to start automatically:

systemctl enable docker-compose-app

Remove URL parameters without refreshing page

Here is an ES6 one liner which preserves the location hash and does not pollute browser history by using replaceState:

(l=>{window.history.replaceState({},'',l.pathname+l.hash)})(location)

What's the difference between echo, print, and print_r in PHP?

Just to add to John's answer, echo should be the only one you use to print content to the page.

print is slightly slower. var_dump() and print_r() should only be used to debug.

Also worth mentioning is that print_r() and var_dump() will echo by default, add a second argument to print_r() at least that evaluates to true to get it to return instead, e.g. print_r($array, TRUE).

The difference between echoing and returning are:

  • echo: Will immediately print the value to the output.
  • returning: Will return the function's output as a string. Useful for logging, etc.

Calling @Html.Partial to display a partial view belonging to a different controller

As GvS said, but I also find it useful to use strongly typed views so that I can write something like

@Html.Partial(MVC.Student.Index(), model)

without magic strings.

Calculate MD5 checksum for a file

Here is a slightly simpler version that I found. It reads the entire file in one go and only requires a single using directive.

byte[] ComputeHash(string filePath)
{
    using (var md5 = MD5.Create())
    {
        return md5.ComputeHash(File.ReadAllBytes(filePath));
    }
}

Sending SMS from PHP

PHP by itself has no SMS module or functions and doesn't allow you to send SMS.

SMS ( Short Messaging System) is a GSM technology an you need a GSM provider that will provide this service for you and may have an PHP API implementation for it.

Usually people in telecom business use Asterisk to handle calls and sms programming.

TypeError: unsupported operand type(s) for /: 'str' and 'str'

I would have written:

percent = 100
while True:
     try:
        pyc = int(input('enter pyc :'))
        tpy = int(input('enter tpy:'))
        percent = (pyc / tpy) * percent
        break
     except ZeroDivisionError as detail:
        print 'Handling run-time error:', detail

How to install both Python 2.x and Python 3.x in Windows

I found that the formal way to do this is as follows:

Just install two (or more, using their installers) versions of Python on Windows 7 (for me work with 3.3 and 2.7).

Follow the instuctions below, changing the parameters for your needs.

Create the following environment variable (to default on double click):

Name:  PY_PYTHON
Value: 3

To launch a script in a particular interpreter, add the following shebang (beginning of script):

#! python2

To execute a script using a specific interpreter, use the following prompt command:

> py -2 MyScript.py

To launch a specific interpreter:

> py -2

To launch the default interpreter (defined by the PY_PYTHON variable):

> py

Resources

Documentation: Using Python on Windows

PEP 397 - Python launcher for Windows

Why do this() and super() have to be the first statement in a constructor?

Simply because this is the inheritance philosophy. And according to the Java language specification, this is how the constructor's body is defined:

ConstructorBody: { ExplicitConstructorInvocationopt    BlockStatementsopt }

The first statement of a constructor body may be either

  • an explicit invocation of another constructor of the same class (by using the keyword "this"); or
  • an explicit invocation of the direct superclass (by using the keyword "super")

If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments. And so on.. there will be a whole chain of constructors called all the way back to the constructor of Object; "All Classes in the Java platform are Descendants of Object". This thing is called "Constructor Chaining".

Now why is this?
And the reason why Java defined the ConstructorBody in this way, is that they needed to maintain the hierarchy of the object. Remember the definition of the inheritance; It's extending a class. With that being said, you cannot extend something that doesn't exist. The base (the superclass) needs to be created first, then you can derive it (the subclass). That's why they called them Parent and Child classes; you can't have a child without a parent.

On a technical level, a subclass inherits all the members (fields, methods, nested classes) from its parent. And since Constructors are NOT members (They don't belong to objects. They are responsible of creating objects) so they are NOT inherited by subclasses, but they can be invoked. And since at the time of object creation only ONE constructor is executed. So how do we guarantee the creation of the superclass when you create the subclass object? Thus the concept of "constructor chaining"; so we have the ability to invoke other constructors (i.e. super) from within the current constructor. And Java required this invocation to be the FIRST line in the subclass constructor to maintain the hierarchy and guarantee it. They assume that if you don't explicitly create the parent object FIRST (like if you forgot about it), they will do it implicitly for you.

This check is done during compilation. But I'm not sure what would happen on runtime, what kind of runtime error we would get, IF Java doesn't throw a compile-error when we explicitly try to execute a base constructor from within a subclass's constructor in the middle of its body and not from the very first line ...

Git list of staged files

The best way to do this is by running the command:

git diff --name-only --cached

When you check the manual you will likely find the following:

--name-only
    Show only names of changed files.

And on the example part of the manual:

git diff --cached
    Changes between the index and your current HEAD.

Combined together you get the changes between the index and your current HEAD and Show only names of changed files.

Update: --staged is also available as an alias for --cached above in more recent git versions.

Keyword not supported: "data source" initializing Entity Framework Context

This appears to be missing the providerName="System.Data.EntityClient" bit. Sure you got the whole thing?

text-align: right on <select> or <option>

The best solution for me was to make

select {
    direction: rtl;
}

and then

option {
    direction: ltr;
}

again. So there is no change in how the text is read in a screen reader or and no formatting-problem.

Working with select using AngularJS's ng-options

I hope the following will work for you.

<select class="form-control"
        ng-model="selectedOption"
        ng-options="option.name + ' (' + (option.price | currency:'USD$') + ')' for option in options">
</select>

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

Typescript: How to define type for a function callback used in a method parameter?

You can declare the callback as 1) function property or 2) method:

interface ParamFnProp {
    callback: (a: Animal) => void; // function property
}

interface ParamMethod {
    callback(a: Animal): void; // method
}

There is an important typing difference since TS 2.6:

You get stronger ("sound") types in --strict or --strictFunctionTypes mode, when a function property is declared. Let's take an example:

const animalCallback = (a: Animal): void => { } // Animal is the base type for Dog
const dogCallback = (d: Dog): void => { } 
// function property variant
const param11: ParamFnProp = { callback: dogCallback } // error: not assignable
const param12: ParamFnProp = { callback: animalCallback } // works

// method variant
const param2: ParamMethod = { callback: dogCallback } // now it works again ...

Technically spoken, methods are bivariant and function properties contravariant in their arguments under strictFunctionTypes. Methods are still checked more permissively (even if not sound) to be a bit more practical in combination with built-in types like Array.

Summary

  • There is a type difference between function property and method declaration
  • Choose a function property for stronger types, if possible

Playground sample code

How can I get input radio elements to horizontally align?

This also works like a charm

_x000D_
_x000D_
<form>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio" checked>Option 1_x000D_
    </label>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 2_x000D_
    </label>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 3_x000D_
    </label>_x000D_
  </form>
_x000D_
_x000D_
_x000D_

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

These are the steps I took (I'm on Linux).

  • Switched to Software rendering (works but is too slow)
  • Tried running on commanline and an error displayed.
  • Forced emulator to use the system graphic drivers.

First, as @jlars62 suggested, I tried using Switching the Graphics to "Software" and this DID work. However, the performance is far to slow so I dug a little deeper.

Then I tried running the device from the console, as @CaptainCrunch suggestion. (My device was created in Android Studio; emulator in the Sdk may be in a different place on your system)

$ ~/Android/Sdk/emulator/emulator -avd Nexus_6_Edited_768Mb_API_23

For me this produced the following error:

libGL error: unable to load driver: i965_dri.so 
libGL error: driver
pointer missing libGL error: failed to load driver: i965 
...

Which I tracked down (on ArchLinux) to mean it's using the wrong graphic drivers (Android Sdk comes with it's own). You can force the system ones on the commandline with -use-system-libs:

$ ~/Android/Sdk/emulator/emulator -avd Nexus_6_Edited_768Mb_API_23 -use-system-libs

To force Android Studio to do this you can intercept the call to "emulator" like so (See Mike42) :

$ cd ~/Android/Sdk/tools/
$ mv emulator emulator.0
$ touch emulator
$ chmod +x emulator

In the new emulator file add this:

#!/bin/sh
set -ex
$0.0 $@ -use-system-libs

Can grep show only words that match search pattern?

grep command for only matching and perl

grep -o -P 'th.*? ' filename

Passing structs to functions

bool data(sampleData *data)
{
}

You need to tell the method which type of struct you are using. In this case, sampleData.

Note: In this case, you will need to define the struct prior to the method for it to be recognized.

Example:

struct sampleData
{
   int N;
   int M;
   // ...
};

bool data(struct *sampleData)
{

}

int main(int argc, char *argv[]) {

      sampleData sd;
      data(&sd);

}

Note 2: I'm a C guy. There may be a more c++ish way to do this.

Link a .css on another folder

I think what you want to do is

_x000D_
_x000D_
<link rel="stylesheet" type="text/css" href="font/font-face/my-font-face.css">
_x000D_
_x000D_
_x000D_

How to bring an activity to foreground (top of stack)?

If you want to bring an activity to the top of the stack when clicking on a Notification then you may need to do the following to make the FLAG_ACTIVITY_REORDER_TO_FRONT work:

The solution for me for this was to make a broadcast receiver that listens to broadcast actions that the notification triggers. So basically:

  1. Notification triggers a broadcast action with an extra the name of the activity to launch.

  2. Broadcast receiver catches this when the notification is clicked, then creates an intent to launch that activity using the FLAG_ACTIVITY_REORDER_TO_FRONT flag

  3. Activity is brought to the top of activity stack, no duplicates.

Python string prints as [u'String']

You probably have a list containing one unicode string. The repr of this is [u'String'].

You can convert this to a list of byte strings using any variation of the following:

# Functional style.
print map(lambda x: x.encode('ascii'), my_list)

# List comprehension.
print [x.encode('ascii') for x in my_list]

# Interesting if my_list may be a tuple or a string.
print type(my_list)(x.encode('ascii') for x in my_list)

# What do I care about the brackets anyway?
print ', '.join(repr(x.encode('ascii')) for x in my_list)

# That's actually not a good way of doing it.
print ' '.join(repr(x).lstrip('u')[1:-1] for x in my_list)

Eclipse reports rendering library more recent than ADT plug-in

Please try once uninstalling from Help-->Installation details

and try again installing using http://dl-ssl.google.com/android/eclipse/

java.lang.RuntimeException: Uncompilable source code - what can cause this?

I also got the same error and I did clean build and it worked.

How do I convert from BLOB to TEXT in MySQL?

SELECCT TO_BASE64(blobfield)  
FROM the Table

worked for me.

The CAST(blobfield AS CHAR(10000) CHARACTER SET utf8) and CAST(blobfield AS CHAR(10000) CHARACTER SET utf16) did not show me the text value I wanted to get.

How to filter data in dataview

DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";

// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");

Ref: http://www.csharp-examples.net/dataview-rowfilter/

http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

First of all, enable the less secure app in your Gmail account from which you will send emails using this link:- https://myaccount.google.com/lesssecureapps?pli=1

Then you simply add the following code in your session creation. It will work fine then.

Session mailSession = Session.getInstance(props, new javax.mail.Authenticator(){
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                    "your_email", "your_password");// Specify the Username and the PassWord
            }
        });

if you want the more elaborated one use the following:-

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MailSender {

    public Properties mailProperties() {
        Properties props = new Properties();

        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.port", "587");
        props.setProperty("mail.smtp.user", "your_email");
        props.setProperty("mail.smtp.password", "your_password");
        props.setProperty("mail.smtp.starttls.enable", "true");
        props.setProperty("mail.smtp.auth", "true");

        return props;
    }

    public String sendMail(String from, String to, String subject, String msgBody) {
        Properties props = mailProperties();
        Session mailSession = Session.getInstance(props, new javax.mail.Authenticator(){
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                    "your_email", "your_password");// Specify the Username and the PassWord
            }
        });

        mailSession.setDebug(false);

        try {
            Transport transport = mailSession.getTransport();

            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject(subject);
            message.setFrom(new InternetAddress(from));
            message.addRecipients(Message.RecipientType.TO, to);

            MimeMultipart multipart = new MimeMultipart();

            MimeBodyPart messageBodyPart = new MimeBodyPart();

            messageBodyPart.setContent(msgBody, "text/html");

            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);

            transport.connect();
            transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
            transport.close();
            return "SUCCESS";
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
            return "INVALID_EMAIL";
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return "ERROR";
    }

    public static void main(String args[]) {
        System.out.println(new MailSender().sendMail("your_email/from_email", "to_email", "Subject", "Message"));
    }
}

Hope! it helps. Thanks!

Using Mockito's generic "any()" method

As I needed to use this feature for my latest project (at one point we updated from 1.10.19), just to keep the users (that are already using the mockito-core version 2.1.0 or greater) up to date, the static methods from the above answers should be taken from ArgumentMatchers class:

import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.ArgumentMatchers.any;

Please keep this in mind if you are planning to keep your Mockito artefacts up to date as possibly starting from version 3, this class may no longer exist:

As per 2.1.0 and above, Javadoc of org.mockito.Matchers states:

Use org.mockito.ArgumentMatchers. This class is now deprecated in order to avoid a name clash with Hamcrest * org.hamcrest.Matchers class. This class will likely be removed in version 3.0.

I have written a little article on mockito wildcards if you're up for further reading.

Change string color with NSAttributedString?

Update for Swift 4.2

var attributes = [NSAttributedString.Key: AnyObject]()

attributes[.foregroundColor] = UIColor.blue

let attributedString = NSAttributedString(string: "Very Bad",
attributes: attributes)

label.attributedText = attributedString

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

3 steps to download the Google Play services Using Genymotion emulator

1. click the right bottom arrow in the toolbar enter image description here

2. Downloading Bar

enter image description here

3. Needs to restart

enter image description here

How do I convert a String to an InputStream in Java?

I find that using Apache Commons IO makes my life much easier.

String source = "This is the source of my input stream";
InputStream in = org.apache.commons.io.IOUtils.toInputStream(source, "UTF-8");

You may find that the library also offer many other shortcuts to commonly done tasks that you may be able to use in your project.

Run exe file with parameters in a batch file

This should work:

start "" "c:\program files\php\php.exe" D:\mydocs\mp\index.php param1 param2

The start command interprets the first argument as a window title if it contains spaces. In this case, that means start considers your whole argument a title and sees no command. Passing "" (an empty title) as the first argument to start fixes the problem.

error running apache after xampp install

www.example.com:443:0 server certificate does NOT include an ID which matches the server name

I was getting this error when trying to start Apache, there is no error with Apache. It's an dependency error on windows 8 - probably the same for 7. Just right click and run as Admin :)

If you're still getting an error check your Antivirus/Firewall is not blocking Xampp or port 443.

How can a LEFT OUTER JOIN return more records than exist in the left table?

In response to your postscript, that depends on what you would like.

You are getting (possible) multiple rows for each row in your left table because there are multiple matches for the join condition. If you want your total results to have the same number of rows as there is in the left part of the query you need to make sure your join conditions cause a 1-to-1 match.

Alternatively, depending on what you actually want you can use aggregate functions (if for example you just want a string from the right part you could generate a column that is a comma delimited string of the right side results for that left row.

If you are only looking at 1 or 2 columns from the outer join you might consider using a scalar subquery since you will be guaranteed 1 result.

How to fix HTTP 404 on Github Pages?

On a private repo, when I first added and pushed my gh-pages branch to github, the settings for github pages automatically changed to indicate that the gh-pages branch would be published, but there no green or blue bar with the github.io url and no custom domain options.

It wasn't until I switched the source to master and quickly switched the source back to gh-pages that it actually updated with the green bar that contains the published url.

One DbContext per web request... why?

Another understated reason for not using a singleton DbContext, even in a single threaded single user application, is because of the identity map pattern it uses. It means that every time you retrieve data using query or by id, it will keep the retrieved entity instances in cache. The next time you retrieve the same entity, it will give you the cached instance of the entity, if available, with any modifications you have done in the same session. This is necessary so the SaveChanges method does not end up with multiple different entity instances of the same database record(s); otherwise, the context would have to somehow merge the data from all those entity instances.

The reason that is a problem is a singleton DbContext can become a time bomb that could eventually cache the whole database + the overhead of .NET objects in memory.

There are ways around this behavior by only using Linq queries with the .NoTracking() extension method. Also these days PCs have a lot of RAM. But usually that is not the desired behavior.

How do I run a Python program in the Command Prompt in Windows 7?

Python comes with a script that takes care of setting up the windows path file for you.

After installation, open command prompt

cmd

Go to the directory you installed Python in

cd C:\Python27

Run python and the win_add2path.py script in Tools\Scripts

python.exe Tools\Scripts\win_add2path.py

Now you can use python as a command anywhere.

How to replace � in a string

for detail

import java.io.UnsupportedEncodingException;

/**
 * File: BOM.java
 * 
 * check if the bom character is present in the given string print the string
 * after skipping the utf-8 bom characters print the string as utf-8 string on a
 * utf-8 console
 */

public class BOM
{
    private final static String BOM_STRING = "Hello World";
    private final static String ISO_ENCODING = "ISO-8859-1";
    private final static String UTF8_ENCODING = "UTF-8";
    private final static int UTF8_BOM_LENGTH = 3;

    public static void main(String[] args) throws UnsupportedEncodingException {
        final byte[] bytes = BOM_STRING.getBytes(ISO_ENCODING);
        if (isUTF8(bytes)) {
            printSkippedBomString(bytes);
            printUTF8String(bytes);
        }
    }

    private static void printSkippedBomString(final byte[] bytes) throws UnsupportedEncodingException {
        int length = bytes.length - UTF8_BOM_LENGTH;
        byte[] barray = new byte[length];
        System.arraycopy(bytes, UTF8_BOM_LENGTH, barray, 0, barray.length);
        System.out.println(new String(barray, ISO_ENCODING));
    }

    private static void printUTF8String(final byte[] bytes) throws UnsupportedEncodingException {
        System.out.println(new String(bytes, UTF8_ENCODING));
    }

    private static boolean isUTF8(byte[] bytes) {
        if ((bytes[0] & 0xFF) == 0xEF && 
            (bytes[1] & 0xFF) == 0xBB && 
            (bytes[2] & 0xFF) == 0xBF) {
            return true;
        }
        return false;
    }
}

How to get the squared symbol (²) to display in a string

No need to get too complicated. If all you need is ² then use the unicode representation.

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

(which is how I assume you got the ² to appear in your question. )

C# compiler error: "not all code paths return a value"

This usually happens to me if I misplace a return statement, for example: enter image description here

Adding a return statement, or in my case, moving it to correct scope will do the trick: enter image description here

How to check for a Null value in VB.NET

 If Short.TryParse(editTransactionRow.pay_id, New Short) Then editTransactionRow.pay_id.ToString()

Should try...catch go inside or outside a loop?

I'll put my $0.02 in. Sometimes you wind up needing to add a "finally" later on in your code (because who ever writes their code perfectly the first time?). In those cases, suddenly it makes more sense to have the try/catch outside the loop. For example:

try {
    for(int i = 0; i < max; i++) {
        String myString = ...;
        float myNum = Float.parseFloat(myString);
        dbConnection.update("MY_FLOATS","INDEX",i,"VALUE",myNum);
    }
} catch (NumberFormatException ex) {
    return null;
} finally {
    dbConnection.release();  // Always release DB connection, even if transaction fails.
}

Because if you get an error, or not, you only want to release your database connection (or pick your favorite type of other resource...) once.

Why is this error, 'Sequence contains no elements', happening?

If this is the offending line:

db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();

Then it's because there is no object in Responses for which the ResponseId == item.ResponseId, and you can't get the First() record if there are no matches.

Try this instead:

var response
  = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).FirstOrDefault();

if (response != null)
{
    // take some alternative action
}
else
    temp.Response = response;

The FirstOrDefault() extension returns an objects default value if no match is found. For most objects (other than primitive types), this is null.

ggplot2 legend to bottom and horizontal

Here is how to create the desired outcome:

library(reshape2); library(tidyverse)
melt(outer(1:4, 1:4), varnames = c("X1", "X2")) %>%
ggplot() + 
  geom_tile(aes(X1, X2, fill = value)) + 
  scale_fill_continuous(guide = guide_legend()) +
  theme(legend.position="bottom",
        legend.spacing.x = unit(0, 'cm'))+
  guides(fill = guide_legend(label.position = "bottom"))

Created on 2019-12-07 by the reprex package (v0.3.0)


Edit: no need for these imperfect options anymore, but I'm leaving them here for reference.

Two imperfect options that don't give you exactly what you were asking for, but pretty close (will at least put the colours together).

library(reshape2); library(tidyverse)
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
 theme(legend.position="bottom", legend.direction="vertical")

p1 + scale_fill_continuous(guide = "colorbar") + theme(legend.position="bottom")

Created on 2019-02-28 by the reprex package (v0.2.1)

How to copy and edit files in Android shell?

You can use cat > filename to use standart input to write to the file. At the end you have to put EOF CTRL+D.

Function overloading in Python: Missing

As unwind noted, keyword arguments with default values can go a long way.

I'll also state that in my opinion, it goes against the spirit of Python to worry a lot about what types are passed into methods. In Python, I think it's more accepted to use duck typing -- asking what an object can do, rather than what it is.

Thus, if your method may accept a string or a tuple, you might do something like this:

def print_names(names):
    """Takes a space-delimited string or an iterable"""
    try:
        for name in names.split(): # string case
            print name
    except AttributeError:
        for name in names:
            print name

Then you could do either of these:

print_names("Ryan Billy")
print_names(("Ryan", "Billy"))

Although an API like that sometimes indicates a design problem.

How to redirect the output of print to a TXT file

A slightly hackier way (that is different than the answers above, which are all valid) would be to just direct the output into a file via console.

So imagine you had main.py

if True:
    print "hello world"
else:
    print "goodbye world"

You can do

python main.py >> text.log

and then text.log will get all of the output.

This is handy if you already have a bunch of print statements and don't want to individually change them to print to a specific file. Just do it at the upper level and direct all prints to a file (only drawback is that you can only print to a single destination).

Runnable with a parameter?

I use the following class which implements the Runnable interface. With this class you can easily create new threads with arguments

public abstract class RunnableArg implements Runnable {

    Object[] m_args;

    public RunnableArg() {
    }

    public void run(Object... args) {
        setArgs(args);
        run();
    }

    public void setArgs(Object... args) {
        m_args = args;
    }

    public int getArgCount() {
        return m_args == null ? 0 : m_args.length;
    }

    public Object[] getArgs() {
        return m_args;
    }
}

List of zeros in python

$ python3
>>> from itertools import repeat
>>> list(repeat(0, 7))
[0, 0, 0, 0, 0, 0, 0]

Shorten string without cutting words in JavaScript

Here's yet another piece of code that truncates along punctuation marks (was looking for this and Google found this question here). Had to come up with a solution on my own, so this is what I hacked in 15 minutes. Finds all occurrences of . ! ? and truncates at any position of these that's < than len

function pos(str, char) {
    let pos = 0
    const ret = []
    while ( (pos = str.indexOf(char, pos + 1)) != -1) {
        ret.push(pos)
    }
    return ret
}

function truncate(str, len) {
    if (str.length < len)
        return str

    const allPos = [  ...pos(str, '!'), ...pos(str, '.'), ...pos(str, '?')].sort( (a,b) => a-b )
    if (allPos.length === 0) {
        return str.substr(0, len)
    }

    for(let i = 0; i < allPos.length; i++) {
        if (allPos[i] > len) {
            return str.substr(0, allPos[i-1] + 1)
        }
    }
}

module.exports = truncate

When to use If-else if-else over switch statements and vice versa

This depends very much on the specific case. Preferably, I think one should use the switch over the if-else if there are many nested if-elses.

The question is how much is many?

Yesterday I was asking myself the same question:

public enum ProgramType {
    NEW, OLD
}

if (progType == OLD) {
    // ...
} else if (progType == NEW) {
    // ...
}

if (progType == OLD) {
    // ...
} else {
    // ...
}

switch (progType) {
case OLD:
    // ...
    break;
case NEW:
    // ...
    break;
default:
    break;
}

In this case, the 1st if has an unnecessary second test. The 2nd feels a little bad because it hides the NEW.

I ended up choosing the switch because it just reads better.

Best way to check if a Data Table has a null value in it

I will do like....

(!DBNull.Value.Equals(dataSet.Tables[6].Rows[0]["_id"]))

how to fix stream_socket_enable_crypto(): SSL operation failed with code 1

Editor's note: disabling SSL verification has security implications. Without verification of the authenticity of SSL/HTTPS connections, a malicious attacker can impersonate a trusted endpoint such as Gmail, and you'll be vulnerable to a Man-in-the-Middle Attack.

Be sure you fully understand the security issues before using this as a solution.

You can add below code in /config/mail.php ( tested and worked on laravel 5.1, 5.2, 5.4 )

'stream' => [
   'ssl' => [
      'allow_self_signed' => true,
      'verify_peer' => false,
      'verify_peer_name' => false,
   ],
],

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Can't run Curl command inside my Docker Container

If you are using an Alpine based image, you have to

RUN
... \
apk add --no-cache curl \
curl ...
...

Height equal to dynamic width (CSS fluid layout)

Simple and neet : use vw units for a responsive height/width according to the viewport width.

vw : 1/100th of the width of the viewport. (Source MDN)

DEMO

HTML:

<div></div>

CSS for a 1:1 aspect ratio:

div{
    width:80vw;
    height:80vw; /* same as width */
}

Table to calculate height according to the desired aspect ratio and width of element.

   aspect ratio  |  multiply width by
    -----------------------------------
         1:1      |         1
         1:3      |         3
         4:3      |        0.75
        16:9      |       0.5625

This technique allows you to :

  • insert any content inside the element without using position:absolute;
  • no unecessary HTML markup (only one element)
  • adapt the elements aspect ratio according to the height of the viewport using vh units
  • you can make a responsive square or other aspect ratio that alway fits in viewport according to the height and width of the viewport (see this answer : Responsive square according to width and height of viewport or this demo)

These units are supported by IE9+ see canIuse for more info

post checkbox value

You should use

<input type="submit" value="submit" />

inside your form.

and add action into your form tag for example:

<form action="booking.php" method="post">

It's post your form into action which you choose.

From php you can get this value by

$_POST['booking-check'];

Pygame Drawing a Rectangle

import pygame, sys
from pygame.locals import *

def main():
    pygame.init()

    DISPLAY=pygame.display.set_mode((500,400),0,32)

    WHITE=(255,255,255)
    BLUE=(0,0,255)

    DISPLAY.fill(WHITE)

    pygame.draw.rect(DISPLAY,BLUE,(200,150,100,50))

    while True:
        for event in pygame.event.get():
            if event.type==QUIT:
                pygame.quit()
                sys.exit()
        pygame.display.update()

main()

This creates a simple window 500 pixels by 400 pixels that is white. Within the window will be a blue rectangle. You need to use the pygame.draw.rect to go about this, and you add the DISPLAY constant to add it to the screen, the variable blue to make it blue (blue is a tuple that values which equate to blue in the RGB values and it's coordinates.

Look up pygame.org for more info

Running PHP script from the command line

UPDATE:

After misunderstanding, I finally got what you are trying to do. You should check your server configuration files; are you using apache2 or some other server software?

Look for lines that start with LoadModule php... There probably are configuration files/directories named mods or something like that, start from there.

You could also check output from php -r 'phpinfo();' | grep php and compare lines to phpinfo(); from web server.

To run php interactively:

(so you can paste/write code in the console)

php -a

To make it parse file and output to console:

php -f file.php

Parse file and output to another file:

php -f file.php > results.html

Do you need something else?

To run only small part, one line or like, you can use:

php -r '$x = "Hello World"; echo "$x\n";'

If you are running linux then do man php at console.

if you need/want to run php through fpm, use cli fcgi

SCRIPT_NAME="file.php" SCRIP_FILENAME="file.php" REQUEST_METHOD="GET" cgi-fcgi -bind -connect "/var/run/php-fpm/php-fpm.sock"

where /var/run/php-fpm/php-fpm.sock is your php-fpm socket file.

What is the difference between SessionState and ViewState?

SessionState

  • Can be persisted in memory, which makes it a fast solution. Which means state cannot be shared in the Web Farm/Web Garden.
  • Can be persisted in a Database, useful for Web Farms / Web Gardens.
  • Is Cleared when the session dies - usually after 20min of inactivity.

ViewState

  • Is sent back and forth between the server and client, taking up bandwidth.
  • Has no expiration date.
  • Is useful in a Web Farm / Web Garden

Using ZXing to create an Android barcode scanning app

Using the provided IntentInegrator is better. It allows you to prompt your user to install the barcode scanner if they do not have it. It also allows you to customize the messages. The IntentIntegrator.REQUEST_CODE constant holds the value of the request code for the onActivityResult to check for in the above if block.

IntentIntegrator intentIntegrator = new IntentIntegrator(this); // where this is activity 
intentIntegrator.initiateScan(IntentIntegrator.ALL_CODE_TYPES); // or QR_CODE_TYPES if you need to scan QR

IntentIntegrator.java

How are ssl certificates verified?

Here is a very simplified explanation:

  1. Your web browser downloads the web server's certificate, which contains the public key of the web server. This certificate is signed with the private key of a trusted certificate authority.

  2. Your web browser comes installed with the public keys of all of the major certificate authorities. It uses this public key to verify that the web server's certificate was indeed signed by the trusted certificate authority.

  3. The certificate contains the domain name and/or ip address of the web server. Your web browser confirms with the certificate authority that the address listed in the certificate is the one to which it has an open connection.

  4. Your web browser generates a shared symmetric key which will be used to encrypt the HTTP traffic on this connection; this is much more efficient than using public/private key encryption for everything. Your browser encrypts the symmetric key with the public key of the web server then sends it back, thus ensuring that only the web server can decrypt it, since only the web server has its private key.

Note that the certificate authority (CA) is essential to preventing man-in-the-middle attacks. However, even an unsigned certificate will prevent someone from passively listening in on your encrypted traffic, since they have no way to gain access to your shared symmetric key.

How to use Simple Ajax Beginform in Asp.net MVC 4?

All This Work :)

Model

  public partial class ClientMessage
    {
        public int IdCon { get; set; } 
        public string Name { get; set; }
        public string Email { get; set; }  
    }

Controller

   public class TestAjaxBeginFormController : Controller{  

 projectNameEntities db = new projectNameEntities();

        public ActionResult Index(){  
            return View();
        }

        [HttpPost] 
        public ActionResult GetClientMessages(ClientMessage Vm) {
            var model = db.ClientMessages.Where(x => x.Name.Contains(Vm.Name));
            return PartialView("_PartialView", model);
        } 
}

View index.cshtml

@model  projectName.Models.ClientMessage 
@{ 
    Layout = null;
}

<script src="~/Scripts/jquery-1.9.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script>
    //\\\\\\\ JS  retrun message SucccessPost or FailPost
    function SuccessMessage() {
        alert("Succcess Post");
    }
    function FailMessage() {
        alert("Fail Post");
    } 
</script>

<h1>Page Index</h1> 

@using (Ajax.BeginForm("GetClientMessages", "TestAjaxBeginForm", null , new AjaxOptions
{
    HttpMethod = "POST",
    OnSuccess = "SuccessMessage",
    OnFailure = "FailMessage" ,
    UpdateTargetId = "resultTarget"  
}, new { id = "MyNewNameId" })) // set new Id name for  Form
{
    @Html.AntiForgeryToken()

    @Html.EditorFor(x => x.Name) 
     <input type="submit" value="Search" /> 

}


<div id="resultTarget">  </div>

View _PartialView.cshtml

@model  IEnumerable<projectName.Models.ClientMessage >
<table> 

@foreach (var item in Model) { 

    <tr> 
        <td>@Html.DisplayFor(modelItem => item.IdCon)</td>
        <td>@Html.DisplayFor(modelItem => item.Name)</td>
        <td>@Html.DisplayFor(modelItem => item.Email)</td>
    </tr>

}

</table>

Difference between acceptance test and functional test?

Functional Testing: Application of test data derived from the specified functional requirements without regard to the final program structure. Also known as black-box testing.

Acceptance Testing: Formal testing conducted to determine whether or not a system satisfies its acceptance criteria—enables an end user to determine whether or not to accept the system.

Eclipse comment/uncomment shortcut?

Single comment ctrl + / and also multiple line comment you can select multiple line and then ctrl + /. Then, to remove comment you can use ctrl + c for both single line and multiple line comment.