Input group - two inputs close to each other
I was not content with any of the answers on this page, so I fiddled with this myself for a bit. I came up with the following
_x000D_
_x000D_
angular.module('showcase', []).controller('Ctrl', function() {_x000D_
var vm = this;_x000D_
vm.focusParent = function(event) {_x000D_
angular.element(event.target).parent().addClass('focus');_x000D_
};_x000D_
_x000D_
vm.blurParent = function(event) {_x000D_
angular.element(event.target).parent().removeClass('focus');_x000D_
};_x000D_
});
_x000D_
.input-merge .col-xs-2,_x000D_
.input-merge .col-xs-4,_x000D_
.input-merge .col-xs-6 {_x000D_
padding-left: 0;_x000D_
padding-right: 0;_x000D_
}_x000D_
.input-merge div:first-child .form-control {_x000D_
border-top-right-radius: 0;_x000D_
border-bottom-right-radius: 0;_x000D_
}_x000D_
.input-merge div:last-child .form-control {_x000D_
border-top-left-radius: 0;_x000D_
border-bottom-left-radius: 0;_x000D_
}_x000D_
.input-merge div:not(:first-child) {_x000D_
margin-left: -1px;_x000D_
}_x000D_
.input-merge div:not(:first-child):not(:last-child) .form-control {_x000D_
border-radius: 0;_x000D_
}_x000D_
.focus {_x000D_
z-index: 2;_x000D_
}
_x000D_
<html ng-app="showcase">_x000D_
_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />_x000D_
</head>_x000D_
_x000D_
<body class="container">_x000D_
<label class="control-label">Person</label>_x000D_
<div class="input-merge" ng-controller="Ctrl as showCase">_x000D_
<div class="col-xs-4">_x000D_
<input class="form-control input-sm" name="initials" type="text" id="initials"_x000D_
ng-focus="showCase.focusParent($event)" ng-blur="showCase.blurParent($event)"_x000D_
ng-model="person.initials" placeholder="Initials" />_x000D_
</div>_x000D_
_x000D_
<div class="col-xs-2">_x000D_
<input class="form-control input-sm" name="prefixes" type="text" id="prefixes"_x000D_
ng-focus="showCase.focusParent($event)" ng-blur="showCase.blurParent($event)"_x000D_
ng-model="persoon.prefixes" placeholder="Prefixes" />_x000D_
</div>_x000D_
_x000D_
<div class="col-xs-6">_x000D_
<input class="form-control input-sm" name="surname" type="text" id="surname"_x000D_
ng-focus="showCase.focusParent($event)" ng-blur="showCase.blurParent($event)"_x000D_
ng-model="persoon.surname" placeholder="Surname" />_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_
With this it is possible to set the width of the individual inputs to your liking. Also a minor issue with the above snippets was that the input looks incomplete when focussed or when it is not valid. I fixed this with some angular code, but you can just as easily do this with jQuery or native javascript or whatever.
The code adds the class .focus to the containing div's, so it can get a higher z-index then the others when the input is focussed.
Use URI builder in Android or create URL with variables
There is another way of using Uri
and we can achieve the same goal
http://api.example.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7
To build the Uri you can use this:
final String FORECAST_BASE_URL =
"http://api.example.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
You can declare all this the above way or even inside the Uri.parse()
and appendQueryParameter()
Uri builtUri = Uri.parse(FORECAST_BASE_URL)
.buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, "json")
.appendQueryParameter(UNITS_PARAM, "metric")
.appendQueryParameter(DAYS_PARAM, Integer.toString(7))
.build();
At last
URL url = new URL(builtUri.toString());
Interface extends another interface but implements its methods
An interface defines behavior. For example, a Vehicle
interface might define the move()
method.
A Car is a Vehicle, but has additional behavior. For example, the Car
interface might define the startEngine()
method. Since a Car is also a Vehicle, the Car
interface extends the Vehicle
interface, and thus defines two methods: move()
(inherited) and startEngine()
.
The Car interface doesn't have any method implementation. If you create a class (Volkswagen) that implements Car, it will have to provide implementations for all the methods of its interface: move()
and startEngine()
.
An interface may not implement any other interface. It can only extend it.
Android: How to stretch an image to the screen width while maintaining aspect ratio?
You can use my StretchableImageView preserving the aspect ratio (by width or by height) depending on width and height of drawable:
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
public class StretchableImageView extends ImageView{
public StretchableImageView(Context context) {
super(context);
}
public StretchableImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public StretchableImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if(getDrawable()!=null){
if(getDrawable().getIntrinsicWidth()>=getDrawable().getIntrinsicHeight()){
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width * getDrawable().getIntrinsicHeight()
/ getDrawable().getIntrinsicWidth();
setMeasuredDimension(width, height);
}else{
int height = MeasureSpec.getSize(heightMeasureSpec);
int width = height * getDrawable().getIntrinsicWidth()
/ getDrawable().getIntrinsicHeight();
setMeasuredDimension(width, height);
}
}
}
}
Print empty line?
This is are other ways of printing empty lines in python
# using \n after the string creates an empty line after this string is passed to the the terminal.
print("We need to put about", average_passengers_per_car, "in each car. \n")
print("\n") #prints 2 empty lines
print() #prints 1 empty line
Evenly distributing n points on a sphere
@robert king It's a really nice solution but has some sloppy bugs in it. I know it helped me a lot though, so never mind the sloppiness. :)
Here is a cleaned up version....
from math import pi, asin, sin, degrees
halfpi, twopi = .5 * pi, 2 * pi
sphere_area = lambda R=1.0: 4 * pi * R ** 2
lat_dist = lambda lat, R=1.0: R*(1-sin(lat))
#A = 2*pi*R^2(1-sin(lat))
def sphere_latarea(lat, R=1.0):
if -halfpi > lat or lat > halfpi:
raise ValueError("lat must be between -halfpi and halfpi")
return 2 * pi * R ** 2 * (1-sin(lat))
sphere_lonarea = lambda lon, R=1.0: \
4 * pi * R ** 2 * lon / twopi
#A = 2*pi*R^2 |sin(lat1)-sin(lat2)| |lon1-lon2|/360
# = (pi/180)R^2 |sin(lat1)-sin(lat2)| |lon1-lon2|
sphere_rectarea = lambda lat0, lat1, lon0, lon1, R=1.0: \
(sphere_latarea(lat0, R)-sphere_latarea(lat1, R)) * (lon1-lon0) / twopi
def test_sphere(n_lats=10, n_lons=19, radius=540.0):
total_area = 0.0
for i_lons in range(n_lons):
lon0 = twopi * float(i_lons) / n_lons
lon1 = twopi * float(i_lons+1) / n_lons
for i_lats in range(n_lats):
lat0 = asin(2 * float(i_lats) / n_lats - 1)
lat1 = asin(2 * float(i_lats+1)/n_lats - 1)
area = sphere_rectarea(lat0, lat1, lon0, lon1, radius)
print("{:} {:}: {:9.4f} to {:9.4f}, {:9.4f} to {:9.4f} => area {:10.4f}"
.format(i_lats, i_lons
, degrees(lat0), degrees(lat1)
, degrees(lon0), degrees(lon1)
, area))
total_area += area
print("total_area = {:10.4f} (difference of {:10.4f})"
.format(total_area, abs(total_area) - sphere_area(radius)))
test_sphere()
SFTP Libraries for .NET
For comprehensive SFTP support in .NET try edtFTPnet/PRO. It's been around a long time with support for many different SFTP servers.
We also sell an SFTP server for Windows, CompleteFTP, which is an inexpensive way to get support for SFTP on your Windows machine. Also has FTP and FTPS.
How to switch between frames in Selenium WebDriver using Java
First you have to locate the frame id and define it in a WebElement
For ex:- WebElement fr = driver.findElementById("id");
Then switch to the frame using this code:- driver.switchTo().frame("Frame_ID");
An example script:-
WebElement fr = driver.findElementById("theIframe");
driver.switchTo().frame(fr);
Then to move out of frame use:- driver.switchTo().defaultContent();
How to create PDFs in an Android app?
A bit late and I have not yet tested it yet myself but another library that is under the BSD license is Android PDF Writer.
Update I have tried the library myself. Works ok with simple pdf generations (it provide methods for adding text, lines, rectangles, bitmaps, fonts). The only problem is that the generated PDF is stored in a String in memory, this may cause memory issues in large documents.
how to fix groovy.lang.MissingMethodException: No signature of method:
In my case it was simply that I had a variable named the same as a function.
Example:
def cleanCache = functionReturningABoolean()
if( cleanCache ){
echo "Clean cache option is true, do not uninstall previous features / urls"
uninstallCmd = ""
// and we call the cleanCache method
cleanCache(userId, serverName)
}
...
and later in my code I have the function:
def cleanCache(user, server){
//some operations to the server
}
Apparently the Groovy language does not support this (but other languages like Java does).
I just renamed my function to executeCleanCache
and it works perfectly (or you can also rename your variable whatever option you prefer).
Does static constexpr variable inside a function make sense?
The short answer is that not only is static
useful, it is pretty well always going to be desired.
First, note that static
and constexpr
are completely independent of each other. static
defines the object's lifetime during execution; constexpr
specifies that the object should be available during compilation. Compilation and execution are disjoint and discontiguous, both in time and space. So once the program is compiled, constexpr
is no longer relevant.
Every variable declared constexpr
is implicitly const
but const
and static
are almost orthogonal (except for the interaction with static const
integers.)
The C++
object model (§1.9) requires that all objects other than bit-fields occupy at least one byte of memory and have addresses; furthermore all such objects observable in a program at a given moment must have distinct addresses (paragraph 6). This does not quite require the compiler to create a new array on the stack for every invocation of a function with a local non-static const array, because the compiler could take refuge in the as-if
principle provided it can prove that no other such object can be observed.
That's not going to be easy to prove, unfortunately, unless the function is trivial (for example, it does not call any other function whose body is not visible within the translation unit) because arrays, more or less by definition, are addresses. So in most cases, the non-static const(expr)
array will have to be recreated on the stack at every invocation, which defeats the point of being able to compute it at compile time.
On the other hand, a local static const
object is shared by all observers, and furthermore may be initialized even if the function it is defined in is never called. So none of the above applies, and a compiler is free not only to generate only a single instance of it; it is free to generate a single instance of it in read-only storage.
So you should definitely use static constexpr
in your example.
However, there is one case where you wouldn't want to use static constexpr
. Unless a constexpr
declared object is either ODR-used or declared static
, the compiler is free to not include it at all. That's pretty useful, because it allows the use of compile-time temporary constexpr
arrays without polluting the compiled program with unnecessary bytes. In that case, you would clearly not want to use static
, since static
is likely to force the object to exist at runtime.
Apply CSS rules if browser is IE
I prefer using a separate file for ie rules, as described earlier.
<!--[if IE]><link rel="stylesheet" type="text/css" href="ie-style.css"/><![endif]-->
And inside it you can set up rules for different versions of ie using this:
.abc {...} /* ALL MSIE */
*html *.abc {...} /* MSIE 6 */
*:first-child+html .abc {...} /* MSIE 7 */
What charset does Microsoft Excel use when saving files?
Russian Edition
offers CSV
, CSV (Macintosh)
and CSV (DOS)
.
When saving in plain CSV
, it uses windows-1251
.
I just tried to save French word Résumé
along with the Russian text, it saved it in HEX
like 52 3F 73 75 6D 3F
, 3F
being the ASCII
code for question mark
.
When I opened the CSV
file, the word, of course, became unreadable (R?sum?
)
Change url query string value using jQuery
purls $.params()
used without a parameter will give you a key-value object of the parameters.
jQuerys $.param()
will build a querystring from the supplied object/array.
var params = parsedUrl.param();
delete params["page"];
var newUrl = "?page=" + $(this).val() + "&" + $.param(params);
Update
I've no idea why I used delete
here...
var params = parsedUrl.param();
params["page"] = $(this).val();
var newUrl = "?" + $.param(params);
Error 0x80005000 and DirectoryServices
Just had that problem in a production system in the company where I live... A webpage that made a LDAP bind stopped working after an IP changed.
The solution...
... I installed Basic Authentication to perform the troubleshooting indicated here: https://support.microsoft.com/en-us/kb/329986
And after that, things just started to work. Even after I re-disabled Basic Authentication in the page I was testing, all other pages started working again with Windows Authentication.
Regards,
Acácio
How can I get the client's IP address in ASP.NET MVC?
The simple answer is to use the HttpRequest.UserHostAddress property.
Example: From within a Controller:
using System;
using System.Web.Mvc;
namespace Mvc.Controllers
{
public class HomeController : ClientController
{
public ActionResult Index()
{
string ip = Request.UserHostAddress;
...
}
}
}
Example: From within a helper class:
using System.Web;
namespace Mvc.Helpers
{
public static class HelperClass
{
public static string GetIPHelper()
{
string ip = HttpContext.Current.Request.UserHostAddress;
..
}
}
}
BUT, if the request has been passed on by one, or more, proxy servers then the IP address returned by HttpRequest.UserHostAddress property will be the IP address of the last proxy server that relayed the request.
Proxy servers MAY use the de facto standard of placing the client's IP address in the X-Forwarded-For HTTP header. Aside from there is no guarantee that a request has a X-Forwarded-For header, there is also no guarantee that the X-Forwarded-For hasn't been SPOOFED.
Original Answer
Request.UserHostAddress
The above code provides the Client's IP address without resorting to looking up a collection. The Request property is available within Controllers (or Views). Therefore instead of passing a Page class to your function you can pass a Request object to get the same result:
public static string getIPAddress(HttpRequestBase request)
{
string szRemoteAddr = request.UserHostAddress;
string szXForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];
string szIP = "";
if (szXForwardedFor == null)
{
szIP = szRemoteAddr;
}
else
{
szIP = szXForwardedFor;
if (szIP.IndexOf(",") > 0)
{
string [] arIPs = szIP.Split(',');
foreach (string item in arIPs)
{
if (!isPrivateIP(item))
{
return item;
}
}
}
}
return szIP;
}
How can I read the client's machine/computer name from the browser?
<html>
<body onload = "load()">
<script>
function load(){
try {
var ax = new ActiveXObject("WScript.Network");
alert('User: ' + ax.UserName );
alert('Computer: ' + ax.ComputerName);
}
catch (e) {
document.write('Permission to access computer name is denied' + '<br />');
}
}
</script>
</body>
</html>
How can I expose more than 1 port with Docker?
if you use docker-compose.yml
file:
services:
varnish:
ports:
- 80
- 6081
You can also specify the host/network port as HOST/NETWORK_PORT:CONTAINER_PORT
varnish:
ports:
- 81:80
- 6081:6081
Read lines from a text file but skip the first two lines
That whole Open <file path> For Input As <some number>
thing is so 1990s. It's also slow and very error-prone.
In your VBA editor, Select References from the Tools menu and look for "Microsoft Scripting Runtime" (scrrun.dll) which should be available on pretty much any XP or Vista machine. It it's there, select it. Now you have access to a (to me at least) rather more robust solution:
With New Scripting.FileSystemObject
With .OpenTextFile(sFilename, ForReading)
If Not .AtEndOfStream Then .SkipLine
If Not .AtEndOfStream Then .SkipLine
Do Until .AtEndOfStream
DoSomethingImportantTo .ReadLine
Loop
End With
End With
Bootstrap 3: Using img-circle, how to get circle from non-square image?
use this in css
.logo-center{
border:inherit 8px #000000;
-moz-border-radius-topleft: 75px;
-moz-border-radius-topright:75px;
-moz-border-radius-bottomleft:75px;
-moz-border-radius-bottomright:75px;
-webkit-border-top-left-radius:75px;
-webkit-border-top-right-radius:75px;
-webkit-border-bottom-left-radius:75px;
-webkit-border-bottom-right-radius:75px;
border-top-left-radius:75px;
border-top-right-radius:75px;
border-bottom-left-radius:75px;
border-bottom-right-radius:75px;
}
<img class="logo-center" src="NBC-Logo.png" height="60" width="60">
CSS list-style-image size
Almost like cheating, I just went into an image editor and resized the image by half. Works like a charm for me.
How can I express that two values are not equal to eachother?
If the class implements comparable, you could also do
int compRes = a.compareTo(b);
if(compRes < 0 || compRes > 0)
System.out.println("not equal");
else
System.out.println("equal);
doesn't use a !
, though not particularly useful, or readable....
What is the best (idiomatic) way to check the type of a Python variable?
isinstance is preferrable over type because it also evaluates as True when you compare an object instance with it's superclass, which basically means you won't ever have to special-case your old code for using it with dict or str subclasses.
For example:
>>> class a_dict(dict):
... pass
...
>>> type(a_dict()) == type(dict())
False
>>> isinstance(a_dict(), dict)
True
>>>
Of course, there might be situations where you wouldn't want this behavior, but those are –hopefully– a lot less common than situations where you do want it.
get current url in twig template?
{{ path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) }}
If you want to read it into a view variable:
{% set currentPath = path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) %}
The app
global view variable contains all sorts of useful shortcuts, such as app.session
and app.security.token.user
, that reference the services you might use in a controller.
What is the recommended way to delete a large number of items from DynamoDB?
Thought about using the test to pass in the vars? Something like:
Test input would be something like:
{
"TABLE_NAME": "MyDevTable",
"PARTITION_KEY": "REGION",
"SORT_KEY": "COUNTRY"
}
Adjusted your code to accept the inputs:
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: '2012-08-10' });
exports.handler = async (event) => {
const TABLE_NAME = event.TABLE_NAME;
const PARTITION_KEY = event.PARTITION_KEY;
const SORT_KEY = event.SORT_KEY;
let params = {
TableName: TABLE_NAME,
};
console.log(`keys: ${PARTITION_KEY} ${SORT_KEY}`);
let items = [];
let data = await docClient.scan(params).promise();
items = [...items, ...data.Items];
while (typeof data.LastEvaluatedKey != 'undefined') {
params.ExclusiveStartKey = data.LastEvaluatedKey;
data = await docClient.scan(params).promise();
items = [...items, ...data.Items];
}
let leftItems = items.length;
let group = [];
let groupNumber = 0;
console.log('Total items to be deleted', leftItems);
for (const i of items) {
// console.log(`item: ${i[PARTITION_KEY] } ${i[SORT_KEY]}`);
const deleteReq = {DeleteRequest: {Key: {},},};
deleteReq.DeleteRequest.Key[PARTITION_KEY] = i[PARTITION_KEY];
deleteReq.DeleteRequest.Key[SORT_KEY] = i[SORT_KEY];
// console.log(`DeleteRequest: ${JSON.stringify(deleteReq)}`);
group.push(deleteReq);
leftItems--;
if (group.length === 25 || leftItems < 1) {
groupNumber++;
console.log(`Batch ${groupNumber} to be deleted.`);
const params = {
RequestItems: {
[TABLE_NAME]: group,
},
};
await docClient.batchWrite(params).promise();
console.log(
`Batch ${groupNumber} processed. Left items: ${leftItems}`
);
// reset
group = [];
}
}
const response = {
statusCode: 200,
// Uncomment below to enable CORS requests
headers: {
"Access-Control-Allow-Origin": "*"
},
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
Mockito, JUnit and Spring
Here's my short summary.
If you want to write a unit test, don't use a Spring applicationContext because you don't want any real dependencies injected in the class you are unit testing. Instead use mocks, either with the @RunWith(MockitoJUnitRunner.class)
annotation on top of the class, or with MockitoAnnotations.initMocks(this)
in the @Before method.
If you want to write an integration test, use:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("yourTestApplicationContext.xml")
To set up your application context with an in-memory database for example.
Normally you don't use mocks in integration tests, but you could do it by using the MockitoAnnotations.initMocks(this)
approach described above.
Why don't self-closing script elements work?
To add to what Brad and squadette have said, the self-closing XML syntax <script />
actually is correct XML, but for it to work in practice, your web server also needs to send your documents as properly formed XML with an XML mimetype like application/xhtml+xml
in the HTTP Content-Type header (and not as text/html
).
However, sending an XML mimetype will cause your pages not to be parsed by IE7, which only likes text/html
.
From w3:
In summary, 'application/xhtml+xml'
SHOULD be used for XHTML Family
documents, and the use of 'text/html'
SHOULD be limited to HTML-compatible
XHTML 1.0 documents. 'application/xml'
and 'text/xml' MAY also be used, but
whenever appropriate,
'application/xhtml+xml' SHOULD be used
rather than those generic XML media
types.
I puzzled over this a few months ago, and the only workable (compatible with FF3+ and IE7) solution was to use the old <script></script>
syntax with text/html
(HTML syntax + HTML mimetype).
If your server sends the text/html
type in its HTTP headers, even with otherwise properly formed XHTML documents, FF3+ will use its HTML rendering mode which means that <script />
will not work (this is a change, Firefox was previously less strict).
This will happen regardless of any fiddling with http-equiv
meta elements, the XML prolog or doctype inside your document -- Firefox branches once it gets the text/html
header, that determines whether the HTML or XML parser looks inside the document, and the HTML parser does not understand <script />
.
Get value from SimpleXMLElement Object
you can convert array with this function
function xml2array($xml){
$arr = array();
foreach ($xml->children() as $r)
{
$t = array();
if(count($r->children()) == 0)
{
$arr[$r->getName()] = strval($r);
}
else
{
$arr[$r->getName()][] = xml2array($r);
}
}
return $arr;
}
Handling exceptions from Java ExecutorService tasks
This is similar to mmm's solution, but a bit more understandable. Have your tasks extend an abstract class that wraps the run() method.
public abstract Task implements Runnable {
public abstract void execute();
public void run() {
try {
execute();
} catch (Throwable t) {
// handle it
}
}
}
public MySampleTask extends Task {
public void execute() {
// heavy, error-prone code here
}
}
2D array values C++
The proper way to initialize a multidimensional array in C or C++ is
int arr[2][5] = {{1,8,12,20,25}, {5,9,13,24,26}};
You can use this same trick to initialize even higher-dimensional arrays if you want.
Also, be careful in your initial code - you were trying to use 1-indexed offsets into the array to initialize it. This didn't compile, but if it did it would cause problems because C arrays are 0-indexed!
Resize an Array while keeping current elements in Java?
You can't resize an array, but you can redefine it keeping old values or use a java.util.List
Here follows two solutions but catch the performance differences running the code below
Java Lists are 450 times faster but 20 times heavier in memory!
testAddByteToArray1 nanoAvg:970355051 memAvg:100000
testAddByteToList1 nanoAvg:1923106 memAvg:2026856
testAddByteToArray1 nanoAvg:919582271 memAvg:100000
testAddByteToList1 nanoAvg:1922660 memAvg:2026856
testAddByteToArray1 nanoAvg:917727475 memAvg:100000
testAddByteToList1 nanoAvg:1904896 memAvg:2026856
testAddByteToArray1 nanoAvg:918483397 memAvg:100000
testAddByteToList1 nanoAvg:1907243 memAvg:2026856
import java.util.ArrayList;
import java.util.List;
public class Test {
public static byte[] byteArray = new byte[0];
public static List<Byte> byteList = new ArrayList<>();
public static List<Double> nanoAvg = new ArrayList<>();
public static List<Double> memAvg = new ArrayList<>();
public static void addByteToArray1() {
// >>> SOLUTION ONE <<<
byte[] a = new byte[byteArray.length + 1];
System.arraycopy(byteArray, 0, a, 0, byteArray.length);
byteArray = a;
//byteArray = Arrays.copyOf(byteArray, byteArray.length + 1); // the same as System.arraycopy()
}
public static void addByteToList1() {
// >>> SOLUTION TWO <<<
byteList.add(new Byte((byte) 0));
}
public static void testAddByteToList1() throws InterruptedException {
System.gc();
long m1 = getMemory();
long n1 = System.nanoTime();
for (int i = 0; i < 100000; i++) {
addByteToList1();
}
long n2 = System.nanoTime();
System.gc();
long m2 = getMemory();
byteList = new ArrayList<>();
nanoAvg.add(new Double(n2 - n1));
memAvg.add(new Double(m2 - m1));
}
public static void testAddByteToArray1() throws InterruptedException {
System.gc();
long m1 = getMemory();
long n1 = System.nanoTime();
for (int i = 0; i < 100000; i++) {
addByteToArray1();
}
long n2 = System.nanoTime();
System.gc();
long m2 = getMemory();
byteArray = new byte[0];
nanoAvg.add(new Double(n2 - n1));
memAvg.add(new Double(m2 - m1));
}
public static void resetMem() {
nanoAvg = new ArrayList<>();
memAvg = new ArrayList<>();
}
public static Double getAvg(List<Double> dl) {
double max = Collections.max(dl);
double min = Collections.min(dl);
double avg = 0;
boolean found = false;
for (Double aDouble : dl) {
if (aDouble < max && aDouble > min) {
if (avg == 0) {
avg = aDouble;
} else {
avg = (avg + aDouble) / 2d;
}
found = true;
}
}
if (!found) {
return getPopularElement(dl);
}
return avg;
}
public static double getPopularElement(List<Double> a) {
int count = 1, tempCount;
double popular = a.get(0);
double temp = 0;
for (int i = 0; i < (a.size() - 1); i++) {
temp = a.get(i);
tempCount = 0;
for (int j = 1; j < a.size(); j++) {
if (temp == a.get(j))
tempCount++;
}
if (tempCount > count) {
popular = temp;
count = tempCount;
}
}
return popular;
}
public static void testCompare() throws InterruptedException {
for (int j = 0; j < 4; j++) {
for (int i = 0; i < 20; i++) {
testAddByteToArray1();
}
System.out.println("testAddByteToArray1\tnanoAvg:" + getAvg(nanoAvg).longValue() + "\tmemAvg:" + getAvg(memAvg).longValue());
resetMem();
for (int i = 0; i < 20; i++) {
testAddByteToList1();
}
System.out.println("testAddByteToList1\tnanoAvg:" + getAvg(nanoAvg).longValue() + "\t\tmemAvg:" + getAvg(memAvg).longValue());
resetMem();
}
}
private static long getMemory() {
Runtime runtime = Runtime.getRuntime();
return runtime.totalMemory() - runtime.freeMemory();
}
public static void main(String[] args) throws InterruptedException {
testCompare();
}
}
What is a Question Mark "?" and Colon ":" Operator Used for?
They are called the ternary operator since they are the only one in Java.
The difference to the if...else construct is, that they return something, and this something can be anything:
int k = a > b ? 7 : 8;
String s = (foobar.isEmpty ()) ? "empty" : foobar.toString ();
How can I read numeric strings in Excel cells as string (not numbers)?
public class Excellib {
public String getExceldata(String sheetname,int rownum,int cellnum, boolean isString) {
String retVal=null;
try {
FileInputStream fis=new FileInputStream("E:\\Sample-Automation-Workspace\\SampleTestDataDriven\\Registration.xlsx");
Workbook wb=WorkbookFactory.create(fis);
Sheet s=wb.getSheet(sheetname);
Row r=s.getRow(rownum);
Cell c=r.getCell(cellnum);
if(c.getCellType() == Cell.CELL_TYPE_STRING)
retVal=c.getStringCellValue();
else {
retVal = String.valueOf(c.getNumericCellValue());
}
I Tried This and It worked For me
Get top first record from duplicate records having no unique identity
Find all products that has been ordered 1 or more times... (kind of duplicate records)
SELECT DISTINCT * from [order_items] where productid in
(SELECT productid
FROM [order_items]
group by productid
having COUNT(*)>0)
order by productid
To select the last inserted of those...
SELECT DISTINCT productid, MAX(id) OVER (PARTITION BY productid) AS LastRowId from [order_items] where productid in
(SELECT productid
FROM [order_items]
group by productid
having COUNT(*)>0)
order by productid
.bashrc at ssh login
.bashrc
is not sourced when you log in using SSH. You need to source it in your .bash_profile
like this:
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
How to check model string property for null in a razor view
Try this first, you may be passing a Null Model:
@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
<label for="Image">Change picture</label>
}
else
{
<label for="Image">Add picture</label>
}
Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.
<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>
Functional, Declarative, and Imperative Programming
imperative and declarative describe two opposing styles of programming. imperative is the traditional "step by step recipe" approach while declarative is more "this is what i want, now you work out how to do it".
these two approaches occur throughout programming - even with the same language and the same program. generally the declarative approach is considered preferable, because it frees the programmer from having to specify so many details, while also having less chance for bugs (if you describe the result you want, and some well-tested automatic process can work backwards from that to define the steps then you might hope that things are more reliable than having to specify each step by hand).
on the other hand, an imperative approach gives you more low level control - it's the "micromanager approach" to programming. and that can allow the programmer to exploit knowledge about the problem to give a more efficient answer. so it's not unusual for some parts of a program to be written in a more declarative style, but for the speed-critical parts to be more imperative.
as you might imagine, the language you use to write a program affects how declarative you can be - a language that has built-in "smarts" for working out what to do given a description of the result is going to allow a much more declarative approach than one where the programmer needs to first add that kind of intelligence with imperative code before being able to build a more declarative layer on top. so, for example, a language like prolog is considered very declarative because it has, built-in, a process that searches for answers.
so far, you'll notice that i haven't mentioned functional programming. that's because it's a term whose meaning isn't immediately related to the other two. at its most simple, functional programming means that you use functions. in particular, that you use a language that supports functions as "first class values" - that means that not only can you write functions, but you can write functions that write functions (that write functions that...), and pass functions to functions. in short - that functions are as flexible and common as things like strings and numbers.
it might seem odd, then, that functional, imperative and declarative are often mentioned together. the reason for this is a consequence of taking the idea of functional programming "to the extreme". a function, in it's purest sense, is something from maths - a kind of "black box" that takes some input and always gives the same output. and that kind of behaviour doesn't require storing changing variables. so if you design a programming language whose aim is to implement a very pure, mathematically influenced idea of functional programming, you end up rejecting, largely, the idea of values that can change (in a certain, limited, technical sense).
and if you do that - if you limit how variables can change - then almost by accident you end up forcing the programmer to write programs that are more declarative, because a large part of imperative programming is describing how variables change, and you can no longer do that! so it turns out that functional programming - particularly, programming in a functional language - tends to give more declarative code.
to summarise, then:
imperative and declarative are two opposing styles of programming (the same names are used for programming languages that encourage those styles)
functional programming is a style of programming where functions become very important and, as a consequence, changing values become less important. the limited ability to specify changes in values forces a more declarative style.
so "functional programming" is often described as "declarative".
How to add parameters to an external data query in Excel which can't be displayed graphically?
Excel's interface for SQL Server queries will not let you have a custom parameters. A way around this is to create a generic Microsoft Query, then add parameters, then paste your parametorized query in the connection's properties. Here are the detailed steps for Excel 2010:
- Open Excel
- Goto Data tab
- From the From Other Sources button choose From Microsoft Query
- The "Choose Data Source" window will appear. Choose a datasource and click OK.
- The Query Qizard
- Choose Column: window will appear. The goal is to create a generic query. I recommend choosing one column from a small table.
- Filter Data: Just click Next
- Sort Order: Just click Next
- Finish: Just click Finish.
- The "Import Data" window will appear:
- Click the Properties... button.
- Choose the Definition tab
- In the "Command text:" section add a WHERE clause that includes Excel parameters. It's important to add all the parameters that you want now. For example, if I want two parameters I could add this:
WHERE 1 = ? and 2 = ?
- Click OK to get back to the "Import Data" window
- Choose PivotTable Report
- Click OK
- You will be prompted to enter the parameters value for each parameter.
- Once you have enter the parameters you will be at your pivot table
- Go batck to the Data tab and click the connections Properties button
- Click the Definition tab
- In the "Command text:" section, Paste in the real SQL Query that you want with the same number of parameters that you defined earlier.
- Click the Parameters... button
- enter the Prompt values for each parameter
- Click OK
- Click OK to close the properties window
- Congratulations, you now have parameters.
How to call one shell script from another shell script?
You can use /bin/sh
to call or execute another script (via your actual script):
# cat showdate.sh
#!/bin/bash
echo "Date is: `date`"
# cat mainscript.sh
#!/bin/bash
echo "You are login as: `whoami`"
echo "`/bin/sh ./showdate.sh`" # exact path for the script file
The output would be:
# ./mainscript.sh
You are login as: root
Date is: Thu Oct 17 02:56:36 EDT 2013
Adding close button in div to close the box
You can use this jsFiddle
And HTML:
<div id="previewBox">
<button id="closeButton">Close</button>
<a class="fragment" href="google.com">
<div>
<img src ="http://placehold.it/116x116" alt="some description"/>
<h3>the title will go here</h3>
<h4> www.myurlwill.com </h4>
<p class="text">
this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etcthis is a short description yada yada peanuts etc
</p>
</div>
</a>
</div>
With JS (jquery required):
$(document).ready(function() {
$('#closeButton').on('click', function(e) {
$('#previewBox').remove();
});
});
Why is there no Char.Empty like String.Empty?
A char is a value type, so its value cannot be null. (Unless it is wrapped in a Nullable container).
Since it can't be null, in contains some numeric code and each code is mapped to some character.
Recommended SQL database design for tags or tagging
Use a single formatted text column[1] for storing the tags and use a capable full text search engine to index this. Else you will run into scaling problems when trying to implement boolean queries.
If you need details about the tags you have, you can either keep track of it in a incrementally maintained table or run a batch job to extract the information.
[1] Some RDBMS even provide a native array type which might be even better suited for storage by not needing a parsing step, but might cause problems with the full text search.
Creating a UITableView Programmatically
- (void)viewDidLoad {
[super viewDidLoad];
arr=[[NSArray alloc]initWithObjects:@"ABC",@"XYZ", nil];
tableview = [[UITableView alloc]initWithFrame:tableFrame style:UITableViewStylePlain];
tableview.delegate = self;
tableview.dataSource = self;
[self.view addSubview:tableview];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];
if(cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyCell"];
}
cell.textLabel.text=[arr objectAtIndex:indexPath.row];
return cell;
}
How to connect to MongoDB in Windows?
Follow
Create default db folder.
c:\data\db
and also log folder
c:\data\log\mongo.log
or use following commands in command-prompt
mkdir c:\data\log
mkdir c:\data\db
Create config file in bin folder of mongo (or you may in save your desired destination).
Add following in text file named "mongod" and save it as
mongod.cfg
dbpath=c:\data\db
logpath=c:\data\log\mongo.log
or use following commands in command-prompt
echo dbpath=c:\data\db>> "mongod.cfg"
echo logpath=c:\data\log\mongo.log>> "mongod.cfg"
Now open command-prompt (administrator) and run the following command to start mongo server
mongod
Open another command-prompt (don't close 1st prompt) and run client command:
mongo
Hope this will help or you have done this already.
Git: How to rebase to a specific commit?
A simpler solution is git rebase <SHA1 of B> topic
. This works irrespective of where your HEAD
is.
We can confirm this behaviour from git rebase doc
<upstream>
Upstream branch to compare against. May be any valid
commit, not just an existing branch name. Defaults to the configured
upstream for the current branch.
You might be thinking what will happen if I mention SHA1 of
topic
too in the above command ?
git rebase <SHA1 of B> <SHA1 of topic>
This will also work but rebase then won't make Topic
point to new branch so created and HEAD
will be in detached state. So from here you have to manually delete old Topic
and create a new branch reference on new branch created by rebase.
Website screenshots
Since PHP 5.2.2 it is possible, to capture a website with PHP solely!
imagegrabscreen — Captures the whole screen
<?php
$img = imagegrabscreen();
imagepng($img, 'screenshot.png');
?>
imagegrabwindow - Grabs a window or its client area using a windows handle (HWND property in COM instance)
<?php
$Browser = new COM('InternetExplorer.Application');
$Browserhandle = $Browser->HWND;
$Browser->Visible = true;
$Browser->Fullscreen = true;
$Browser->Navigate('http://www.stackoverflow.com');
while($Browser->Busy){
com_message_pump(4000);
}
$img = imagegrabwindow($Browserhandle, 0);
$Browser->Quit();
imagepng($img, 'screenshot.png');
?>
Edit: Note, these functions are available on Windows systems ONLY!
Can I get the name of the currently running function in JavaScript?
Since you have written a function named foo
and you know it is in myfile.js
why do you need to get this information dynamically?
That being said you can use arguments.callee.toString()
inside the function (this is a string representation of the entire function) and regex out the value of the function name.
Here is a function that will spit out its own name:
function foo() {
re = /^function\s+([^(]+)/
alert(re.exec(arguments.callee.toString())[1]);
}
How can I turn a JSONArray into a JSONObject?
Can't you originally get the data as a JSONObject?
Perhaps parse the string as both a JSONObject and a JSONArray in the first place?
Where is the JSON string coming from?
I'm not sure that it is possible to convert a JsonArray into a JsonObject.
I presume you are using the following from json.org
JSONObject.java
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
JSONArray.java
A JSONArray is an ordered sequence of values. Its external form is a string wrapped in square brackets with commas between the values. The internal form is an object having get() and opt() methods for accessing the values by index, and put() methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
jQuery/JavaScript: accessing contents of an iframe
I create a sample code . Now you can easily understand from different domain you can't access
content of iframe .. Same domain we can access iframe content
I share you my code , Please run this code
check the console . I print image src at console. There are four iframe , two iframe coming from same domain & other two from other domain(third party) .You can see two image src( https://www.google.com/logos/doodles/2015/googles-new-logo-5078286822539264.3-hp2x.gif
and
https://www.google.com/logos/doodles/2015/arbor-day-2015-brazil-5154560611975168-hp2x.gif
)
at console and also can see two permission error(
2
Error: Permission denied to access property 'document'
...irstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument...
) which is coming from third party iframe.
<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top">
<p>iframe from same domain</p>
<iframe frameborder="0" scrolling="no" width="500" height="500"
src="iframe.html" name="imgbox" class="iView">
</iframe>
<p>iframe from same domain</p>
<iframe frameborder="0" scrolling="no" width="500" height="500"
src="iframe2.html" name="imgbox" class="iView1">
</iframe>
<p>iframe from different domain</p>
<iframe frameborder="0" scrolling="no" width="500" height="500"
src="https://www.google.com/logos/doodles/2015/googles-new-logo-5078286822539264.3-hp2x.gif" name="imgbox" class="iView2">
</iframe>
<p>iframe from different domain</p>
<iframe frameborder="0" scrolling="no" width="500" height="500"
src="http://d1rmo5dfr7fx8e.cloudfront.net/" name="imgbox" class="iView3">
</iframe>
<script type='text/javascript'>
$(document).ready(function(){
setTimeout(function(){
var src = $('.iView').contents().find(".shrinkToFit").attr('src');
console.log(src);
}, 2000);
setTimeout(function(){
var src = $('.iView1').contents().find(".shrinkToFit").attr('src');
console.log(src);
}, 3000);
setTimeout(function(){
var src = $('.iView2').contents().find(".shrinkToFit").attr('src');
console.log(src);
}, 3000);
setTimeout(function(){
var src = $('.iView3').contents().find("img").attr('src');
console.log(src);
}, 3000);
})
</script>
</body>
Python read-only property
Just my two cents, Silas Ray is on the right track, however I felt like adding an example. ;-)
Python is a type-unsafe language and thus you'll always have to trust the users of your code to use the code like a reasonable (sensible) person.
Per PEP 8:
Use one leading underscore only for non-public methods and instance variables.
To have a 'read-only' property in a class you can make use of the @property
decoration, you'll need to inherit from object
when you do so to make use of the new-style classes.
Example:
>>> class A(object):
... def __init__(self, a):
... self._a = a
...
... @property
... def a(self):
... return self._a
...
>>> a = A('test')
>>> a.a
'test'
>>> a.a = 'pleh'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
Git commit -a "untracked files"?
First you need to add all untracked files. Use this command line:
git add *
Then commit using this command line :
git commit -a
Open Redis port for remote connections
A quick note that if you are using AWS ec2 instance then there is one more extra step that I believe is also mandatory. I missed the step-3 and it took me whole day to figure out to add an inbound rule to security group
Step 1(as previous): in your redis.conf change bind 127.0.0.1 to bind 0.0.0.0
Step2(as previous): in your redis.conf change protected-mode yes to protected-mode no
important for Amazon Ec2 Instance:
Step3: In your current ec2 machine go to the security group. add an inbound rule
for custom TCP with 6379 port and select option "use from anywhere".
How to convert DATE to UNIX TIMESTAMP in shell script on MacOS
Alternatively you can install GNU date like so:
- install Homebrew: https://brew.sh/
brew install coreutils
- add to your bash_profile:
alias date="/usr/local/bin/gdate"
date +%s
1547838127
Comments saying Mac has to be "different" simply reveal the commenter is ignorant of the history of UNIX. macOS is based on BSD UNIX, which is way older than Linux. Linux essentially was a copy of other UNIX systems, and Linux decided to be "different" by adopting GNU tools instead of BSD tools. GNU tools are more user friendly, but they're not usually found on any *BSD system (just the way it is).
Really, if you spend most of your time in Linux, but have a Mac desktop, you probably want to make the Mac work like Linux. There's no sense in trying to remember two different sets of options, or scripting for the mac's BSD version of Bash, unless you are writing a utility that you want to run on both BSD and GNU/Linux shells.
How to use a variable from a cursor in the select statement of another cursor in pl/sql
You can certainly do something like
SQL> ed
Wrote file afiedt.buf
1 begin
2 for d in (select * from dept)
3 loop
4 for e in (select * from emp where deptno=d.deptno)
5 loop
6 dbms_output.put_line( 'Employee ' || e.ename ||
7 ' in department ' || d.dname );
8 end loop;
9 end loop;
10* end;
SQL> /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES
PL/SQL procedure successfully completed.
Or something equivalent using explicit cursors.
SQL> ed
Wrote file afiedt.buf
1 declare
2 cursor dept_cur
3 is select *
4 from dept;
5 d dept_cur%rowtype;
6 cursor emp_cur( p_deptno IN dept.deptno%type )
7 is select *
8 from emp
9 where deptno = p_deptno;
10 e emp_cur%rowtype;
11 begin
12 open dept_cur;
13 loop
14 fetch dept_cur into d;
15 exit when dept_cur%notfound;
16 open emp_cur( d.deptno );
17 loop
18 fetch emp_cur into e;
19 exit when emp_cur%notfound;
20 dbms_output.put_line( 'Employee ' || e.ename ||
21 ' in department ' || d.dname );
22 end loop;
23 close emp_cur;
24 end loop;
25 close dept_cur;
26* end;
27 /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES
PL/SQL procedure successfully completed.
However, if you find yourself using nested cursor FOR loops, it is almost always more efficient to let the database join the two results for you. After all, relational databases are really, really good at joining. I'm guessing here at what your tables look like and how they relate based on the code you posted but something along the lines of
FOR x IN (SELECT *
FROM all_users,
org
WHERE length(all_users.username) = 3
AND all_users.username = org.username )
LOOP
<<do something>>
END LOOP;
datetime dtypes in pandas read_csv
You might try passing actual types instead of strings.
import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4']
dtypes = [datetime, datetime, str, float]
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)
But it's going to be really hard to diagnose this without any of your data to tinker with.
And really, you probably want pandas to parse the the dates into TimeStamps, so that might be:
pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=True)
Array of strings in groovy
Most of the time you would create a list in groovy rather than an array. You could do it like this:
names = ["lucas", "Fred", "Mary"]
Alternately, if you did not want to quote everything like you did in the ruby example, you could do this:
names = "lucas Fred Mary".split()
How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?
The accepted answer to set git config core.filemode false
, works, but with consequences. Setting core.filemode
to false tells git to ignore any executable bit changes on the filesystem so it won't view this as a change. If you do need to stage an executable bit change for this repository anytime in the future, you would have to do it manually, or set core.filemode
back to true.
A less consequential alternative, if all the modified files should have mode 100755, is to do something like
chmod 100755 $(git ls-files --modified)
which just does exactly the change in mode, no more, no less, without additional implications.
(in my case, it was due to a OneDrive sync with my filesystem on MacOS; by not changing core.filemode
, I'm leaving the possibility open that the mode change might happen again in the future; in my case, I'd like to know if it happens again, and changing core.filemode
will hide it from me, which I don't want)
How can I print out just the index of a pandas dataframe?
You can access the index attribute of a df using df.index[i]
>> import pandas as pd
>> import numpy as np
>> df = pd.DataFrame({'a':np.arange(5), 'b':np.random.randn(5)})
a b
0 0 1.088998
1 1 -1.381735
2 2 0.035058
3 3 -2.273023
4 4 1.345342
>> df.index[1] ## Second index
>> df.index[-1] ## Last index
>> for i in xrange(len(df)):print df.index[i] ## Using loop
...
0
1
2
3
4
How to unpackage and repackage a WAR file
you can update your war from the command line using java commands as mentioned here:
jar -uvf test.war yourclassesdir
Other useful commands:
Command to unzip/explode the war file
jar -xvf test.war
Command to create the war file
jar -cvf test.war yourclassesdir
Eg:
jar -cvf test.war *
jar -cvf test.war WEB-INF META-INF
Django request.GET
Calling /search/
should result in "you submitted nothing", but calling /search/?q=
on the other hand should result in "you submitted u''"
Browsers have to add the q=
even when it's empty, because they have to include all fields which are part of the form. Only if you do some DOM manipulation in Javascript (or a custom javascript submit action), you might get such a behavior, but only if the user has javascript enabled. So you should probably simply test for non-empty strings, e.g:
if request.GET.get('q'):
message = 'You submitted: %r' % request.GET['q']
else:
message = 'You submitted nothing!'
Run R script from command line
This does not answer the question directly. But someone may end up here because they want to run a oneliner of R from the terminal. For example, if you just want to install some missing packages and quit, this oneliner can be very convenient. I use it a lot when I suddenly find out that I miss some packages, and I want to install them to where I want.
To install to the default location:
R -e 'install.packages(c("package1", "package2"))'
To install to a location that requires root
privileges:
R -e 'install.packages(c("package1", "package2"), lib="/usr/local/lib/R/site-library")'
Why is ZoneOffset.UTC != ZoneId.of("UTC")?
The answer comes from the javadoc of ZoneId
(emphasis mine) ...
A ZoneId is used to identify the rules used to convert between an
Instant and a LocalDateTime. There are two distinct types of ID:
- Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
- Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply
Most fixed offsets are represented by ZoneOffset. Calling normalized()
on any ZoneId will ensure that a fixed offset ID will be represented
as a ZoneOffset.
... and from the javadoc of ZoneId#of
(emphasis mine):
This method parses the ID producing a ZoneId or ZoneOffset. A
ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.
The argument id is specified as "UTC"
, therefore it will return a ZoneId
with an offset, which also presented in the string form:
System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));
Outputs:
2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]
As you use the equals
method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false
.
When the normalized()
method is used as proposed in the documentation, the comparison using equals
will return true
, as normalized()
will return the corresponding ZoneOffset
:
Normalizes the time-zone ID, returning a ZoneOffset where possible.
now.withZoneSameInstant(ZoneOffset.UTC)
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true
As the documentation states, if you use "Z"
or "+0"
as input id, of
will return the ZoneOffset
directly and there is no need to call normalized()
:
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true
To check if they store the same date time, you can use the isEqual
method instead:
now.withZoneSameInstant(ZoneOffset.UTC)
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true
Sample
System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));
Output:
equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true
CMake output/build directory
It sounds like you want an out of source build. There are a couple of ways you can create an out of source build.
Do what you were doing, run
cd /path/to/my/build/folder
cmake /path/to/my/source/folder
which will cause cmake to generate a build tree in /path/to/my/build/folder
for the source tree in /path/to/my/source/folder
.
Once you've created it, cmake remembers where the source folder is - so you can rerun
cmake on the build tree with
cmake /path/to/my/build/folder
or even
cmake .
if your current directory is already the build folder.
For CMake 3.13 or later, use these options to set the source and build folders
cmake -B/path/to/my/build/folder -S/path/to/my/source/folder
For older CMake, use some undocumented options to set the source and build folders:
cmake -B/path/to/my/build/folder -H/path/to/my/source/folder
which will do exactly the same thing as (1), but without the reliance on the current working directory.
CMake puts all of its outputs in the build tree by default, so unless you are liberally using ${CMAKE_SOURCE_DIR}
or ${CMAKE_CURRENT_SOURCE_DIR}
in your cmake files, it shouldn't touch your source tree.
The biggest thing that can go wrong is if you have previously generated a build tree in your source tree (i.e. you have an in source build). Once you've done this the second part of (1) above kicks in, and cmake doesn't make any changes to the source or build locations. Thus, you cannot create an out-of-source build for a source directory with an in-source build. You can fix this fairly easily by removing (at a minimum) CMakeCache.txt
from the source directory. There are a few other files (mostly in the CMakeFiles
directory) that CMake generates that you should remove as well, but these won't cause cmake to treat the source tree as a build tree.
Since out-of-source builds are often more desirable than in-source builds, you might want to modify your cmake to require out of source builds:
# Ensures that we do an out of source build
MACRO(MACRO_ENSURE_OUT_OF_SOURCE_BUILD MSG)
STRING(COMPARE EQUAL "${CMAKE_SOURCE_DIR}"
"${CMAKE_BINARY_DIR}" insource)
GET_FILENAME_COMPONENT(PARENTDIR ${CMAKE_SOURCE_DIR} PATH)
STRING(COMPARE EQUAL "${CMAKE_SOURCE_DIR}"
"${PARENTDIR}" insourcesubdir)
IF(insource OR insourcesubdir)
MESSAGE(FATAL_ERROR "${MSG}")
ENDIF(insource OR insourcesubdir)
ENDMACRO(MACRO_ENSURE_OUT_OF_SOURCE_BUILD)
MACRO_ENSURE_OUT_OF_SOURCE_BUILD(
"${CMAKE_PROJECT_NAME} requires an out of source build."
)
The above macro comes from a commonly used module called MacroOutOfSourceBuild
. There are numerous sources for MacroOutOfSourceBuild.cmake
on google but I can't seem to find the original and it's short enough to include here in full.
Unfortunately cmake has usually written a few files by the time the macro is invoked, so although it will stop you from actually performing the build you will still need to delete CMakeCache.txt
and CMakeFiles
.
You may find it useful to set the paths that binaries, shared and static libraries are written to - in which case see how do I make cmake output into a 'bin' dir? (disclaimer, I have the top voted answer on that question...but that's how I know about it).
How to install mcrypt extension in xampp
The recent versions of XAMPP for Windows runs PHP 7.x which are NOT compatible with mbcrypt.
If you have a package like Laravel that requires mbcrypt, you will need to install an older version of XAMPP. OR, you can run XAMPP with multiple versions of PHP by downloading a PHP package from Windows.PHP.net, installing it in your XAMPP folder, and configuring php.ini and httpd.conf to use the correct version of PHP for your site.
%i or %d to print integer in C using printf()?
They are completely equivalent when used with printf()
. Personally, I prefer %d
, it's used more often (should I say "it's the idiomatic conversion specifier for int
"?).
(One difference between %i
and %d
is that when used with scanf()
, then %d
always expects a decimal integer, whereas %i
recognizes the 0
and 0x
prefixes as octal and hexadecimal, but no sane programmer uses scanf()
anyway so this should not be a concern.)
ReferenceError: describe is not defined NodeJs
OP asked about running from node
not from mocha
. This is a very common use case, see Using Mocha Programatically
This is what injected describe and it into my tests.
mocha.ui('bdd').run(function (failures) {
process.on('exit', function () {
process.exit(failures);
});
});
I tried tdd
like in the docs, but that didn't work, bdd worked though.
Add Foreign Key relationship between two Databases
In my experience, the best way to handle this when the primary authoritative source of information for two tables which are related has to be in two separate databases is to sync a copy of the table from the primary location to the secondary location (using T-SQL or SSIS with appropriate error checking - you cannot truncate and repopulate a table while it has a foreign key reference, so there are a few ways to skin the cat on the table updating).
Then add a traditional FK relationship in the second location to the table which is effectively a read-only copy.
You can use a trigger or scheduled job in the primary location to keep the copy updated.
How to ignore the certificate check when ssl
Just incidentally, this is a the least verbose way of turning off all certificate validation in a given app that I know of:
ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
Insert array into MySQL database with PHP
Personally I'd json_encode the array (taking into account any escaping etc needed) and bung the entire lot into an appropriately sized text/blob field.
It makes it very easy to store "unstructured" data but a real PITA to search/index on with any grace.
A simple json_decode will "explode" the data back into an array for you.
Ripple effect on Android Lollipop CardView
I managed to get the ripple effect on the cardview by :
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:clickable="true"
android:foreground="@drawable/custom_bg"/>
and for the custom_bg that you can see in above code, you have to define a xml file for both lollipop(in drawable-v21 package) and pre-lollipop(in drawable package) devices.
for custom_bg in drawable-v21 package the code is:
<ripple
xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?android:attr/colorControlHighlight">
<item
android:id="@android:id/mask"
android:drawable="@android:color/white"/>
</ripple>
for custom_bg in the drawable package, code is:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape>
<solid android:color="@color/colorHighlight"></solid>
</shape>
</item>
<item>
<shape>
<solid android:color="@color/navigation_drawer_background"></solid>
</shape>
</item>
</selector>
so on pre-lollipop devices you will have a solid click effect and on lollipop devices you will have a ripple effect on the cardview.
git revert back to certain commit
git reset --hard 4a155e5
Will move the HEAD back to where you want to be. There may be other references ahead of that time that you would need to remove if you don't want anything to point to the history you just deleted.
PHP remove commas from numeric strings
Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
Do it the other way around:
$a = "1,435";
$b = str_replace( ',', '', $a );
if( is_numeric( $b ) ) {
$a = $b;
}
The easiest would be:
$var = intval(preg_replace('/[^\d.]/', '', $var));
or if you need float:
$var = floatval(preg_replace('/[^\d.]/', '', $var));
PHP Undefined Index
The checking of the presence of the member before assigning it is, in my opinion, quite ugly.
Kohana has a useful function to make selecting parameters simple.
You can make your own like so...
function arrayGet($array, $key, $default = NULL)
{
return isset($array[$key]) ? $array[$key] : $default;
}
And then do something like...
$page = arrayGet($_GET, 'p', 1);
SQL - Query to get server's IP address
I know this is an old post, but perhaps this solution can be usefull when you want to retrieve the IP address and TCP port from a Shared Memory connection (e.g. from a script run in SSMS locally on the server). The key is to open a secondary connection to your SQL Server using OPENROWSET, in which you specify 'tcp:' in your connection string. The rest of the code is merely building dynamic SQL to get around OPENROWSET’s limitation of not being able to take variables as its parameters.
DECLARE @ip_address varchar(15)
DECLARE @tcp_port int
DECLARE @connectionstring nvarchar(max)
DECLARE @parm_definition nvarchar(max)
DECLARE @command nvarchar(max)
SET @connectionstring = N'Server=tcp:' + @@SERVERNAME + ';Trusted_Connection=yes;'
SET @parm_definition = N'@ip_address_OUT varchar(15) OUTPUT
, @tcp_port_OUT int OUTPUT';
SET @command = N'SELECT @ip_address_OUT = a.local_net_address,
@tcp_port_OUT = a.local_tcp_port
FROM OPENROWSET(''SQLNCLI''
, ''' + @connectionstring + '''
, ''SELECT local_net_address
, local_tcp_port
FROM sys.dm_exec_connections
WHERE session_id = @@spid
'') as a'
EXEC SP_executeSQL @command
, @parm_definition
, @ip_address_OUT = @ip_address OUTPUT
, @tcp_port_OUT = @tcp_port OUTPUT;
SELECT @ip_address, @tcp_port
Should each and every table have a primary key?
Short answer: yes.
Long answer:
- You need your table to be joinable on something
- If you want your table to be clustered, you need some kind of a primary key.
- If your table design does not need a primary key, rethink your design: most probably, you are missing something. Why keep identical records?
In MySQL, the InnoDB storage engine always creates a primary key if you didn't specify it explicitly, thus making an extra column you don't have access to.
Note that a primary key can be composite.
If you have a many-to-many link table, you create the primary key on all fields involved in the link. Thus you ensure that you don't have two or more records describing one link.
Besides the logical consistency issues, most RDBMS engines will benefit from including these fields in a unique index.
And since any primary key involves creating a unique index, you should declare it and get both logical consistency and performance.
See this article in my blog for why you should always create a unique index on unique data:
P.S. There are some very, very special cases where you don't need a primary key.
Mostly they include log tables which don't have any indexes for performance reasons.
Creating a Custom Event
Yes, provided you have access to the object definition and can modify it to declare the custom event
public event EventHandler<EventArgs> ModelChanged;
And normally you'd back this up with a private method used internally to invoke the event:
private void OnModelChanged(EventArgs e)
{
if (ModelChanged != null)
ModelChanged(this, e);
}
Your code simply declares a handler for the declared myMethod
event (you can also remove the constructor), which would get invoked every time the object triggers the event.
myObject.myMethod += myNameEvent;
Similarly, you can detach a handler using
myObject.myMethod -= myNameEvent;
Also, you can write your own subclass of EventArgs
to provide specific data when your event fires.
When to use "ON UPDATE CASCADE"
It's true that if your primary key is just a identity value auto incremented, you would have no real use for ON UPDATE CASCADE.
However, let's say that your primary key is a 10 digit UPC bar code and because of expansion, you need to change it to a 13-digit UPC bar code. In that case, ON UPDATE CASCADE would allow you to change the primary key value and any tables that have foreign key references to the value will be changed accordingly.
In reference to #4, if you change the child ID to something that doesn't exist in the parent table (and you have referential integrity), you should get a foreign key error.
#1055 - Expression of SELECT list is not in GROUP BY clause and contains nonaggregated column this is incompatible with sql_mode=only_full_group_by
You need to specify all of the columns that you're not using for an aggregation function in your GROUP BY
clause like this:
select libelle,credit_initial,disponible_v,sum(montant) as montant
FROM fiche,annee,type where type.id_type=annee.id_type and annee.id_annee=fiche.id_annee
and annee = year(current_timestamp) GROUP BY libelle,credit_initial,disponible_v order by libelle asc
The full_group_by
mode basically makes you write more idiomatic SQL. You can turn off this setting if you'd like. There are different ways to do this that are outlined in the MySQL Documentation. Here's MySQL's definition of what I said above:
MySQL 5.7.5 and up implements detection of functional dependence. If
the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default),
MySQL rejects queries for which the select list, HAVING condition, or
ORDER BY list refer to nonaggregated columns that are neither named in
the GROUP BY clause nor are functionally dependent on them. (Before
5.7.5, MySQL does not detect functional dependency and ONLY_FULL_GROUP_BY is not enabled by default. For a description of
pre-5.7.5 behavior, see the MySQL 5.6 Reference Manual.)
You're getting the error because you're on a version < 5.7.5
How to check if a network port is open on linux?
Building upon the psutil
solution mentioned by Joe (only works for checking local ports):
import psutil
1111 in [i.laddr.port for i in psutil.net_connections()]
returns True
if port 1111 currently used.
psutil
is not part of python stdlib, so you'd need to pip install psutil
first. It also needs python headers to be available, so you need something like python-devel
Print current call stack from a method in Python code
Install Inspect-it
pip3 install inspect-it --user
Code
import inspect;print(*['\n\x1b[0;36;1m| \x1b[0;32;1m{:25}\x1b[0;36;1m| \x1b[0;35;1m{}'.format(str(x.function), x.filename+'\x1b[0;31;1m:'+str(x.lineno)+'\x1b[0m') for x in inspect.stack()])
you can Make a snippet of this line
it will show you a list of the function call stack with a filename and line number
list from start to where you put this line
Manifest merger failed : uses-sdk:minSdkVersion 14
You have to configure all the supports and appcompat libraries with version 19.+
If the recommendation of leave the support library with the 19.+ version doesn't works you can try the next tip in your AndroidManifest file.
First add this code:
xmlns:tools="http://schemas.android.com/tools"
And then, at the application level (not inside application!)
<uses-sdk tools:node="replace" />
The zip() function in Python 3
The zip()
function in Python 3 returns an iterator. That is the reason why when you print test1
you get - <zip object at 0x1007a06c8>
. From documentation -
Make an iterator that aggregates elements from each of the iterables.
But once you do - list(test1)
- you have exhausted the iterator. So after that anytime you do list(test1)
would only result in empty list.
In case of test2
, you have already created the list once, test2
is a list, and hence it will always be that list.
How to do a https request with bad certificate?
Security note: Disabling security checks is dangerous and should be avoided
You can disable security checks globally for all requests of the default client:
package main
import (
"fmt"
"net/http"
"crypto/tls"
)
func main() {
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
_, err := http.Get("https://golang.org/")
if err != nil {
fmt.Println(err)
}
}
You can disable security check for a client:
package main
import (
"fmt"
"net/http"
"crypto/tls"
)
func main() {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
_, err := client.Get("https://golang.org/")
if err != nil {
fmt.Println(err)
}
}
Is there anything like .NET's NotImplementedException in Java?
As mentioned, the JDK does not have a close match. However, my team occasionally has a use for such an exception as well. We could have gone with UnsupportedOperationException
as suggested by other answers, but we prefer a custom exception class in our base library that has deprecated constructors:
public class NotYetImplementedException extends RuntimeException
{
/**
* @deprecated Deprecated to remind you to implement the corresponding code
* before releasing the software.
*/
@Deprecated
public NotYetImplementedException()
{
}
/**
* @deprecated Deprecated to remind you to implement the corresponding code
* before releasing the software.
*/
@Deprecated
public NotYetImplementedException(String message)
{
super(message);
}
}
This approach has the following benefits:
- When readers see
NotYetImplementedException
, they know that an implementation was planned and was either forgotten or is still in progress, whereas UnsupportedOperationException
says (in line with collection contracts) that something will never be implemented. That's why we have the word "yet" in the class name. Also, an IDE can easily list the call sites.
- With the deprecation warning at each call site, your IDE and static code analysis tool can remind you where you still have to implement something. (This use of deprecation may feel wrong to some, but in fact deprecation is not limited to announcing removal.)
- The constructors are deprecated, not the class. This way, you only get a deprecation warning inside the method that needs implementing, not at the
import
line (JDK 9 fixed this, though).
Using gradle to find dependency tree
Note that you may need to do something like ./gradlew <module_directory>:<module_name>:dependencies
if the module has extra directory before reach its build.gradle. When in doubt, do ./gradlew tasks --all
to check the name.
Jenkins could not run git
For Jenkins 2.121.3 version, Go to Manage jenkins -> Global tool configuration -> Git installations -> Path to Git executable: C:\Program Files\Git\bin\git.exe
It works!
In Jenkins, give the http URL. SSH URL shows similar error.
Check status of one port on remote host
Use nc command,
nc -zv <hostname/ip> <port/port range>
For example,
nc -zv localhost 27017-27019
or
nc -zv localhost 27017
You can also use telnet command
telnet <ip/host> port
Can local storage ever be considered secure?
This is a really interesting article here. I'm considering implementing JS encryption for offering security when using local storage. It's absolutely clear that this will only offer protection if the device is stolen (and is implemented correctly). It won't offer protection against keyloggers etc. However this is not a JS issue as the keylogger threat is a problem of all applications, regardless of their execution platform (browser, native). As to the article "JavaScript Crypto Considered Harmful" referenced in the first answer, I have one criticism; it states "You could use SSL/TLS to solve this problem, but that's expensive and complicated". I think this is a very ambitious claim (and possibly rather biased). Yes, SSL has a cost, but if you look at the cost of developing native applications for multiple OS, rather than web-based due to this issue alone, the cost of SSL becomes insignificant.
My conclusion - There is a place for client-side encryption code, however as with all applications the developers must recognise it's limitations and implement if suitable for their needs, and ensuring there are ways of mitigating it's risks.
Can HTML checkboxes be set to readonly?
I know that "disabled" isn't an acceptable answer, since the op wants it to post. However, you're always going to have to validate values on the server side EVEN if you have the readonly option set. This is because you can't stop a malicious user from posting values using the readonly attribute.
I suggest storing the original value (server side), and setting it to disabled. Then, when they submit the form, ignore any values posted and take the original values that you stored.
It'll look and behave like it's a readonly value. And it handles (ignores) posts from malicious users. You're killing 2 birds with one stone.
Uncaught TypeError: Object #<Object> has no method 'movingBoxes'
When I had this problem it was because I was trying to use an actual function in place of an anonymous function.
Incorrect:
$(document).on('change', "#MyId", MyFunction());
Correct
$(document).on('change', "#MyId", MyFunction);
or also correct and if you need to pass event object or other params.
$(document).on('change', "#MyId", function(e) { MyFunction(e); });
How to annotate MYSQL autoincrement field with JPA annotations
If you are using Mysql with Hibernate v3 it's ok to use GenerationType.AUTO
because internally it will use GenerationType.IDENTITY
, which is the most optimal in for MySQL.
However in Hibernate v5, It has changed. GenerationType.AUTO
will use GenerationType.TABLE
which generates to much queries for the insertion.
You can avoid that using GenerationType.IDENTITY
(if MySQL is the only database you are using) or with these notations (if you have multiple databases):
@GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
@GenericGenerator(name = "native", strategy = "native")
HTML 5 Video "autoplay" not automatically starting in CHROME
Try this:
<video src="{{ asset('path/to/your_video.mp4' )}}" muted autoplay loop playsinline></video>
And put this js
after that:
window.addEventListener('load', async () => {
let video = document.querySelector('video[muted][autoplay]');
try {
await video.play();
} catch (err) {
video.controls = true;
}
});
Delete everything in a MongoDB database
By compiling answers from @Robse and @DanH (kudos!), I've got the following solution which completely satisfies me:
db.getCollectionNames().forEach( function(collection_name) {
if (collection_name.indexOf("system.") == -1)
db[collection_name].drop();
else
db.collection_name.remove({});
});
Connect to you database, run the code.
It cleans the database by dropping the user collections and emptying the system collections.
Access-control-allow-origin with multiple domains
You can add this code to your asp.net webapi project
in file Global.asax
protected void Application_BeginRequest()
{
string origin = Request.Headers.Get("Origin");
if (Request.HttpMethod == "OPTIONS")
{
Response.AddHeader("Access-Control-Allow-Origin", origin);
Response.AddHeader("Access-Control-Allow-Headers", "*");
Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,PUT,OPTIONS,DELETE");
Response.StatusCode = 200;
Response.End();
}
else
{
Response.AddHeader("Access-Control-Allow-Origin", origin);
Response.AddHeader("Access-Control-Allow-Headers", "*");
Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,PUT,OPTIONS,DELETE");
}
}
Create an enum with string values
With custom transformers (https://github.com/Microsoft/TypeScript/pull/13940) which is available in typescript@next, you can create enum like object with string values from string literal types.
Please look into my npm package, ts-transformer-enumerate.
Example usage:
// The signature of `enumerate` here is `function enumerate<T extends string>(): { [K in T]: K };`
import { enumerate } from 'ts-transformer-enumerate';
type Colors = 'green' | 'yellow' | 'red';
const Colors = enumerate<Colors>();
console.log(Colors.green); // 'green'
console.log(Colors.yellow); // 'yellow'
console.log(Colors.red); // 'red'
How do I fix maven error The JAVA_HOME environment variable is not defined correctly?
This is how I fixed this issue on Windows 10:
My JDK is located in C:\Program Files\Java\jdk-11.0.2
and the problem I had was the space in Program Files
. If I set JAVA_HOME using set JAVA_HOME="C:\Program Files\Java\jdk-11.0.2"
then Maven had an issue with the double quotes:
C:\Users>set JAVA_HOME="C:\Program Files\Java\jdk-11.0.2"
C:\Users>echo %JAVA_HOME%
"C:\Program Files\Java\jdk-11.0.2"
C:\Users>mvn -version
Files\Java\jdk-11.0.2""=="" was unexpected at this time.
Referring to Program Files
as PROGRA~1
didn't help either. The solution is using the PROGRAMFILES variable inside of JAVA_HOME:
C:\Users>echo %PROGRAMFILES%
C:\Program Files
C:\Program Files>set JAVA_HOME=%PROGRAMFILES%\Java\jdk-11.0.2
C:\Program Files>echo %JAVA_HOME%
C:\Program Files\Java\jdk-11.0.2
C:\Program Files>mvn -version
Apache Maven 3.6.2 (40f52333136460af0dc0d7232c0dc0bcf0d9e117; 2019-08-27T17:06:16+02:00)
Maven home: C:\apache-maven-3.6.2\bin\..
Java version: 11.0.2, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk-11.0.2
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"
Is there a limit to the length of a GET request?
Not in the RFC, no, but there are practical limits.
The HTTP protocol does not place any a priori limit on the length of
a URI. Servers MUST be able to handle the URI of any resource they
serve, and SHOULD be able to handle URIs of unbounded length if they
provide GET-based forms that could generate such URIs. A server
SHOULD return 414 (Request-URI Too Long) status if a URI is longer
than the server can handle (see section 10.4.15).
Note: Servers should be cautious about depending on URI lengths
above 255 bytes, because some older client or proxy implementations
may not properly support these lengths.
Plotting power spectrum in python
Numpy has a convenience function, np.fft.fftfreq
to compute the frequencies associated with FFT components:
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
data = np.random.rand(301) - 0.5
ps = np.abs(np.fft.fft(data))**2
time_step = 1 / 30
freqs = np.fft.fftfreq(data.size, time_step)
idx = np.argsort(freqs)
plt.plot(freqs[idx], ps[idx])
Note that the largest frequency you see in your case is not 30 Hz, but
In [7]: max(freqs)
Out[7]: 14.950166112956811
You never see the sampling frequency in a power spectrum. If you had had an even number of samples, then you would have reached the Nyquist frequency, 15 Hz in your case (although numpy would have calculated it as -15).
INNER JOIN vs INNER JOIN (SELECT . FROM)
You did the right thing by checking from query plans. But I have 100% confidence in version 2. It is faster when the number off records are on the very high side.
My database has around 1,000,000 records and this is exactly the scenario where the query plan shows the difference between both the queries.
Further, instead of using a where clause, if you use it in the join itself, it makes the query faster :
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID
WHERE p.isactive = 1
The better version of this query is :
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID AND p.isactive = 1
(Assuming isactive is a field in product table which represents the active/inactive products).
How do I use dataReceived event of the SerialPort Port Object in C#?
I think your issue is the line:**
sp.DataReceived += port_OnReceiveDatazz;
Shouldn't it be:
sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
**Nevermind, the syntax is fine (didn't realize the shortcut at the time I originally answered this question).
I've also seen suggestions that you should turn the following options on for your serial port:
sp.DtrEnable = true; // Data-terminal-ready
sp.RtsEnable = true; // Request-to-send
You may also have to set the handshake to RequestToSend (via the handshake enumeration).
UPDATE:
Found a suggestion that says you should open your port first, then assign the event handler. Maybe it's a bug?
So instead of this:
sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
sp.Open();
Do this:
sp.Open();
sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
Let me know how that goes.
How to play a sound using Swift?
import AVFoundation
import AudioToolbox
public final class MP3Player : NSObject {
// Singleton class
static let shared:MP3Player = MP3Player()
private var player: AVAudioPlayer? = nil
// Play only mp3 which are stored in the local
public func playLocalFile(name:String) {
guard let url = Bundle.main.url(forResource: name, withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
guard let player = player else { return }
player.play()
}catch let error{
print(error.localizedDescription)
}
}
}
To call this function
MP3Player.shared.playLocalFile(name: "JungleBook")
How to create a <style> tag with Javascript?
An example that works and are compliant with all browsers :
var ss = document.createElement("link");
ss.type = "text/css";
ss.rel = "stylesheet";
ss.href = "style.css";
document.getElementsByTagName("head")[0].appendChild(ss);
Returning JSON response from Servlet to Javascript/JSP page
I think that what you want to do is turn the JSON string back into an object when it arrives back in your XMLHttpRequest - correct?
If so, you need to eval the string to turn it into a JavaScript object - note that this can be unsafe as you're trusting that the JSON string isn't malicious and therefore executing it. Preferably you could use jQuery's parseJSON
Are the decimal places in a CSS width respected?
Even when the number is rounded when the page is painted, the full value is preserved in memory and used for subsequent child calculation. For example, if your box of 100.4999px paints to 100px, it's child with a width of 50% will be calculated as .5*100.4999 instead of .5*100. And so on to deeper levels.
I've created deeply nested grid layout systems where parents widths are ems, and children are percents, and including up to four decimal points upstream had a noticeable impact.
Edge case, sure, but something to keep in mind.
Newline in JLabel
Surround the string with <html></html>
and break the lines with <br/>
.
JLabel l = new JLabel("<html>Hello World!<br/>blahblahblah</html>", SwingConstants.CENTER);
Determine if $.ajax error is a timeout
If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.
Per the jQuery documentation:
Possible values for the second
argument (besides null) are "timeout",
"error", "notmodified" and
"parsererror".
You can handle your error accordingly then.
I created this fiddle that demonstrates this.
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 1000,
success: function(response) { alert(response); },
error: function(xmlhttprequest, textstatus, message) {
if(textstatus==="timeout") {
alert("got timeout");
} else {
alert(textstatus);
}
}
});?
With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.
Hope this helps!
Creating a JSON array in C#
new {var_data[counter] =new [] {
new{ "S NO": "+ obj_Data_Row["F_ID_ITEM_MASTER"].ToString() +","PART NAME": " + obj_Data_Row["F_PART_NAME"].ToString() + ","PART ID": " + obj_Data_Row["F_PART_ID"].ToString() + ","PART CODE":" + obj_Data_Row["F_PART_CODE"].ToString() + ", "CIENT PART ID": " + obj_Data_Row["F_ID_CLIENT"].ToString() + ","TYPES":" + obj_Data_Row["F_TYPE"].ToString() + ","UOM":" + obj_Data_Row["F_UOM"].ToString() + ","SPECIFICATION":" + obj_Data_Row["F_SPECIFICATION"].ToString() + ","MODEL":" + obj_Data_Row["F_MODEL"].ToString() + ","LOCATION":" + obj_Data_Row["F_LOCATION"].ToString() + ","STD WEIGHT":" + obj_Data_Row["F_STD_WEIGHT"].ToString() + ","THICKNESS":" + obj_Data_Row["F_THICKNESS"].ToString() + ","WIDTH":" + obj_Data_Row["F_WIDTH"].ToString() + ","HEIGHT":" + obj_Data_Row["F_HEIGHT"].ToString() + ","STUFF QUALITY":" + obj_Data_Row["F_STUFF_QTY"].ToString() + ","FREIGHT":" + obj_Data_Row["F_FREIGHT"].ToString() + ","THRESHOLD FG":" + obj_Data_Row["F_THRESHOLD_FG"].ToString() + ","THRESHOLD CL STOCK":" + obj_Data_Row["F_THRESHOLD_CL_STOCK"].ToString() + ","DESCRIPTION":" + obj_Data_Row["F_DESCRIPTION"].ToString() + "}
}
};
Git adding files to repo
After adding files to the stage, you need to commit them with git commit -m "comment"
after git add .
. Finally, to push them to a remote repository, you need to git push <remote_repo> <local_branch>
.
Changing the color of an hr element
I like the answers setting border-top, but they are somehow still a little off in Chrome...
BUT if I set border-top: 1px solid black;
and border-bottom: 0px;
I end up with a truly single line (that also works fine with higher thickness).
Eclipse CDT: no rule to make target all
Yet another solution:
I got inside objects.mk file
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
USER_OBJS := /home/../mylib.so
LIBS := -lstdc++fs -lGL -lGLU -lGLEW -lglut -lm -lmylib
then didn't read first line. Then altered next line. It was another projects' folder because I copied this using "copy/clone project" feature and this was causing the error for me. I changed myLib.so into /proper_address/reallyMyLib.so and it worked.
Warning: It may harm some unknown places! Backup whole project before doing this. Because it says "do not edit".
Vuex - passing multiple parameters to mutation
In simple terms you need to build your payload into a key array
payload = {'key1': 'value1', 'key2': 'value2'}
Then send the payload directly to the action
this.$store.dispatch('yourAction', payload)
No change in your action
yourAction: ({commit}, payload) => {
commit('YOUR_MUTATION', payload )
},
In your mutation call the values with the key
'YOUR_MUTATION' (state, payload ){
state.state1 = payload.key1
state.state2 = payload.key2
},
Return JSON with error status code MVC
You need to decide if you want "HTTP level error" (that what error codes are for) or "application level error" (that what your custom JSON response is for).
Most high level objects using HTTP will never look into response stream if error code set to something that is not 2xx (success range). In your case you are explicitly setting error code to failure (I think 403 or 500) and force XMLHttp object to ignore body of the response.
To fix - either handle error conditions on client side or not set error code and return JSON with error information (see Sbossb reply for details).
Why should I use var instead of a type?
As the others have said, there is no difference in the compiled code (IL) when you use either of the following:
var x1 = new object();
object x2 = new object;
I suppose Resharper warns you because it is [in my opinion] easier to read the first example than the second. Besides, what's the need to repeat the name of the type twice?
Consider the following and you'll get what I mean:
KeyValuePair<string, KeyValuePair<string, int>> y1 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));
It's way easier to read this instead:
var y2 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));
How do I flush the PRINT buffer in TSQL?
Building on the answer by @JoelCoehoorn, my approach is to leave all my PRINT statements in place, and simply follow them with the RAISERROR statement to cause the flush.
For example:
PRINT 'MyVariableName: ' + @MyVariableName
RAISERROR(N'', 0, 1) WITH NOWAIT
The advantage of this approach is that the PRINT statements can concatenate strings, whereas the RAISERROR cannot. (So either way you have the same number of lines of code, as you'd have to declare and set a variable to use in RAISERROR).
If, like me, you use AutoHotKey or SSMSBoost or an equivalent tool, you can easily set up a shortcut such as "]flush" to enter the RAISERROR line for you. This saves you time if it is the same line of code every time, i.e. does not need to be customised to hold specific text or a variable.
How to add \newpage in Rmarkdown in a smart way?
In the initialization chunk I define a function
pagebreak <- function() {
if(knitr::is_latex_output())
return("\\newpage")
else
return('<div style="page-break-before: always;" />')
}
In the markdown part where I want to insert a page break, I type
`r pagebreak()`
What happens when a duplicate key is put into a HashMap?
HashMap<Emp, Emp> empHashMap = new HashMap<Emp, Emp>();
empHashMap.put(new Emp(1), new Emp(1));
empHashMap.put(new Emp(1), new Emp(1));
empHashMap.put(new Emp(1), new Emp());
empHashMap.put(new Emp(1), new Emp());
System.out.println(empHashMap.size());
}
}
class Emp{
public Emp(){
}
public Emp(int id){
this.id = id;
}
public int id;
@Override
public boolean equals(Object obj) {
return this.id == ((Emp)obj).id;
}
@Override
public int hashCode() {
return id;
}
}
OUTPUT : is 1
Means hash map wont allow duplicates, if you have properly overridden equals and hashCode() methods.
HashSet also uses HashMap internally, see the source doc
public class HashSet{
public HashSet() {
map = new HashMap<>();
}
}
Shortcut for creating single item list in C#
Simply use this:
List<string> list = new List<string>() { "single value" };
You can even omit the () braces:
List<string> list = new List<string> { "single value" };
Update: of course this also works for more than one entry:
List<string> list = new List<string> { "value1", "value2", ... };
How to change symbol for decimal point in double.ToString()?
You can change the decimal separator by changing the culture used to display the number. Beware however that this will change everything else about the number (eg. grouping separator, grouping sizes, number of decimal places). From your question, it looks like you are defaulting to a culture that uses a comma as a decimal separator.
To change just the decimal separator without changing the culture, you can modify the NumberDecimalSeparator
property of the current culture's NumberFormatInfo
.
Thread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";
This will modify the current culture of the thread. All output will now be altered, meaning that you can just use value.ToString()
to output the format you want, without worrying about changing the culture each time you output a number.
(Note that a neutral culture cannot have its decimal separator changed.)
NodeJS/express: Cache and 304 status code
As you said, Safari sends Cache-Control: max-age=0
on reload. Express (or more specifically, Express's dependency, node-fresh) considers the cache stale when Cache-Control: no-cache
headers are received, but it doesn't do the same for Cache-Control: max-age=0
. From what I can tell, it probably should. But I'm not an expert on caching.
The fix is to change (what is currently) line 37 of node-fresh/index.js
from
if (cc && cc.indexOf('no-cache') !== -1) return false;
to
if (cc && (cc.indexOf('no-cache') !== -1 ||
cc.indexOf('max-age=0') !== -1)) return false;
I forked node-fresh and express to include this fix in my project's package.json
via npm
, you could do the same. Here are my forks, for example:
https://github.com/stratusdata/node-fresh
https://github.com/stratusdata/express#safari-reload-fix
The safari-reload-fix branch is based on the 3.4.7 tag.
Best Practice: Access form elements by HTML id or name attribute?
name
field works well. It provides a reference to the elements
.
parent.children
- Will list all elements with a name field of the parent.
parent.elements
- Will list only form elements
such as input-text, text-area, etc
_x000D_
_x000D_
var form = document.getElementById('form-1');_x000D_
console.log(form.children.firstname)_x000D_
console.log(form.elements.firstname)_x000D_
console.log(form.elements.progressBar); // undefined_x000D_
console.log(form.children.progressBar);_x000D_
console.log(form.elements.submit); // undefined
_x000D_
<form id="form-1">_x000D_
<input type="text" name="firstname" />_x000D_
<input type="file" name="file" />_x000D_
<progress name="progressBar" value="20" min="0" max="100" />_x000D_
<textarea name="address"></textarea>_x000D_
<input type="submit" name="submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_
Note: For .elements
to work, the parent
needs to be a <form> tag
. Whereas, .children
will work on any HTML-element
- such as <div>, <span>, etc
.
Good Luck...
How to hide image broken Icon using only CSS/HTML?
If you need to still have the image container visible due to it being filled in later on and don't want to bother with showing and hiding it you can stick a 1x1 transparent image inside of the src:
<img id="active-image" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"/>
I used this for this exact purpose. I had an image container that was going to have an image loaded into it via Ajax. Because the image was large and took a bit to load, it required setting a background-image in CSS of a Gif loading bar.
However, because the src of the was empty, the broken image icon still appeared in browsers that use it.
Setting the transparent 1x1 Gif fixes this problem simply and effectively with no code additions through CSS or JavaScript.
How to make a website secured with https
What should I do to prepare my website
for https. (Do I need to alter the
code / Config)
You should keep best practices for secure coding in mind (here is a good intro: http://www.owasp.org/index.php/Secure_Coding_Principles ), otherwise all you need is a correctly set up SSL certificate.
Is SSL and https one and the same..
Pretty much, yes.
Do I need to apply with someone to get
some license or something.
You can buy an SSL certificate from a certificate authority or use a self-signed certificate. The ones you can purchase vary wildly in price - from $10 to hundreds of dollars a year. You would need one of those if you set up an online shop, for example. Self-signed certificates are a viable option for an internal application. You can also use one of those for development. Here's a good tutorial on how to set up a self-signed certificate for IIS: Enabling SSL on IIS 7.0 Using Self-Signed Certificates
Do I need to make all my pages secured
or only the login page..
Use HTTPS for everything, not just the initial user login. It's not going to be too much of an overhead and it will mean the data that the users send/receive from your remotely hosted application cannot be read by outside parties if it is intercepted. Even Gmail now turns on HTTPS by default.
jQuery: selecting each td in a tr
Your $(magicSelector)
could be $('td', this)
. This will grab all td
that are children of this
, which in your case is each tr
. This is the same as doing $(this).find('td')
.
$('td', this).each(function() {
// Logic
});
Android: where are downloaded files saved?
Most devices have some form of emulated storage. if they support sd cards they are usually mounted to /sdcard
(or some variation of that name) which is usually symlinked to to a directory in /storage
like /storage/sdcard0
or /storage/0
sometimes the emulated storage is mounted to /sdcard
and the actual path is something like /storage/emulated/legacy. You should be able to use to get the downloads directory. You are best off using the api calls to get directories.
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Since the filesystems and sdcard support varies among devices.
see similar question for more info how to access downloads folder in android?
Usually the DownloadManager handles downloads and the files are then accessed by requesting the file's uri fromthe download manager using a file id to get where file was places which would usually be somewhere in the sdcard/ real or emulated since apps can only read data from certain places on the filesystem outside of their data directory like the sdcard
MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
If the mongoDB server is already installed and if you are unable to connect from a remote host then follow the below steps,
Login to your machine, open mongodb configuration file located at /etc/mongod.conf
and change the bindIp
field to specific ip / 0.0.0.0
, after that restart mongodb server.
sudo vi /etc/mongod.conf
The file should contain the following kind of content:
systemLog:
destination: file
path: "/var/log/mongodb/mongod.log"
logAppend: true
storage:
journal:
enabled: true
processManagement:
fork: true
net:
bindIp: 127.0.0.1 // change here to 0.0.0.0
port: 27017
setParameter:
enableLocalhostAuthBypass: false
Once you change the bindIp
, then you have to restart the mongodb, using the following command
sudo service mongod restart
Now you'll be able to connect to the mongodb server, from remote server.
How to reset selected file with input tag file type in Angular 2?
Angular 5
html
<input type="file" #inputFile>
<button (click)="reset()">Reset</button>
template
@ViewChild('inputFile') myInputVariable: ElementRef;
reset() {
this.myInputVariable.nativeElement.value = '';
}
Button is not required. You can reset it after change event, it is just for demonstration
Fatal error: Maximum execution time of 300 seconds exceeded
In Codeignitor version 3.0.x the system/core/Codeigniter.php do not contain the time constraint as well as inserting
ini_set('MAX_EXECUTION_TIME', -1);
will not work since codeignitor will override that with its own function set_time_limit() .
So either you have to delete that function from codeignitor or simply you can insert
set_time_limit('1000');
in the beginning of the php file if you wanna change that to 1000 seconds.
Set the time to 0 (zero) if you want to run it as long as it want.
How can I clone an SQL Server database on the same server in SQL Server 2008 Express?
The solution, based on this comment: https://stackoverflow.com/a/22409447/2399045 .
Just set settings: DB name, temp folder, db files folder.
And after run you will have the copy of DB with Name in "sourceDBName_yyyy-mm-dd" format.
-- Settings --
-- New DB name will have name = sourceDB_yyyy-mm-dd
declare @sourceDbName nvarchar(50) = 'MyDbName';
declare @tmpFolder nvarchar(50) = 'C:\Temp\'
declare @sqlServerDbFolder nvarchar(100) = 'C:\Databases\'
-- Execution --
declare @sourceDbFile nvarchar(50);
declare @sourceDbFileLog nvarchar(50);
declare @destinationDbName nvarchar(50) = @sourceDbName + '_' + (select convert(varchar(10),getdate(), 121))
declare @backupPath nvarchar(400) = @tmpFolder + @destinationDbName + '.bak'
declare @destMdf nvarchar(100) = @sqlServerDbFolder + @destinationDbName + '.mdf'
declare @destLdf nvarchar(100) = @sqlServerDbFolder + @destinationDbName + '_log' + '.ldf'
SET @sourceDbFile = (SELECT top 1 files.name
FROM sys.databases dbs
INNER JOIN sys.master_files files
ON dbs.database_id = files.database_id
WHERE dbs.name = @sourceDbName
AND files.[type] = 0)
SET @sourceDbFileLog = (SELECT top 1 files.name
FROM sys.databases dbs
INNER JOIN sys.master_files files
ON dbs.database_id = files.database_id
WHERE dbs.name = @sourceDbName
AND files.[type] = 1)
BACKUP DATABASE @sourceDbName TO DISK = @backupPath
RESTORE DATABASE @destinationDbName FROM DISK = @backupPath
WITH REPLACE,
MOVE @sourceDbFile TO @destMdf,
MOVE @sourceDbFileLog TO @destLdf
C++ deprecated conversion from string constant to 'char*'
In fact a string constant literal is neither a const char * nor a char* but a char[]. Its quite strange but written down in the c++ specifications; If you modify it the behavior is undefined because the compiler may store it in the code segment.
Android statusbar icons color
Not since Lollipop. Starting with Android 5.0, the guidelines say:
Notification icons must be entirely white.
Even if they're not, the system will only consider the alpha channel of your icon, rendering them white
Workaround
The only way to have a coloured icon on Lollipop is to lower your targetSdkVersion
to values <21
, but I think you would do better to follow the guidelines and use white icons only.
If you still however decide you want colored icons, you could use the DrawableCompat.setTint method from the new v4 support library.
What is the best way to implement nested dictionaries?
I like the idea of wrapping this in a class and implementing __getitem__
and __setitem__
such that they implemented a simple query language:
>>> d['new jersey/mercer county/plumbers'] = 3
>>> d['new jersey/mercer county/programmers'] = 81
>>> d['new jersey/mercer county/programmers']
81
>>> d['new jersey/mercer country']
<view which implicitly adds 'new jersey/mercer county' to queries/mutations>
If you wanted to get fancy you could also implement something like:
>>> d['*/*/programmers']
<view which would contain 'programmers' entries>
but mostly I think such a thing would be really fun to implement :D
how to change listen port from default 7001 to something different?
You can change the listen port as per your requirement.
This task can be accomplished in two diffrent ways.
By changing config.xml file
By changing in admin console
Change the listen port in config.xml as per your requirement and bounce the domain.
Admin Console
Login to AdminConsole->Server->Configuration->ListenPort (Change it)
Note:
It is a bad practice to edit config.xml and try to edit in admin console(It's a good practise as well)
How to check if an email address exists without sending an email?
"Can you tell if an email customer / user enters is correct & exists?"
Actually these are two separate things. It might exist but might not be correct.
Sometimes you have to take the user inputs at the face value. There are many ways to defeat the system otherwise.
Routing for custom ASP.NET MVC 404 Error page
Source
NotFoundMVC - Provides a user-friendly 404 page whenever a controller, action or route is not found in your ASP.NET MVC3 application.
A view called NotFound is rendered instead of the default ASP.NET error page.
You can add this plugin via nuget using:
Install-Package NotFoundMvc
NotFoundMvc automatically installs itself during web application start-up. It handles all the different ways a 404 HttpException is usually thrown by ASP.NET MVC. This includes a missing controller, action and route.
Step by Step Installation Guide :
1 - Right click on your Project and Select Manage Nuget Packages...
2 - Search for NotFoundMvc
and install it.
3 - Once the installation has be completed, two files will be added to your project. As shown in the screenshots below.
4 - Open the newly added NotFound.cshtml present at Views/Shared and modify it at your will. Now run the application and type in an incorrect url, and you will be greeted with a User friendly 404 page.
No more, will users get errors message like Server Error in '/' Application. The resource cannot be found.
Hope this helps :)
P.S : Kudos to Andrew Davey for making such an awesome plugin.
How do you change text to bold in Android?
In XML
android:textStyle="bold" //only bold
android:textStyle="italic" //only italic
android:textStyle="bold|italic" //bold & italic
You can only use specific fonts sans
, serif
& monospace
via xml, Java code can use custom fonts
android:typeface="monospace" // or sans or serif
Programmatically (Java code)
TextView textView = (TextView) findViewById(R.id.TextView1);
textView.setTypeface(Typeface.SANS_SERIF); //only font style
textView.setTypeface(null,Typeface.BOLD); //only text style(only bold)
textView.setTypeface(null,Typeface.BOLD_ITALIC); //only text style(bold & italic)
textView.setTypeface(Typeface.SANS_SERIF,Typeface.BOLD);
//font style & text style(only bold)
textView.setTypeface(Typeface.SANS_SERIF,Typeface.BOLD_ITALIC);
//font style & text style(bold & italic)
Regex for empty string or white space
The \
(backslash) in the .match
call is not properly escaped. It would be easier to use a regex literal though. Either will work:
var regex = "^\\s+$";
var regex = /^\s+$/;
Also note that +
will require at least one space. You may want to use *
.