Page
is a special case handler.
Generic Web handler (*.ashx
, extension based processor) is the default HTTP handler for all Web handlers that do not have a UI and that include the @WebHandler
directive.
ASP.NET page handler (*.aspx
) is the default HTTP handler for all ASP.NET pages.
Among the built-in HTTP handlers there are also Web service handler (*.asmx
) and Trace handler (trace.axd
)
MSDN says:
An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler.
The image below illustrates this:
As to your second question:
Does ashx handle more connections than aspx?
Don't think so (but for sure, at least not less than).
The fastest by a factor of 10 is to iterate over the arrays as if they are one, without actually joining them (if you can help it).
I was surprised that concat is slightly faster than push, unless the test is somehow unfair.
const arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
const arr2 = ['j', 'k', 'l', 'i', 'm', 'n', 'o', 'p', 'q', 'r', 's'];
const arr3 = ['t', 'u', 'v', 'w'];
const arr4 = ['x', 'y', 'z'];
let start;
// Not joining but iterating over all arrays - fastest
// at about 0.06ms
start = performance.now()
const joined = [arr1, arr2, arr3, arr4];
for (let j = 0; j < 1000; j++) {
let i = 0;
while (joined.length) {
// console.log(joined[0][i]);
if (i < joined[0].length - 1) i++;
else {
joined.shift()
i = 0;
}
}
}
console.log(performance.now() - start);
// Concating (0.51ms).
start = performance.now()
for (let j = 0; j < 1000; j++) {
const a = [].concat(arr1, arr2, arr3, arr4);
}
console.log(performance.now() - start);
// Pushing on to an array (mutating). Slowest (0.77ms)
start = performance.now()
const joined2 = [arr1, arr2, arr3, arr4];
for (let j = 0; j < 1000; j++) {
const arr = [];
for (let i = 0; i < joined2.length; i++) {
Array.prototype.push.apply(arr, joined2[i])
}
}
console.log(performance.now() - start);
_x000D_
You can make the iteration without joining cleaner if you abstract it and it's still twice as fast:
const arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
const arr2 = ['j', 'k', 'l', 'i', 'm', 'n', 'o', 'p', 'q', 'r', 's'];
const arr3 = ['t', 'u', 'v', 'w'];
const arr4 = ['x', 'y', 'z'];
function iterateArrays(arrays, onEach) {
let i = 0;
while (joined.length) {
onEach(joined[0][i]);
if (i < joined[0].length - 1) i++;
else {
joined.shift();
i = 0;
}
}
}
// About 0.23ms.
let start = performance.now()
const joined = [arr1, arr2, arr3, arr4];
for (let j = 0; j < 1000; j++) {
iterateArrays(joined, item => {
//console.log(item);
});
}
console.log(performance.now() - start);
_x000D_
Well it depends on the memory allocator implementation and the OS.
Under windows for example a process can ask for a page or more of RAM. The OS then assigns those pages to the process. This is not, however, memory allocated to your application. The CRT memory allocator will mark the memory as a contiguous "available" block. The CRT memory allocator will then run through the list of free blocks and find the smallest possible block that it can use. It will then take as much of that block as it needs and add it to an "allocated" list. Attached to the head of the actual memory allocation will be a header. This header will contain various bit of information (it could, for example, contain the next and previous allocated blocks to form a linked list. It will most probably contain the size of the allocation).
Free will then remove the header and add it back to the free memory list. If it forms a larger block with the surrounding free blocks these will be added together to give a larger block. If a whole page is now free the allocator will, most likely, return the page to the OS.
It is not a simple problem. The OS allocator portion is completely out of your control. I recommend you read through something like Doug Lea's Malloc (DLMalloc) to get an understanding of how a fairly fast allocator will work.
Edit: Your crash will be caused by the fact that by writing larger than the allocation you have overwritten the next memory header. This way when it frees it gets very confused as to what exactly it is free'ing and how to merge into the following block. This may not always cause a crash straight away on the free. It may cause a crash later on. In general avoid memory overwrites!
You can redirect the output of a cmd prompt to a file using >
or >>
to append to a file.
i.e.
echo Hello World >C:\output.txt
echo Hello again! >>C:\output.txt
or
mybatchfile.bat >C:\output.txt
Note that using >
will automatically overwrite the file if it already exists.
You also have the option of redirecting stdin, stdout and stderr.
See here for a complete list of options.
First you can use a Paginator. This is as simple as:
$allUsers = User::paginate(15);
$someUsers = User::where('votes', '>', 100)->paginate(15);
The variables will contain an instance of Paginator class. all of your data will be stored under data
key.
Or you can do something like:
Old versions Laravel.
Model::all()->take(10)->get();
Newer version Laravel.
Model::all()->take(10);
For more reading consider these links:
@GET
@Path("/test2")
public Response test2(){
List<String> list=new Vector<String>();
list.add("a");
list.add("b");
final GenericEntity<List<String>> entity = new GenericEntity<List<String>>(list) { };
return Response.ok().entity(entity).build();
}
Add a helper class:
public static class Redirector {
public static void RedirectTo(this Controller ct, string action) {
UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);
ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action));
}
public static void RedirectTo(this Controller ct, string action, string controller) {
UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);
ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action, controller));
}
public static void RedirectTo(this Controller ct, string action, string controller, object routeValues) {
UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);
ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action, controller, routeValues));
}
}
Then call in your action:
this.RedirectTo("Index", "Cement");
Add javascript code to any global javascript included file or layout file to intercept all ajax requests:
<script type="text/javascript">_x000D_
$(function() {_x000D_
$(document).ajaxComplete(function (event, xhr, settings) {_x000D_
var urlHeader = xhr.getResponseHeader('AjaxRedirectURL');_x000D_
_x000D_
if (urlHeader != null && urlHeader !== undefined) {_x000D_
window.location = xhr.getResponseHeader('AjaxRedirectURL');_x000D_
}_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
Here is the way to do it:
#!/bin/sh
abort()
{
echo >&2 '
***************
*** ABORTED ***
***************
'
echo "An error occurred. Exiting..." >&2
exit 1
}
trap 'abort' 0
set -e
# Add your script below....
# If an error occurs, the abort() function will be called.
#----------------------------------------------------------
# ===> Your script goes here
# Done!
trap : 0
echo >&2 '
************
*** DONE ***
************
'
# Dependencies
import numpy as np
import matplotlib.pyplot as plt
#Set Axes
# Set x axis to numerical value for month
x_axis_data = np.arange(1,13,1)
x_axis_data
# Average weather temp
points = [39, 42, 51, 62, 72, 82, 86, 84, 77, 65, 55, 44]
# Plot the line
plt.plot(x_axis_data, points)
plt.show()
# Convert to Celsius C = (F-32) * 0.56
points_C = [round((x-32) * 0.56,2) for x in points]
points_C
# Plot using Celsius
plt.plot(x_axis_data, points_C)
plt.show()
# Plot both on the same chart
plt.plot(x_axis_data, points)
plt.plot(x_axis_data, points_C)
#Line colors
plt.plot(x_axis_data, points, "-b", label="F")
plt.plot(x_axis_data, points_C, "-r", label="C")
#locate legend
plt.legend(loc="upper left")
plt.show()
dataGridView1.Rows.Clear();
dataGridView1.Refresh();
The below method is the implementation of binary divide considering both numbers are positive. If subtraction is a concern we can implement that as well using binary operators.
-(int)binaryDivide:(int)numerator with:(int)denominator
{
if (numerator == 0 || denominator == 1) {
return numerator;
}
if (denominator == 0) {
#ifdef DEBUG
NSAssert(denominator == 0, @"denominator should be greater then 0");
#endif
return INFINITY;
}
// if (numerator <0) {
// numerator = abs(numerator);
// }
int maxBitDenom = [self getMaxBit:denominator];
int maxBitNumerator = [self getMaxBit:numerator];
int msbNumber = [self getMSB:maxBitDenom ofNumber:numerator];
int qoutient = 0;
int subResult = 0;
int remainingBits = maxBitNumerator-maxBitDenom;
if (msbNumber >= denominator) {
qoutient |=1;
subResult = msbNumber - denominator;
}
else {
subResult = msbNumber;
}
while (remainingBits>0) {
int msbBit = (numerator & (1 << (remainingBits-1)))>0 ? 1 : 0;
subResult = (subResult << 1) |msbBit;
if (subResult >= denominator) {
subResult = subResult-denominator;
qoutient = (qoutient << 1) | 1;
}
else {
qoutient = qoutient << 1;
}
remainingBits--;
}
return qoutient;
}
-(int)getMaxBit:(int)inputNumber
{
int maxBit =0;
BOOL isMaxBitSet = NO;
for (int i=0; i<sizeof(inputNumber)*8; i++) {
if (inputNumber & (1 << i) ) {
maxBit = i;
isMaxBitSet=YES;
}
}
if (isMaxBitSet) {
maxBit += 1;
}
return maxBit;
}
-(int)getMSB:(int)bits ofNumber:(int)number
{
int numbeMaxBit = [self getMaxBit:number];
return number >> (numbeMaxBit -bits);
}
I tried as shown in the first answer. It works, but minus brought me into confusion. My answer by Groovy:
import static java.util.concurrent.TimeUnit.*
...
private static String formatElapsedTime(long millis) {
int hrs = MILLISECONDS.toHours(millis) % 24
int min = MILLISECONDS.toMinutes(millis) % 60
int sec = MILLISECONDS.toSeconds(millis) % 60
int mls = millis % 1000
sprintf( '%02d:%02d:%02d (%03d)', [hrs, min, sec, mls])
}
If you happen to apply migrations already this may fix it.
Go to your Web.config and update your connection string based on your migration files.
Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-GigHub-201802102244201.mdf;Initial Catalog=aspnet-GigHub-201802102244201;
The datestrings should match the first numbers on your Migrations.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date d = dateFormat.parse(datestring)
I had a similar problem of getting a black screen appear on sliding transition from one activity to another using overridependingtransition
. and I followed the way below and it worked
1) created a noanim.xml
in anim folder
<?xml version="1.0" encoding="utf-8"?>
<translate
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="@android:integer/config_longAnimTime"
android:fromYDelta="0%p"
android:toYDelta="0%p" />
and used
overridePendingTransition(R.drawable.lefttorightanim, R.anim.noanim);
The first parameter as my original animation and second parameter which is the exit animation as my dummy animation
This worked for me with Laravel 5.6.
In the file web.php
, just replace:
Auth::routes();
By:
//Auth::routes();
// Authentication Routes...
Route::get('admin/login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('admin/login', 'Auth\LoginController@login');
Route::post('admin/logout', 'Auth\LoginController@logout')->name('logout');
// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');
And remove the Register link in the two files below:
welcome.blade.php
layouts/app.blade.php
For new
you should use delete
. For new[]
use delete[]
. Your second variant is correct.
Leaving alone any debates over when (if ever) it should be done, @functions is how you do it.
@functions {
// Add code here.
}
Try this
Snackbar.make(findViewById(android.R.id.content), "Got the Result", Snackbar.LENGTH_LONG)
.setAction("Submit", mOnClickListener)
.setActionTextColor(Color.RED)
.show();
Just choose Grid system
and "responsive utilities"
it gives you this: http://jsfiddle.net/7LVzs/
I simplified @Michael Kropats solution and made a LINQ-esque version.
string RandomString(int length, string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
{
var outOfRange = byte.MaxValue + 1 - (byte.MaxValue + 1) % alphabet.Length;
return string.Concat(
Enumerable
.Repeat(0, int.MaxValue)
.Select(e => RandomByte())
.Where(randomByte => randomByte < outOfRange)
.Take(length)
.Select(randomByte => alphabet[randomByte % alphabet.Length])
);
}
byte RandomByte()
{
using (var randomizationProvider = new RNGCryptoServiceProvider())
{
var randomBytes = new byte[1];
randomizationProvider.GetBytes(randomBytes);
return randomBytes.Single();
}
}
Found this thread when trying (unsuccessfully) to load a local json file. This solution worked for me...
function load_json(src) {
var head = document.getElementsByTagName('head')[0];
//use class, as we can't reference by id
var element = head.getElementsByClassName("json")[0];
try {
element.parentNode.removeChild(element);
} catch (e) {
//
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
script.className = "json";
script.async = false;
head.appendChild(script);
//call the postload function after a slight delay to allow the json to load
window.setTimeout(postloadfunction, 100)
}
... and is used like this...
load_json("test2.html.js")
...and this is the <head>
...
<head>
<script type="text/javascript" src="test.html.js" class="json"></script>
</head>
This works for me :D
@Override
public void onResume() {
super.onResume();
if(getView() == null){
return;
}
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
// handle back button's click listener
return true;
}
return false;
}
});}
I use:
from pathlib import Path
import platform
import tempfile
tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())
This is because on MacOS, i.e. Darwin, tempfile.gettempdir()
and os.getenv('TMPDIR')
return a value such as '/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T'
; it is one that I do not always want.
You have two options:
Either use:
sb.setLength(0); // It will just discard the previous data, which will be garbage collected later.
Or use:
sb.delete(0, sb.length()); // A bit slower as it is used to delete sub sequence.
Avoid declaring StringBuffer
or StringBuilder
objects within the loop else it will create new objects with each iteration. Creating of objects requires system resources, space and also takes time. So for long run, avoid declaring them within a loop if possible.
If the first segment doesn't start with /
it is a relative route. router.navigate
needs a relativeTo
parameter for relative navigation
Either you make the route absolute:
this.router.navigate(['/foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)
or you pass relativeTo
this.router.navigate(['../foo-content', 'bar-contents', 'baz-content', 'page'], {queryParams: this.params.queryParams, relativeTo: this.currentActivatedRoute})
See also
You can change the user with
Subversion 1.6 and earlier:
svn switch --relocate protocol://currentUser@server/path protocol://newUser@server/path
Subversion 1.7 and later:
svn relocate protocol://currentUser@server/path protocol://newUser@server/path
To find out what protocol://currentUser@server/path
is, run
svn info
in your working copy.
Yet another solution is to use Google's Guava
import com.google.common.collect.Table;
import com.google.common.collect.HashBasedTable;
Table<String, String, Integer> table = HashBasedTable.create();
The usage is really simple:
String row = "a";
String column = "b";
int value = 1;
if (!table.contains(row, column)) {
table.put(row, column, value);
}
System.out.println("value = " + table.get(row, column));
The method HashBasedTable.create()
is basically doing something like this:
Table<String, String, Integer> table = Tables.newCustomTable(
Maps.<String, Map<String, Integer>>newHashMap(),
new Supplier<Map<String, Integer>>() {
public Map<String, Integer> get() {
return Maps.newHashMap();
}
});
if you're trying to create some custom maps, you should go for the second option (as @Karatheodory suggests) otherwise you should be fine with the first one.
select persons.personsid,name,info.id,address
-> from persons
-> inner join persons on info.infoid = info.info.id;
Simply casting the string as an int
won't work reliably. You need to convert it to an int32
. For this you can use the .NET convert
class and its ToInt32
method. The method requires a string
($strNum
) as the main input, and the base number
(10
) for the number system to convert to. This is because you can not only convert to the decimal system (the 10
base number), but also to, for example, the binary system (base 2).
Give this method a try:
[string]$strNum = "1.500"
[int]$intNum = [convert]::ToInt32($strNum, 10)
$intNum
<ul id="unOrderedList">
<li value="2">Whatever</li>
.
.
$('#unOrderedList li').click(function(){
var value = $(this).attr('value');
alert(value);
});
Your looking for the attribute "value" inside the "li" tag
Expect is built for this and can handle the input/output plus timeouts etc. Note that if you're not a TCL fan, there are Expect modules for Perl/Python/Java.
EDIT: The above page suggests that the Wikipedia Expect entry is a useful resource :-)
For linuxes I've figured out that ECU could be measured by sysbench:
sysbench --num-threads=128 --test=cpu --cpu-max-prime=50000 --max-requests=50000 run
Total time (t) should be calculated by formula:
ECU=1925/t
And my example test results:
| instance type | time | ECU |
|-------------------|----------|---------|
| m1.small | 1735,62 | 1 |
| m3.xlarge | 147,62 | 13 |
| m3.2xlarge | 74,61 | 26 |
| r3.large | 295,84 | 7 |
| r3.xlarge | 148,18 | 13 |
| m4.xlarge | 146,71 | 13 |
| m4.2xlarge | 73,69 | 26 |
| c4.xlarge | 123,59 | 16 |
| c4.2xlarge | 61,91 | 31 |
| c4.4xlarge | 31,14 | 62 |
I remember my CompSci professor saying never to use floats for currency.
The reason for that is how the IEEE specification defines floats in binary format. Basically, it stores sign, fraction and exponent to represent a Float. It's like a scientific notation for binary (something like +1.43*10^2
). Because of that, it is impossible to store fractions and decimals in Float exactly.
That's why there is a Decimal format. If you do this:
irb:001:0> "%.47f" % (1.0/10)
=> "0.10000000000000000555111512312578270211815834045" # not "0.1"!
whereas if you just do
irb:002:0> (1.0/10).to_s
=> "0.1" # the interprer rounds the number for you
So if you are dealing with small fractions, like compounding interests, or maybe even geolocation, I would highly recommend Decimal format, since in decimal format 1.0/10
is exactly 0.1.
However, it should be noted that despite being less accurate, floats are processed faster. Here's a benchmark:
require "benchmark"
require "bigdecimal"
d = BigDecimal.new(3)
f = Float(3)
time_decimal = Benchmark.measure{ (1..10000000).each { |i| d * d } }
time_float = Benchmark.measure{ (1..10000000).each { |i| f * f } }
puts time_decimal
#=> 6.770960 seconds
puts time_float
#=> 0.988070 seconds
Use float when you don't care about precision too much. For example, some scientific simulations and calculations only need up to 3 or 4 significant digits. This is useful in trading off accuracy for speed. Since they don't need precision as much as speed, they would use float.
Use decimal if you are dealing with numbers that need to be precise and sum up to correct number (like compounding interests and money-related things). Remember: if you need precision, then you should always use decimal.
Additionally if you want to know which extensions are available on your server: SELECT * FROM pg_available_extensions
For applications such as Squirrel SQL Client (http://squirrel-sql.sourceforge.net/) version 4 you can set "serverTimezone" under "driver properties" to GMT+1
(example of timezone "Europe/Vienna).
Use related name to count votes for a specific contest
class Item(models.Model):
name = models.CharField()
class Contest(models.Model);
name = models.CharField()
class Votes(models.Model):
user = models.ForeignKey(User)
item = models.ForeignKey(Item)
contest = models.ForeignKey(Contest, related_name="contest_votes")
comment = models.TextField()
>>> comments = Contest.objects.get(id=contest_id).contest_votes.count()
First of all, the provided long code:
<xsl:choose>
<xsl:when test="OU_NAME='OU_ADDR1'"> --comparing two elements coming from XML
<!--remove if adrees already contain operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="OU_NAME"/>
<fo:block/>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:otherwise>
</xsl:choose>
is equivalent to this, much shorter code:
<xsl:if test="not(OU_NAME='OU_ADDR1)'">
<xsl:value-of select="OU_NAME"/>
</xsl:if>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
Now, to your question:
how to compare two elements coming from xml as string
In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator =
and the function not()
together with the operator =
.
$str1 = $str2
evaluates to true()
exactly when the string $str1
is equal to the string $str2
.
not($str1 = $str2)
evaluates to true()
exactly when the string $str1
is not equal to the string $str2
.
There is also the !=
operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.
Now, the rules for comparing two element nodes are similar:
$el1 = $el2
evaluates to true()
exactly when the string value of $el1
is equal to the string value of $el2
.
not($el1 = $el2)
evaluates to true()
exactly when the string value of $el1
is not equal to the string value of $el2
.
However, if one of the operands of =
is a node-set, then
$ns = $str
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string $str
$ns1 = $ns2
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string value of some node from $ns2
Therefore, the expression:
OU_NAME='OU_ADDR1'
evaluates to true()
only when there is at least one element child of the current node that is named OU_NAME
and whose string value is the string 'OU_ADDR1'.
This is obviously not what you want!
Most probably you want:
OU_NAME=OU_ADDR1
This expression evaluates to true
exactly there is at least one OU_NAME
child of the current node and one OU_ADDR1
child of the current node with the same string value.
Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt
, le
, eq
, gt
, ge
and the inherited from XPath 1.0 general comparison operator =
.
Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.
For these bulky reads from DB you may want to tune your Statement's fetch size. It might save a lot of roundtrips to DB.
http://download.oracle.com/javase/1.5.0/docs/api/java/sql/Statement.html#setFetchSize%28int%29
I would personally prefer using "\n". This just puts a line break in Linux or Android.
For example,
String str = "I am the first part of the info being emailed.\nI am the second part.\n\nI am the third part.";
Output
I am the first part of the info being emailed.
I am the second part.
I am the third part.
A more generalized way would be to use,
System.getProperty("line.separator")
For example,
String str = "I am the first part of the info being emailed." + System.getProperty("line.separator") + "I am the second part." + System.getProperty("line.separator") + System.getProperty("line.separator") + "I am the third part.";
brings the same output as above. Here, the static getProperty()
method of the System
class can be used to get the "line.seperator
" for the particular OS.
But this is not necessary at all, as the OS here is fixed, that is, Android. So, calling a method every time is a heavy and unnecessary operation.
Moreover, this also increases your code length and makes it look kind of messy. A "\n" is sweet and simple.
Building on the answer from alex2k8, here's a revised version that works in all browsers that jQuery supports (the problem was in missing arguments to jQuery.event.trigger, which is easy to forget when using that internal function).
// jQuery plugin. Called on a jQuery object, not directly.
jQuery.fn.simulateKeyPress = function (character) {
// Internally calls jQuery.event.trigger with arguments (Event, data, elem).
// That last argument, 'elem', is very important!
jQuery(this).trigger({ type: 'keypress', which: character.charCodeAt(0) });
};
jQuery(function ($) {
// Bind event handler
$('body').keypress(function (e) {
alert(String.fromCharCode(e.which));
console.log(e);
});
// Simulate the key press
$('body').simulateKeyPress('x');
});
You could even push this further and let it not only simulate the event but actually insert the character (if it is an input element), however there are many cross-browser gotcha's when trying to do that. Better use a more elaborate plugin like SendKeys.
The concept of static constructors was introduced in Java after they learned from the problems in C++. So we have no direct equivalent.
The best solution is to use POD types that can be initialised explicitly.
Or make your static members a specific type that has its own constructor that will initialize it correctly.
//header
class A
{
// Make sure this is private so that nobody can missues the fact that
// you are overriding std::vector. Just doing it here as a quicky example
// don't take it as a recomendation for deriving from vector.
class MyInitedVar: public std::vector<char>
{
public:
MyInitedVar()
{
// Pre-Initialize the vector.
for(char c = 'a';c <= 'z';++c)
{
push_back(c);
}
}
};
static int count;
static MyInitedVar var1;
};
//source
int A::count = 0;
A::MyInitedVar A::var1;
Some disassembly is always interesting...
$ cat Test.java
public class Test {
public static void main(String... args) {
String abc = "abc";
String def = new String("def");
}
}
$ javap -c -v Test
Compiled from "Test.java"
public class Test extends java.lang.Object
SourceFile: "Test.java"
minor version: 0
major version: 50
Constant pool:
const #1 = Method #7.#16; // java/lang/Object."<init>":()V
const #2 = String #17; // abc
const #3 = class #18; // java/lang/String
const #4 = String #19; // def
const #5 = Method #3.#20; // java/lang/String."<init>":(Ljava/lang/String;)V
const #6 = class #21; // Test
const #7 = class #22; // java/lang/Object
const #8 = Asciz <init>;
...
{
public Test(); ...
public static void main(java.lang.String[]);
Code:
Stack=3, Locals=3, Args_size=1
0: ldc #2; // Load string constant "abc"
2: astore_1 // Store top of stack onto local variable 1
3: new #3; // class java/lang/String
6: dup // duplicate top of stack
7: ldc #4; // Load string constant "def"
9: invokespecial #5; // Invoke constructor
12: astore_2 // Store top of stack onto local variable 2
13: return
}
The get/set pattern provides a structure that allows logic to be added during the setting ('set') or retrieval ('get') of a property instance of an instantiated class, which can be useful when some instantiation logic is required for the property.
A property can have a 'get' accessor only, which is done in order to make that property read-only
When implementing a get/set pattern, an intermediate variable is used as a container into which a value can be placed and a value extracted. The intermediate variable is usually prefixed with an underscore. this intermediate variable is private in order to ensure that it can only be accessed via its get/set calls. See the answer from Brandon, as his answer demonstrates the most commonly used syntax conventions for implementing get/set.
I am so glad to solve this problem:
HttpPost httppost = new HttpPost(postData);
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", getSessionId());
//cookie.setDomain("your domain");
cookie.setPath("/");
cookieStore.addCookie(cookie);
client.setCookieStore(cookieStore);
response = client.execute(httppost);
So Easy!
Just 2 things I think make it ALWAYS preferable to use a # Temp Table rather then a CTE are:
You can not put a primary key on a CTE so the data being accessed by the CTE will have to traverse each one of the indexes in the CTE's tables rather then just accessing the PK or Index on the temp table.
Because you can not add constraints, indexes and primary keys to a CTE they are more prone to bugs creeping in and bad data.
-onedaywhen yesterday
Here is an example where #table constraints can prevent bad data which is not the case in CTE's
DECLARE @BadData TABLE (
ThisID int
, ThatID int );
INSERT INTO @BadData
( ThisID
, ThatID
)
VALUES
( 1, 1 ),
( 1, 2 ),
( 2, 2 ),
( 1, 1 );
IF OBJECT_ID('tempdb..#This') IS NOT NULL
DROP TABLE #This;
CREATE TABLE #This (
ThisID int NOT NULL
, ThatID int NOT NULL
UNIQUE(ThisID, ThatID) );
INSERT INTO #This
SELECT * FROM @BadData;
WITH This_CTE
AS (SELECT *
FROM @BadData)
SELECT *
FROM This_CTE;
I like to use Optional and streams to have a net and clear solution, i use the below code to iterate over a directory. the below cases are handled by the code:
but as mentioned by others, you still have to pay attention for outOfMemory in case you have huge folders
File directoryFile = new File("put your path here");
Stream<File> files = Optional.ofNullable(directoryFile// directoryFile
.listFiles(File::isDirectory)) // filter only directories(change with null if you don't need to filter)
.stream()
.flatMap(Arrays::stream);// flatmap from Stream<File[]> to Stream<File>
In the old days (you know, anytime before yesterday) a PC's BIOS timer would "tick" at a certain interval. That interval would be on the order of 12 milliseconds. Thus, it's quite easy to perform two consecutive calls to get the time and have them return a difference of zero. This only means that the timer didn't "tick" between your two calls. Try getting the time in a loop and displaying the values to the console. If your PC and display are fast enough, you'll see that time jumps, making it look as though it's quantized! (Einstein would be upset!) Newer PCs also have a high resolution timer. I'd imagine that nanoTime() uses the high resolution timer.
Since the outer div only contains floated divs, it renders with 0 height. Either give it a height or set its overflow to hidden.
I know this is silly, but in my case while I was getting the same error message, just changing the USB cable used to connect the device fixed the problem :O
Perhaps this might benefit someone else as well?!
I know this post is old but i want to add a few points to this!
you can try
vagrant ssh -c "ifconfig | grep inet" hostname
this will be easy if you have setup a name to your guests individually!
These are the primitive types in Java:
All the other types are reference types: they reference objects.
This is the first part of the Java tutorial about the basics of the language.
.gitconfig
using a personal access tokenIf you do not want to modify your host file, use SSH keys, or setup a .gitconfig
for each repo, then you may use a personal .gitconfig
that you basically include from the root level config. Given an OSX directory structure like
# root level git config
~/.gitconfig
# your personal repos under some folder like
../personal/
../home/
~/Dropbox/
Add a .gitconfig
in your personal folder, such as ~/Dropbox/.gitconfig
[user]
email = [email protected]
name = First Last
[credential]
username = PersonalGithubUsername
helper = osxkeychain
In your root level .gitconfig
add an includeIf section to source your personal config whenever you are in your personal directory. Any settings there will override the root config as long as the includeIf
comes after the settings you want to override.
[user]
email = [email protected]
name = "First Last"
[credential]
helper = osxkeychain
[includeIf "gitdir:~/Dropbox/**"]
path = ~/Dropbox/.gitconfig
Try pushing to your personal repo or pulling from your private repo
git push
# prompts for password
When prompted enter either your personal password or, better yet, your personal access token that you have created in your account developer settings. Enter that token as your password.
Assuming you are already using git-credential-osxkeychain, your personal credentials should be stored in your keychain, so two github
entries will show up, but with different accounts.
Here's some code. This assumes you are doing this on a form, or a UserControl.
Graphics g = this.CreateGraphics();
SizeF size = g.MeasureString("string to measure");
int nLeft = Convert.ToInt32((this.ClientRectangle.Width / 2) - (size.Width / 2));
int nTop = Convert.ToInt32((this.ClientRectangle.Height / 2) - (size.Height / 2));
From your post, it sounds like the ClientRectangle part (as in, you're not using it) is what's giving you difficulty.
There are two commands which will work in this situation,
root>git reset --hard HEAD~1
root>git push -f
For more git commands refer this page
To everyone who said that this is a bad idea I want to say it is not always a bad one. Sometimes it is very boring to have to zoom out to see all the content. For example when you type on an input on iOS it zooms to get it in the center of the screen. You have to zoom out after that cause closing the keyboard does not do the work. Also I agree that when you put many I hours in making a great layout and user experience you don't want it to be messed up by a zoom.
But the other argument is valuable as well for people with vision issues. However In my opinion if you have issues with your eyes you are already using the zooming features of the system so there is no need to disturb the content.
simple / elegant / how I do it:
Preview:
XML:
<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/btn_dropdown"
android:spinnerMode="dropdown"/>
spinnerMode
set to dropdown
is androids way to make a dropdown. (https://developer.android.com/reference/android/widget/Spinner#attr_android:spinnerMode)
Java:
//get the spinner from the xml.
Spinner dropdown = findViewById(R.id.spinner1);
//create a list of items for the spinner.
String[] items = new String[]{"1", "2", "three"};
//create an adapter to describe how the items are displayed, adapters are used in several places in android.
//There are multiple variations of this, but this is the basic variant.
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
//set the spinners adapter to the previously created one.
dropdown.setAdapter(adapter);
Documentation:
This is the basics but there is more to be self taught with experimentation. https://developer.android.com/guide/topics/ui/controls/spinner.html
Well, first you need to select the elements with a function like getElementById
.
var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];
getElementById
only returns one node, but getElementsByClassName
returns a node list. Since there is only one element with that class name (as far as I can tell), you can just get the first one (that's what the [0]
is for—it's just like an array).
Then, you can change the html with .textContent
.
targetDiv.textContent = "Goodbye world!";
var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];_x000D_
targetDiv.textContent = "Goodbye world!";
_x000D_
<div id="foo">_x000D_
<div class="bar">_x000D_
Hello world!_x000D_
</div>_x000D_
</div>
_x000D_
This is for view controller reusability.
Your view controller shouldn't care if it is being presented as a modal, pushed on a navigation controller, or whatever. If your view controller dismisses itself, then you're assuming it is being presented modally. You won't be able to push that view controller onto a navigation controller.
By implementing a protocol, you let the parent view controller decide how it should be presented/pushed and dismissed/popped.
Fetch the remote branch from the origin first.
git fetch origin remote_branch_name
Merge the remote branch to the local branch
git merge origin/remote_branch_name
An update to @Brandon's answer, generalized to a method
- (NSString*) postToUrl:(NSString*)urlString data:(NSData*)dataToSend withFilename:(NSString*)filename
{
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:dataToSend]];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
NSError* error;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
if (returnData) {
return [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
}
else {
return nil;
}
}
Invoke like so, sending data from a string:
[self postToUrl:@"<#Your url string#>"
data:[@"<#Your string to send#>" dataUsingEncoding:NSUTF8StringEncoding]
withFilename:@"<#Filename to post with#>"];
You could use Guava Ranges
You can get a SortedSet
by using
ImmutableSortedSet<Integer> set = Ranges.open(1, 5).asSet(DiscreteDomains.integers());
// set contains [2, 3, 4]
Here are the steps I followed to recover from a corrupt blob object.
1) Identify corrupt blob
git fsck --full
error: inflate: data stream error (incorrect data check)
error: sha1 mismatch 241091723c324aed77b2d35f97a05e856b319efd
error: 241091723c324aed77b2d35f97a05e856b319efd: object corrupt or missing
...
Corrupt blob is 241091723c324aed77b2d35f97a05e856b319efd
2) Move corrupt blob to a safe place (just in case)
mv .git/objects/24/1091723c324aed77b2d35f97a05e856b319efd ../24/
3) Get parent of corrupt blob
git fsck --full
Checking object directories: 100% (256/256), done.
Checking objects: 100% (70321/70321), done.
broken link from tree 0716831e1a6c8d3e6b2b541d21c4748cc0ce7180
to blob 241091723c324aed77b2d35f97a05e856b319efd
Parent hash is 0716831e1a6c8d3e6b2b541d21c4748cc0ce7180.
4) Get file name corresponding to corrupt blob
git ls-tree 0716831e1a6c8d3e6b2b541d21c4748cc0ce7180
...
100644 blob 241091723c324aed77b2d35f97a05e856b319efd dump.tar.gz
...
Find this particular file in a backup or in the upstream git repository (in my case it is dump.tar.gz). Then copy it somewhere inside your local repository.
5) Add previously corrupted file in the git object database
git hash-object -w dump.tar.gz
6) Celebrate!
git gc
Counting objects: 75197, done.
Compressing objects: 100% (21805/21805), done.
Writing objects: 100% (75197/75197), done.
Total 75197 (delta 52999), reused 69857 (delta 49296)
ComputerDruid's answer is great but I don't think it's necessary to set upstream manually unless you want to. I'm adding this answer because people might think that that's a necessary step.
This error will be gone if you specify the remote that you want to pull like below:
git pull origin master
Note that origin
is the name of the remote and master
is the branch name.
1) How to check remote's name
git remote -v
2) How to see what branches available in the repository.
git branch -r
you can use the following command line:
java -jar -Dspring.profiles.active=[yourProfileName] target/[yourJar].jar
There are three different font families that I know of that you can choose from and each has its own weight element that needs to be applied:
First
font-family: 'Font Awesome 5 Brands';
content: "\f373";
Second
font-family: 'Font Awesome 5 Free';
content: "\f061";
font-weight: 900;
Third
font-family: 'Font Awesome 5 Pro';
Reference here - https://fontawesome.com/how-to-use/on-the-web/advanced/css-pseudo-elements
Hope this helps.
Because you didn't tell the linker about location of math library. Compile with gcc test.c -o test -lm
You can name cells. This is done by clicking the Name Box (that thing next to the formula bar which says "A1" for example) and typing a name, such as, "myvar". Now you can use that name instead of the cell reference:
= myvar*25
You can get MinGW (as others have suggested) but I would recommend getting a simple IDE (not VS Express). You can try Dev C++ http://www.bloodshed.net/devcpp.html Its a simple IDE for C/C++ and uses MinGW internally. In this you can write and compile single C files without creating a full-blown "project".
I just closed all open chrome instances, stopped my project and then start it again. that fixed the problem for me.
The String
class has a Replace
method that will do that.
Dim clean as String
clean = myString.Replace(",", "")
You can put a meta refresh Tag in the irc_online.php
<meta http-equiv="refresh" content="30">
OR you can use Javascript with setInterval to refresh the src of the Source...
<script>
window.setInterval("reloadIFrame();", 30000);
function reloadIFrame() {
document.frames["frameNameHere"].location.reload();
}
</script>
I have to agree with Tobias. The error is too generic. When the same thing happened to me I dug into the error message and realized I'd screwed up something in the build properties, but not the code signing. So yeah, I'd dig in to the details.
Propably this would do it for you.
$('input').val('').removeAttr('checked').removeAttr('selected');
Resizing the icon is not straightforward. You need to use Java's graphics 2D to scale the image. The first parameter is a Image class which you can easily get from ImageIcon
class. You can use ImageIcon
class to load your image file and then simply call getter method to get the image.
private Image getScaledImage(Image srcImg, int w, int h){
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImg, 0, 0, w, h, null);
g2.dispose();
return resizedImg;
}
For me this error occurred simply because I forgot tell Eclipse that I wanted a runnable jar file and not a simple library jar file. So when you create the jar file in Eclipse make sure that you click the right radio button
An easy way to print the sorted contents of the dictionary, in Python 3:
>>> dict_example = {'c': 1, 'b': 2, 'a': 3}
>>> for key, value in sorted(dict_example.items()):
... print("{} : {}".format(key, value))
...
a : 3
b : 2
c : 1
The expression dict_example.items()
returns tuples, which can then be sorted by sorted()
:
>>> dict_example.items()
dict_items([('c', 1), ('b', 2), ('a', 3)])
>>> sorted(dict_example.items())
[('a', 3), ('b', 2), ('c', 1)]
Below is an example to pretty print the sorted contents of a Python dictionary's values.
for key, value in sorted(dict_example.items(), key=lambda d_values: d_values[1]):
print("{} : {}".format(key, value))
The current version of Mongoose (v4.x) has time stamping as a built-in option to a schema:
var mySchema = new mongoose.Schema( {name: String}, {timestamps: true} );
This option adds createdAt
and updatedAt
properties that are timestamped with a Date
, and which does all the work for you. Any time you update the document, it updates the updatedAt
property. Schema Timestamps Docs.
R treats backslashes as escape values for character constants. (... and so do regular expressions. Hence the need for two backslashes when supplying a character argument for a pattern. The first one isn't actually a character, but rather it makes the second one into a character.) You can see how they are processed using cat
.
y <- "double quote: \", tab: \t, newline: \n, unicode point: \u20AC"
print(y)
## [1] "double quote: \", tab: \t, newline: \n, unicode point: €"
cat(y)
## double quote: ", tab: , newline:
## , unicode point: €
Further reading: Escaping a backslash with a backslash in R produces 2 backslashes in a string, not 1
To use special characters in a regular expression the simplest method is usually to escape them with a backslash, but as noted above, the backslash itself needs to be escaped.
grepl("\\[", "a[b")
## [1] TRUE
To match backslashes, you need to double escape, resulting in four backslashes.
grepl("\\\\", c("a\\b", "a\nb"))
## [1] TRUE FALSE
The rebus
package contains constants for each of the special characters to save you mistyping slashes.
library(rebus)
OPEN_BRACKET
## [1] "\\["
BACKSLASH
## [1] "\\\\"
For more examples see:
?SpecialCharacters
Your problem can be solved this way:
library(rebus)
grepl(OPEN_BRACKET, "a[b")
You can also wrap the special characters in square brackets to form a character class.
grepl("[?]", "a?b")
## [1] TRUE
Two of the special characters have special meaning inside character classes: \
and ^
.
Backslash still needs to be escaped even if it is inside a character class.
grepl("[\\\\]", c("a\\b", "a\nb"))
## [1] TRUE FALSE
Caret only needs to be escaped if it is directly after the opening square bracket.
grepl("[ ^]", "a^b") # matches spaces as well.
## [1] TRUE
grepl("[\\^]", "a^b")
## [1] TRUE
rebus
also lets you form a character class.
char_class("?")
## <regex> [?]
If you want to match all punctuation, you can use the [:punct:]
character class.
grepl("[[:punct:]]", c("//", "[", "(", "{", "?", "^", "$"))
## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE
stringi
maps this to the Unicode General Category for punctuation, so its behaviour is slightly different.
stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "[[:punct:]]")
## [1] TRUE TRUE TRUE TRUE TRUE FALSE FALSE
You can also use the cross-platform syntax for accessing a UGC.
stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "\\p{P}")
## [1] TRUE TRUE TRUE TRUE TRUE FALSE FALSE
Placing characters between \\Q
and \\E
makes the regular expression engine treat them literally rather than as regular expressions.
grepl("\\Q.\\E", "a.b")
## [1] TRUE
rebus
lets you write literal blocks of regular expressions.
literal(".")
## <regex> \Q.\E
Regular expressions are not always the answer. If you want to match a fixed string then you can do, for example:
grepl("[", "a[b", fixed = TRUE)
stringr::str_detect("a[b", fixed("["))
stringi::stri_detect_fixed("a[b", "[")
public class GetFilesRecursive {
public static List <String> getFilesRecursively(File dir){
List <String> ls = new ArrayList<String>();
for (File fObj : dir.listFiles()) {
if(fObj.isDirectory()) {
ls.add(String.valueOf(fObj));
ls.addAll(getFilesRecursively(fObj));
} else {
ls.add(String.valueOf(fObj));
}
}
return ls;
}
public static List <String> getListOfFiles(String fullPathDir) {
List <String> ls = new ArrayList<String> ();
File f = new File(fullPathDir);
if (f.exists()) {
if(f.isDirectory()) {
ls.add(String.valueOf(f));
ls.addAll(getFilesRecursively(f));
}
} else {
ls.add(fullPathDir);
}
return ls;
}
public static void main(String[] args) {
List <String> ls = getListOfFiles("/Users/srinivasab/Documents");
for (String file:ls) {
System.out.println(file);
}
System.out.println(ls.size());
}
}
Try:
next(g)
Check out this neat table that shows the differences in syntax between 2 and 3 when it comes to this.
Drag and drop apk if the emulator is launched from Android Studio. If the emulator is started from command line, drag and drop doesn't work, but @Tarek K. Ajaj instructions (above) work.
Note: Installed app won't automatically appear on the home screen, it is in the apps container - the dotted grid icon. It can be dragged from there to the home screen.
If you don't want your data to be seen by the user, use a PHP session.
Data in a post request is still accessible (and manipulable) by the user.
Checkout this tutorial on PHP Sessions.
I would recommend using PATCH, because your resource 'group' has many properties but in this case, you are updating only the activation field(partial modification)
according to the RFC5789 (https://tools.ietf.org/html/rfc5789)
The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.
Also, in more details,
The difference between the PUT and PATCH requests is reflected in the way the server processes the enclosed entity to modify the resource
identified by the Request-URI. In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the
origin server, and the client is requesting that the stored version
be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the
origin server should be modified to produce a new version. The PATCH method affects the resource identified by the Request-URI, and it
also MAY have side effects on other resources; i.e., new resources
may be created, or existing ones modified, by the application of a
PATCH.PATCH is neither safe nor idempotent as defined by [RFC2616], Section 9.1.
Clients need to choose when to use PATCH rather than PUT. For
example, if the patch document size is larger than the size of the
new resource data that would be used in a PUT, then it might make
sense to use PUT instead of PATCH. A comparison to POST is even more difficult, because POST is used in widely varying ways and can
encompass PUT and PATCH-like operations if the server chooses. If
the operation does not modify the resource identified by the Request- URI in a predictable way, POST should be considered instead of PATCH
or PUT.
The response code for PATCH is
The 204 response code is used because the response does not carry a message body (which a response with the 200 code would have). Note that other success codes could be used as well.
also refer thttp://restcookbook.com/HTTP%20Methods/patch/
Caveat: An API implementing PATCH must patch atomically. It MUST not be possible that resources are half-patched when requested by a GET.
To clarify, a database created under SQL Server 2008 R2 was being opened in an instance of SQL Server 2008 (the version prior to R2). The solution for me was to simply perform an upgrade installation of SQL Server 2008 R2. I can only speak for the Express edition, but it worked.
Oddly, though, the Web Platform Installer indicated that I had Express R2 installed. The better way to tell is to ask the database server itself:
SELECT @@VERSION
update YourTable
set YourColumn = replace(YourColumn, '@domain2', '@domain1')
where charindex('@domain2', YourColumn) <> 0
I would also like to add something here that if you load desired form that contain tooltip controll before the program's run then tool tip control on that form will not work as described below...
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
objfrmmain = new Frm_Main();
Showtop();//this is procedure in program.cs to load an other form, so if that contain's tool tip control then it will not work
Application.Run(objfrmmain);
}
so I solved this problem by puting following code in Fram_main_load event procedure like this
private void Frm_Main_Load(object sender, EventArgs e)
{
Program.Showtop();
}
PYSPARK
In the below code, df
is the name of dataframe. 1st parameter is to show all rows in the dataframe dynamically rather than hardcoding a numeric value. The 2nd parameter will take care of displaying full column contents since the value is set as False
.
df.show(df.count(),False)
SCALA
In the below code, df
is the name of dataframe. 1st parameter is to show all rows in the dataframe dynamically rather than hardcoding a numeric value. The 2nd parameter will take care of displaying full column contents since the value is set as false
.
df.show(df.count().toInt,false)
Pass the object as is to the class constructor; No conventions or checks
interface iPerson {
name: string;
age: number;
}
class Person {
constructor(private person: iPerson) { }
toString(): string {
return this.person.name + ' is ' + this.person.age;
}
}
// runs this as //
const object1 = { name: 'Watson1', age: 64 };
const object2 = { name: 'Watson2' }; // age is missing
const person1 = new Person(object1);
const person2 = new Person(object2 as iPerson); // now matches constructor
console.log(person1.toString()) // Watson1 is 64
console.log(person2.toString()) // Watson2 is undefined
You should try this one :
task getDeps(type: Copy) {
from configurations.runtime
into 'runtime/'
}
I was was looking for it some time ago when working on a project in which we had to download all dependencies into current working directory at some point in our provisioning script. I guess you're trying to achieve something similar.
table_ages <- subset(infert, select=c("age"))
summary(table_ages)
# age
# Min. :21.00
# 1st Qu.:28.00
# Median :31.00
# Mean :31.50
# 3rd Qu.:35.25
# Max. :44.00
This is probably what they're looking for. summary(...)
applied to a numeric returns the min, max, mean, median, and 25th and 75th percentile of the data.
Note that
summary(infert$age)
# Min. 1st Qu. Median Mean 3rd Qu. Max.
# 21.00 28.00 31.00 31.50 35.25 44.00
The numbers are the same but the format is different. This is because table_ages
is a data frame with one column (ages), whereas infert$age
is a numeric vector. Try typing summary(infert)
.
require 'rubygems'
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :ie
driver.get "https://www.google.com"
driver.save_screenshot("./screen.png")
More file types and options are available and you can see them in file takes_screenshot.rb.
you can write events on elements like chain,
$(element).on('click',function(){
//action on click
}).on('mouseup',function(){
//action on mouseup (just before click event)
});
i've used it for removing cart items. same object, doing some action, after another action
From the jQuery documentation - http://api.jquery.com/jQuery.ajax/
contentType When sending data to the server, use this content type.
dataType The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response
"text": A plain text string.
So you want contentType to be application/json
and dataType to be text
:
$.ajax({
type : "POST",
url : /v1/user,
dataType : "text",
contentType: "application/json",
data : dataAttribute,
success : function() {
},
error : function(error) {
}
});
The simplest way to produce these dummy variables is something like the following:
> print(year)
[1] 1956 1957 1957 1958 1958 1959
> dummy <- as.numeric(year == 1957)
> print(dummy)
[1] 0 1 1 0 0 0
> dummy2 <- as.numeric(year >= 1957)
> print(dummy2)
[1] 0 1 1 1 1 1
More generally, you can use ifelse
to choose between two values depending on a condition. So if instead of a 0-1 dummy variable, for some reason you wanted to use, say, 4 and 7, you could use ifelse(year == 1957, 4, 7)
.
You can use Stack
to make the image stretch to the full screen.
Stack(
children: <Widget>
[
Positioned.fill( //
child: Image(
image: AssetImage('assets/placeholder.png'),
fit : BoxFit.fill,
),
),
...... // other children widgets of Stack
..........
.............
]
);
Note: Optionally if are using a Scaffold
, you can put the Stack
inside the Scaffold
with or without AppBar
according to your needs.
Start with this:
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(path)) Then
msg = path & " exists."
Else
msg = path & " doesn't exist."
End If
Taken from the documentation.
Thanks a lot for your link to the requests module. It's just perfect. Below the solution to my problem.
import requests
import json
url = 'https://www.mywbsite.fr/Services/GetFromDataBaseVersionned'
payload = {
"Host": "www.mywbsite.fr",
"Connection": "keep-alive",
"Content-Length": 129,
"Origin": "https://www.mywbsite.fr",
"X-Requested-With": "XMLHttpRequest",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5",
"Content-Type": "application/json",
"Accept": "*/*",
"Referer": "https://www.mywbsite.fr/data/mult.aspx",
"Accept-Encoding": "gzip,deflate,sdch",
"Accept-Language": "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4",
"Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
"Cookie": "ASP.NET_SessionId=j1r1b2a2v2w245; GSFV=FirstVisit=; GSRef=https://www.google.fr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CHgQFjAA&url=https://www.mywbsite.fr/&ei=FZq_T4abNcak0QWZ0vnWCg&usg=AFQjCNHq90dwj5RiEfr1Pw; HelpRotatorCookie=HelpLayerWasSeen=0; NSC_GSPOUGS!TTM=ffffffff09f4f58455e445a4a423660; GS=Site=frfr; __utma=1.219229010.1337956889.1337956889.1337958824.2; __utmb=1.1.10.1337958824; __utmc=1; __utmz=1.1337956889.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)"
}
# Adding empty header as parameters are being sent in payload
headers = {}
r = requests.post(url, data=json.dumps(payload), headers=headers)
print(r.content)
The error occurs when your repository does not have the default branch set for the remote. You can use the git remote set-head
command to modify the default branch, and thus be able to use the remote name instead of a specified branch in that remote.
To query the remote (in this case origin
) for its HEAD
(typically master
), and set that as the default branch:
$ git remote set-head origin --auto
If you want to use a different default remote branch locally, you can specify that branch:
$ git remote set-head origin new-default
Once the default branch is set, you can use just the remote name in git rebase <remote>
and any other commands instead of explicit <remote>/<branch>
.
Behind the scenes, this command updates the reference in .git/refs/remotes/origin/HEAD
.
$ cat .git/refs/remotes/origin/HEAD
ref: refs/remotes/origin/master
See the git-remote man page for further details.
Unset will destroy a particular session variable whereas session_destroy()
will destroy all the session data for that user.
It really depends on your application as to which one you should use. Just keep the above in mind.
unset($_SESSION['name']); // will delete just the name data
session_destroy(); // will delete ALL data associated with that user.
Instead of QString::number()
i would use QLocale::toString()
, so i can get locale aware group seperatores like german "1.234.567,89".
The code below resolved the issue
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls Or SecurityProtocolType.Ssl3
I had the same problem and all the solutions mentioned here didn't work out for me.
After uninstalling the "Productivity Power Tools 2013" extension, the performance was back to normal.
To share some analysis info. With a simple test how long it takes to read ~1180 lines of values.
If you need to read the data very fast, use the good old BufferedReader FileReader example. It took me ~8ms
The Scanner is much slower. Took me ~138ms
The nice Java 8 Files.lines(...) is the slowest version. Took me ~388ms.
Not sure if someone still needs it after 10 years but I solved it using eigenclass.
module UsefulThings
def useful_thing_1
"thing_1"
end
class << self
include UsefulThings
end
end
class A
include UsefulThings
end
class B
extend UsefulThings
end
UsefulThings.useful_thing_1 # => "thing_1"
A.new.useful_thing_1 # => "thing_1"
B.useful_thing_1 # => "thing_1"
Another fast solution that saves boilerplate code is Lombok EqualsAndHashCode annotation. It is easy, elegant and customizable. And does not depends on the IDE. For example;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode(of={"errorNumber","messageCode"}) // Will only use this fields to generate equals.
public class ErrorMessage{
private long errorNumber;
private int numberOfParameters;
private Level loggingLevel;
private String messageCode;
See the options avaliable to customize which fields to use in the equals. Lombok is avalaible in maven. Just add it with provided scope:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.14.8</version>
<scope>provided</scope>
</dependency>
<div id="AlertDiv" style="width:600px;height:400px;border:SOLID 1px;">
<h1 style="width:100%;height:10%;text-align:center;position:relative;top:40%;">Yes</h1>
</div>
You can try the code here:
JavaScript developers tend to refer to the above data-structure as either an object or hash instead of a Dictionary.
Your syntax above is wrong as you are initializing the users
object as null. I presume this is a typo, as the code should read:
// Initialize users as a new hash.
var users = {};
users["182982"] = "...";
To retrieve all the values from a hash, you need to iterate over it using a for loop:
function getValues (hash) {
var values = [];
for (var key in hash) {
// Ensure that the `key` is actually a member of the hash and not
// a member of the `prototype`.
// see: http://javascript.crockford.com/code.html#for%20statement
if (hash.hasOwnProperty(key)) {
values.push(key);
}
}
return values;
};
If you plan on doing a lot of work with data-structures in JavaScript then the underscore.js library is definitely worth a look. Underscore comes with a values
method which will perform the above task for you:
var values = _.values(users);
I don't use Angular myself, but I'm pretty sure there will be a convenience method build in for iterating over a hash's values (ah, there we go, Artem Andreev provides the answer above :))
As of year 2020, JetBrains suggests to commit the .idea
folder.
The JetBrains IDEs (webstorm, intellij, android studio, pycharm, clion, etc.) automatically add that folder to your git repository (if there's one).
Inside the folder .idea
, has been already created a .gitignore
, updated by the IDE itself to avoid to commit user related settings that may contains privacy/password data.
It is safe (and usually useful) to commit the .idea
folder.
Type "gg" in command mode. This brings the cursor to the first line.
Adding to @StriplingWarrior's answer about bit flags in enums, there's an easy convention you can use in hexadecimal for counting upwards through the bit shifts. Use the sequence 1-2-4-8, move one column to the left, and repeat.
[Flags]
enum Scenery
{
Trees = 0x001, // 000000000001
Grass = 0x002, // 000000000010
Flowers = 0x004, // 000000000100
Cactus = 0x008, // 000000001000
Birds = 0x010, // 000000010000
Bushes = 0x020, // 000000100000
Shrubs = 0x040, // 000001000000
Trails = 0x080, // 000010000000
Ferns = 0x100, // 000100000000
Rocks = 0x200, // 001000000000
Animals = 0x400, // 010000000000
Moss = 0x800, // 100000000000
}
Scan down starting with the right column and notice the pattern 1-2-4-8 (shift) 1-2-4-8 (shift) ...
To answer the original question, I second @Sahuagin's suggestion to use hexadecimal literals. If you're working with binary numbers often enough for this to be a concern, it's worth your while to get the hang of hexadecimal.
If you need to see binary numbers in source code, I suggest adding comments with binary literals like I have above.
Error shows that script does not exists
The file does not exists. check your full path
C:\Windows\TEMP\hudson6299483223982766034.sh
The system cannot find the file specified
Moreover, to launch .sh scripts into windows, you need to have CYGWIN installed and well configured into your path
Confirm that script exists.
Into jenkins script, do the following to confirm that you do have the file
cd C:\Windows\TEMP\
ls -rtl
sh -xe hudson6299483223982766034.sh
Copy-pasted from here:
/* localtime example */
#include <stdio.h>
#include <time.h>
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );
return 0;
}
(just add void
to the main()
arguments list in order for this to work in C)
This should help:
import csv
import requests
CSV_URL = 'http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv'
with requests.Session() as s:
download = s.get(CSV_URL)
decoded_content = download.content.decode('utf-8')
cr = csv.reader(decoded_content.splitlines(), delimiter=',')
my_list = list(cr)
for row in my_list:
print(row)
Ouput sample:
['street', 'city', 'zip', 'state', 'beds', 'baths', 'sq__ft', 'type', 'sale_date', 'price', 'latitude', 'longitude']
['3526 HIGH ST', 'SACRAMENTO', '95838', 'CA', '2', '1', '836', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '59222', '38.631913', '-121.434879']
['51 OMAHA CT', 'SACRAMENTO', '95823', 'CA', '3', '1', '1167', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '68212', '38.478902', '-121.431028']
['2796 BRANCH ST', 'SACRAMENTO', '95815', 'CA', '2', '1', '796', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '68880', '38.618305', '-121.443839']
['2805 JANETTE WAY', 'SACRAMENTO', '95815', 'CA', '2', '1', '852', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '69307', '38.616835', '-121.439146']
[...]
Related question with answer: https://stackoverflow.com/a/33079644/295246
Edit: Other answers are useful if you need to download large files (i.e. stream=True
).
In my case, I got a similar error and it was happening because I had run mongod with the root user and that had created a log file only accessible by the root. I could fix this by changing the ownership from root to the user you normally run mongod from. The log file was in /var/lib/mongodb/journal/
Like this:
import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);
Or adding from an Array/ or multiple literals; wrap to a list, first.
Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b)); // from an array variable
b.addAll( Arrays.asList( 8, 9, 10)); // from literals
To get the intersection:
// copies all from A; then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print; r.toString() implied.
System.out.println("A intersect B="+r);
Hope this answer helps. Vote for it!
i founded a great toool to auto parse and connect to web services
http://www.wsdl2code.com/pages/Example.aspx
SampleService srv1 = new SampleService();
req = new Request();
req.companyId = "1";
req.userName = "userName";
req.password = "pas";
Response response = srv1.ServiceSample(req);
As Ayman farhat mentioned you can use the simple method len(matrix) to get the length of rows and get the length of the first row to get the no. of columns using len(matrix[0]) :
>>> a=[[1,5,6,8],[1,2,5,9],[7,5,6,2]]
>>> len(a)
3
>>> len(a[0])
4
Also you can use a library that helps you with matrices "numpy":
>>> import numpy
>>> numpy.shape(a)
(3,4)
Nowadays you can put
@Autowired
private Environment environment;
in your @Component
, @Bean
, etc., and then access the properties through the Environment
class:
environment.getProperty("myProp");
For a single property in a @Bean
@Value("${my.another.property:123}") // value after ':' is the default
Integer property;
Another way are the handy @ConfigurationProperties
beans:
@ConfigurationProperties(prefix="my.properties.prefix")
public class MyProperties {
// value from my.properties.prefix.myProperty will be bound to this variable
String myProperty;
// and this will even throw a startup exception if the property is not found
@javax.validation.constraints.NotNull
String myRequiredProperty;
//getters
}
@Component
public class MyOtherBean {
@Autowired
MyProperties myProperties;
}
Note: Just remember to restart eclipse after setting a new environment variable
Looks to me like you need to set the yellow
on #doc3
and then get rid of the white
that is called out on the #yui-main
(which is covering up the color of the #doc3
). This gets you yellow between header and footer.
for i=1,#target do
game.Players.target[i].Character:BreakJoints()
end
Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:
game.Players.target.1.Character:BreakJoints()
Which is completely incorrect.
c = game.Players:GetChildren()
Never use "Players:GetChildren()", it is not guaranteed to return only players.
Instead use:
c = Game.Players:GetPlayers()
if msg:lower()=="me" then
table.insert(people, source)
return people
Here you add the player's name in the list "people", where you in the other places adds the player object.
Fixed code:
local Admins = {"FakeNameHereSoNoStalkers"}
function Kill(Players)
for i,Player in ipairs(Players) do
if Player.Character then
Player.Character:BreakJoints()
end
end
end
function IsAdmin(Player)
for i,AdminName in ipairs(Admins) do
if Player.Name:lower() == AdminName:lower() then return true end
end
return false
end
function GetPlayers(Player,Msg)
local Targets = {}
local Players = Game.Players:GetPlayers()
if Msg:lower() == "me" then
Targets = { Player }
elseif Msg:lower() == "all" then
Targets = Players
elseif Msg:lower() == "others" then
for i,Plr in ipairs(Players) do
if Plr ~= Player then
table.insert(Targets,Plr)
end
end
else
for i,Plr in ipairs(Players) do
if Plr.Name:lower():sub(1,Msg:len()) == Msg then
table.insert(Targets,Plr)
end
end
end
return Targets
end
Game.Players.PlayerAdded:connect(function(Player)
if IsAdmin(Player) then
Player.Chatted:connect(function(Msg)
if Msg:lower():sub(1,6) == ":kill " then
Kill(GetPlayers(Player,Msg:sub(7)))
end
end)
end
end)
public int GetResult(List<int> list){
int first = list.First();
return list.All(x => x == first) ? first : SOME_OTHER_VALUE;
}
I ran in to this recently, and as it turned out, I've imported the wrong annotation in my service class. Netbeans has an option to hide import statements, that's why I did not see it for some time.
I've used @org.jvnet.hk2.annotations.Service
instead of @org.springframework.stereotype.Service
.
Depending on the database engine you are using, there can be limits on the length of an instruction.
SQL Server has a very large limit:
http://msdn.microsoft.com/en-us/library/ms143432.aspx
ORACLE has a very easy to reach limit on the other side.
So, for large IN clauses, it's better to create a temp table, insert the values and do a JOIN. It works faster also.
ou are able to create local variables once you call the render function on a partial, therefore if you want to customize a partial you can for example render the partial _form.html.erb
by:
<%= render 'form', button_label: "Create New Event", url: new_event_url %>
<%= render 'form', button_label: "Update Event", url: edit_event_url %>
this way you can access in the partial to the label for the button and the URL, those are different if you try to create or update a record.
finally, for accessing to this local variables you have to put in your code local_assigns[:button_label]
(local_assigns[:name_of_your_variable]
)
<%=form_for(@event, url: local_assigns[:url]) do |f| %>
<%= render 'shared/error_messages_events' %>
<%= f.label :title ,"Title"%>
<%= f.text_field :title, class: 'form-control'%>
<%=f.label :date, "Date"%>
<%=f.date_field :date, class: 'form-control' %>
<%=f.label :description, "Description"%>
<%=f.text_area :description, class: 'form-control' %>
<%= f.submit local_assigns[:button_label], class:"btn btn-primary"%>
<%end%>
<c:forEach items="${sessionScope.empL}" var="emp">
<tr>
<td>Employee ID: <c:out value="${emp.eid}"/></td>
<td>Employee Pass: <c:out value="${emp.ename}"/></td>
</tr>
</c:forEach>
you can use laravel validation if you want to insert a unique record:
$validated = $request->validate([
'title' => 'required|unique:usersTable,emailAddress|max:255',
]);
But you use these ways also:
1:
if (User::where('email', $request->email)->exists())
{
// object exists
} else {
// object not found
}
2:
$user = User::where('email', $request->email)->first();
if ($user)
{
// object exists
} else {
// object not found
}
3:
$user = User::where('email', $request->email)->first();
if ($user->isEmpty())
{
// object exists
} else {
// object not found
}
4:
$user = User::where('email', $request->email)->firstOrCreate([
'email' => 'email'
],$request->all());
You are missing the view engine, for example use jade:
change your
app.set('view engine', 'html');
with
app.set('view engine', 'jade');
If you want use a html friendly syntax use instead ejs
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
EDIT
As you can read from view.js Express View Module
module.exports = View;
/**
* Initialize a new `View` with the given `name`.
*
* Options:
*
* - `defaultEngine` the default template engine name
* - `engines` template engine require() cache
* - `root` root path for view lookup
*
* @param {String} name
* @param {Object} options
* @api private
*/
function View(name, options) {
options = options || {};
this.name = name;
this.root = options.root;
var engines = options.engines;
this.defaultEngine = options.defaultEngine;
var ext = this.ext = extname(name);
if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no extension was provided.');
if (!ext) name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') + this.defaultEngine);
this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express);
this.path = this.lookup(name);
}
You must have installed a default engine
Express
search default layout view by program.template
as you can read below:
mkdir(path + '/views', function(){
switch (program.template) {
case 'ejs':
write(path + '/views/index.ejs', ejsIndex);
break;
case 'jade':
write(path + '/views/layout.jade', jadeLayout);
write(path + '/views/index.jade', jadeIndex);
break;
case 'jshtml':
write(path + '/views/layout.jshtml', jshtmlLayout);
write(path + '/views/index.jshtml', jshtmlIndex);
break;
case 'hjs':
write(path + '/views/index.hjs', hoganIndex);
break;
}
});
and as you can read below:
program.template = 'jade';
if (program.ejs) program.template = 'ejs';
if (program.jshtml) program.template = 'jshtml';
if (program.hogan) program.template = 'hjs';
the default view engine is jade
Perhaps, you can have them marked as internal, and in this case only classes in your DAL or BL (assuming they are separate dlls) would be able to set it.
You could also supply a constructor that takes the fields and then only exposes them as properties.
loc function can be used to replace multiple values, Documentation for it : loc
df.loc[df['BrandName'].isin(['ABC', 'AB'])]='A'
Let's make random convenient again!
I made up a nice C++11 header only solution. You could easily add one header file to your project and then add your tests or use random strings for another purposes.
That's a quick description, but you can follow the link to check full code. The main part of solution is in class Randomer:
class Randomer {
// random seed by default
std::mt19937 gen_;
std::uniform_int_distribution<size_t> dist_;
public:
/* ... some convenience ctors ... */
Randomer(size_t min, size_t max, unsigned int seed = std::random_device{}())
: gen_{seed}, dist_{min, max} {
}
// if you want predictable numbers
void SetSeed(unsigned int seed) {
gen_.seed(seed);
}
size_t operator()() {
return dist_(gen_);
}
};
Randomer
incapsulates all random stuff and you can add your own functionality to it easily. After we have Randomer
, it's very easy to generate strings:
std::string GenerateString(size_t len) {
std::string str;
auto rand_char = [](){ return alphabet[randomer()]; };
std::generate_n(std::back_inserter(str), len, rand_char);
return str;
}
Write your suggestions for improvement below. https://gist.github.com/VjGusev/e6da2cb4d4b0b531c1d009cd1f8904ad
First install express and http-proxy-middleware
npm install express http-proxy-middleware --save
Then in your server.js
const express = require('express');
const proxy = require('http-proxy-middleware');
const app = express();
app.use(express.static('client'));
// Add middleware for http proxying
const apiProxy = proxy('/api', { target: 'http://localhost:8080' });
app.use('/api', apiProxy);
// Render your site
const renderIndex = (req, res) => {
res.sendFile(path.resolve(__dirname, 'client/index.html'));
}
app.get('/*', renderIndex);
app.listen(3000, () => {
console.log('Listening on: http://localhost:3000');
});
In this example we serve the site on port 3000, but when a request end with /api we redirect it to localhost:8080.
http://localhost:3000/api/login redirect to http://localhost:8080/api/login
You should do:
try:
value_index = my_list.index(value)
except:
value_index = -1;
Following is correct way:
xmlhttp.open("GET","getuser.php?fname="+abc ,true);
The next version of dplyr will support an improved version of select that also incorporates renaming:
> mtcars2 <- select( mtcars, disp2 = disp )
> head( mtcars2 )
disp2
Mazda RX4 160
Mazda RX4 Wag 160
Datsun 710 108
Hornet 4 Drive 258
Hornet Sportabout 360
Valiant 225
> changes( mtcars, mtcars2 )
Changed variables:
old new
disp 0x105500400
disp2 0x105500400
Changed attributes:
old new
names 0x106d2cf50 0x106d28a98
I had this problem. The solution was to allow node.js through the server's firewall.
A more generic way to convert python lists to strings would be:
>>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_lst_str = ''.join(map(str, my_lst))
>>> print(my_lst_str)
'12345678910'
I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr
), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:
```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```
Then all the images will be written as PDF files, and LaTeX will be happy.
Your second problem is you are mixing up the HTML units with LaTeX units in out.width
/ out.height
. LaTeX and HTML are very different technologies. You should not expect \maxwidth
to work in HTML, or 200px
in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width
/ out.height
(use fig.width
/ fig.height
and let LaTeX use the original size).
For me I needed to do something like this to completely remove the borders from the table and all cells. This does not require modifying the HTML at all, which was helpful in my case.
table, tr, td {
border: none;
}
Apart from standard Heap parameters -Xms
and -Xmx
it's also good to know -XX:PermSize
and -XX:MaxPermSize
, which is used to specify size of Perm Gen space because even though you could have space in other generation in heap you can run out of memory if your perm gen space gets full. This link also has nice overview of some important JVM parameters.
Same thing, Just start the table name with #
or ##
:
CREATE TABLE #TemporaryTable -- Local temporary table - starts with single #
(
Col1 int,
Col2 varchar(10)
....
);
CREATE TABLE ##GlobalTemporaryTable -- Global temporary table - note it starts with ##.
(
Col1 int,
Col2 varchar(10)
....
);
Temporary table names start with #
or ##
- The first is a local temporary table and the last is a global temporary table.
Here is one of many articles describing the differences between them.
although sets browser encoding to UTF-8
(If you're using numeric character references of course it doesn't matter what encoding is being used, browsers will get the correct Unicode codepoint directly from the number.)
<span style="font-family: wingdings; font-size: 200%;">ü</span>
I would appreciate if someone could check under FF on Windows. I am pretty sure it won't work on a non Windows box.
Fails for me in Firefox 3, Opera, and Safari. Curiously, works in the other Webkit browser, Chrome. Also fails on Linux (obviously, as Wingdings isn't installed there; it is installed on Macs, but that doesn't help you if Safari's not having it).
Also it's a pretty nasty hack — that character is to all intents and purposes “ü” and will appear that way to things like search engines, or if the text is copy-and-pasted. Proper Unicode code points are the way to go unless you really have no alternative.
The problem is that no font bundled with Windows supplies U+2713 CHECK MARK (‘?’). The only one that you're at all likely to find on a Windows machine is “Arial Unicode MS”, which is not really to be relied upon. So in the end I think you'll have to either:
Try BeanComparator from Apache Commons.
import org.apache.commons.beanutils.BeanComparator;
BeanComparator fieldComparator = new BeanComparator("fruitName");
Collections.sort(fruits, fieldComparator);
Much in line with Aurelio's answer, I now work in Ruby on Rails on some applications that I might formerly have done in MS Access. The back end database for a Rails App. is usually, MySql (works well enough and is available on most shared Web hosting) or PostgreSQL (the better choice when possible).
There are to ways: Use the attribute of the image tag align="absmiddle" or locate the image and the text in a container DIV or TD in a table and use
style="vertical-align:middle"
seq[::n]
is a sequence of each n
-th item in the entire sequence.
Example:
>>> range(10)[::2]
[0, 2, 4, 6, 8]
The syntax is:
seq[start:end:step]
So you can do (in Python 2):
>>> range(100)[5:18:2]
[5, 7, 9, 11, 13, 15, 17]
Wanny is correct. The &&
operator doesn't work in HTML. With Angular, you must use the double pipes (||
)for multiple conditions.
The error may occur when the number of times you iterate the array is greater than the actual size of the array. for example:
$one="909";
for($i=0;$i<10;$i++)
echo ' '.$one[$i];
will show the error. first case u can take the mod of i.. for example
function mod($i,$length){
$m = $i % $size;
if ($m > $size)
mod($m,$size)
return $m;
}
for($i=0;$i<10;$i++)
{
$k=mod($i,3);
echo ' '.$one[$k];
}
or might be it not an array (maybe it was a value and you tried to access it like an array) for example:
$k = 2;
$k[0];
I created UIView and set the property of cell selectedBackgroundView:
UIView *v = [[UIView alloc] init];
v.backgroundColor = [UIColor redColor];
cell.selectedBackgroundView = v;
You have to tell it which component you want to import by explicitly giving the class name..in your case it's Map
import Map from './Map';
class App extends Component{
/*your code here...*/
}
Apparently, Angular had the max/min directives for template driven forms at some point but had to remove them in v4.2.0. You can read about the regression that caused the removal here: https://github.com/angular/angular/issues/17491
For now the only working solution that I know of is to use custom directive as @amd suggested. Here's how to use it with Bootstrap 4.
min-validator.directive.ts
import { Directive, Input } from '@angular/core'
import { NG_VALIDATORS, Validator, AbstractControl, Validators } from '@angular/forms'
@Directive({
selector: '[min]',
providers: [{ provide: NG_VALIDATORS, useExisting: MinDirective, multi: true }]
})
export class MinDirective implements Validator {
@Input() min: number;
validate(control: AbstractControl): { [key: string]: any } {
return Validators.min(this.min)(control)
}
}
And in your template:
<input type="number" [min]="minAge" #age="ngModel" [(ngModel)]="person.age" class="form-control" [ngClass]="{'is-invalid':age.invalid}">
<div *ngIf="age.invalid && (age.dirty || age.touched)" class="invalid-feedback">You need to be older than {{minAge}} to participate</div>
Hope this helps!
I modified Bryan's solution to be a little more robust, so that it would play nicely with other types of keyboards that could appear in the same view. It's described here:
Create a DONE button on the iOS numpad UIKeyboard
I'd try to explain it here, but most of it is code to look at that wouldn't easily fit here
Yes, in Pandas we have many functions has the parameter inplace
but by default it is assigned to False
.
So, when you do df.dropna(axis='index', how='all', inplace=False)
it thinks that you do not want to change the orignial DataFrame
, therefore it instead creates a new copy for you with the required changes.
But, when you change the inplace
parameter to True
Then it is equivalent to explicitly say that I do not want a new copy of the
DataFrame
instead do the changes on the givenDataFrame
This forces the Python interpreter to not to create a new DataFrame
But you can also avoid using the inplace
parameter by reassigning the result to the orignal DataFrame
df = df.dropna(axis='index', how='all')
I started to get the 500 for debug=False in the form of
django.urls.exceptions.NoReverseMatch: Reverse for 'home' not found.
or...
django.urls.exceptions.NoReverseMatch: Reverse for 'about' not found.
when raising django.core.exceptions.ValidationError instead of raising rest_framework.serializers.ValidationError
To be fair, it was already raising a 500 before, but as a ValidationError, with debug=False, this changed into the NoReverseMatch.
TL;DR: Use StandardError
instead for general exception catching. When the original exception is re-raised (e.g. when rescuing to log the exception only), rescuing Exception
is probably okay.
Exception
is the root of Ruby's exception hierarchy, so when you rescue Exception
you rescue from everything, including subclasses such as SyntaxError
, LoadError
, and Interrupt
.
Rescuing Interrupt
prevents the user from using CTRLC to exit the program.
Rescuing SignalException
prevents the program from responding correctly to signals. It will be unkillable except by kill -9
.
Rescuing SyntaxError
means that eval
s that fail will do so silently.
All of these can be shown by running this program, and trying to CTRLC or kill
it:
loop do
begin
sleep 1
eval "djsakru3924r9eiuorwju3498 += 5u84fior8u8t4ruyf8ihiure"
rescue Exception
puts "I refuse to fail or be stopped!"
end
end
Rescuing from Exception
isn't even the default. Doing
begin
# iceberg!
rescue
# lifeboats
end
does not rescue from Exception
, it rescues from StandardError
. You should generally specify something more specific than the default StandardError
, but rescuing from Exception
broadens the scope rather than narrowing it, and can have catastrophic results and make bug-hunting extremely difficult.
If you have a situation where you do want to rescue from StandardError
and you need a variable with the exception, you can use this form:
begin
# iceberg!
rescue => e
# lifeboats
end
which is equivalent to:
begin
# iceberg!
rescue StandardError => e
# lifeboats
end
One of the few common cases where it’s sane to rescue from Exception
is for logging/reporting purposes, in which case you should immediately re-raise the exception:
begin
# iceberg?
rescue Exception => e
# do some logging
raise # not enough lifeboats ;)
end
It's actually a simple answer.
Your function is returning a string rather than the div
node. appendChild
can only append a node.
For example, if you try to appendChild the string:
var z = '<p>test satu dua tiga</p>'; // is a string
document.body.appendChild(z);
The above code will never work. What will work is:
var z = document.createElement('p'); // is a node
z.innerHTML = 'test satu dua tiga';
document.body.appendChild(z);
For whatever reason, @AliUmair reverted the edit to his answer that fixes his code that doesn't run as is, so here is the working version that doesn't have the file access error and properly handles null object property values:
/// <summary>
/// Creates the CSV from a generic list.
/// </summary>;
/// <typeparam name="T"></typeparam>;
/// <param name="list">The list.</param>;
/// <param name="csvNameWithExt">Name of CSV (w/ path) w/ file ext.</param>;
public static void CreateCSVFromGenericList<T>(List<T> list, string csvCompletePath)
{
if (list == null || list.Count == 0) return;
//get type from 0th member
Type t = list[0].GetType();
string newLine = Environment.NewLine;
if (!Directory.Exists(Path.GetDirectoryName(csvCompletePath))) Directory.CreateDirectory(Path.GetDirectoryName(csvCompletePath));
using (var sw = new StreamWriter(csvCompletePath))
{
//make a new instance of the class name we figured out to get its props
object o = Activator.CreateInstance(t);
//gets all properties
PropertyInfo[] props = o.GetType().GetProperties();
//foreach of the properties in class above, write out properties
//this is the header row
sw.Write(string.Join(",", props.Select(d => d.Name).ToArray()) + newLine);
//this acts as datarow
foreach (T item in list)
{
//this acts as datacolumn
var row = string.Join(",", props.Select(d => $"\"{item.GetType().GetProperty(d.Name).GetValue(item, null)?.ToString()}\"")
.ToArray());
sw.Write(row + newLine);
}
}
}
If you're using Closure you can use the built-in goog.format.EmailAddress
type:
http://docs.closure-library.googlecode.com/git/class_goog_format_EmailAddress.html
For example:
goog.format.EmailAddress.isValidAddrSpec("[email protected]")
Note that by reading the source (linked above) you can see the comments state that IDN are not supported and that it only aims to cover most addresses:
// This is a fairly naive implementation, but it covers 99% of use cases.
// For more details, see http://en.wikipedia.org/wiki/Email_address#Syntax
// TODO(mariakhomenko): we should also be handling i18n domain names as per
// http://en.wikipedia.org/wiki/Internationalized_domain_name
In general you can use pandas rename function here. Given your dataframe you could change to a new name like this. If you had more columns you could also rename those in the dictionary. The 0 is the current name of your column
import pandas as pd
import numpy as np
e = np.random.normal(size=100)
e_dataframe = pd.DataFrame(e)
e_dataframe.rename(index=str, columns={0:'new_column_name'})
Use get_the_category()
function.
$post_categories = wp_get_post_categories( 4 );
$categories = get_the_category($post_categories[0]);
var_dump($categories);
lots of big companies dont even use your expiration date anymore because it causes auto-renewal of payments to be lost when cards are issued with new expiration dates and the same account number. This has been a huge problem in the service industry, so these companies have cornered the card issuers into processing payments w/o expiration dates to avoid this pitfall. Not many people know about this yet, so not all companies use this practice.
below is an generic example
//base class
class A {
// The virtual method
protected virtualStuff1?():void;
public Stuff2(){
//Calling overridden child method by parent if implemented
this.virtualStuff1 && this.virtualStuff1();
alert("Baseclass Stuff2");
}
}
//class B implementing virtual method
class B extends A{
// overriding virtual method
public virtualStuff1()
{
alert("Class B virtualStuff1");
}
}
//Class C not implementing virtual method
class C extends A{
}
var b1 = new B();
var c1= new C();
b1.Stuff2();
b1.virtualStuff1();
c1.Stuff2();
Wrong method was used for errors, here is the working code:
BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
We had a similar problem in a web application, and ended up by reading the filename from the HTML <input type="file">
, and setting that in the url-encoded form in a new HTML <input type="hidden">
. Of course we had to remove the path like "C:\fakepath\" that is returned by some browsers.
Of course this does not directly answer OPs question, but may be a solution for others.
The page sizes are looking different in your PDF because the images were originally set to different DPI (even if images are identical HxW in pixels). The good news is - it's only a display issue - and can be fixed easily.
An image with a higher DPI value would display smaller in a PDF (displays at the 'print-size' of the image). To avoid this, open each image in an image editor like GIMP or Photoshop. Open relevant image print control dialog box and set a suitable uniform DPI info for all the images. Remake the PDF with these new images. If in the new PDF images are too big - redo the DPI setting for each to a higher value. If in the new PDF pages are too small to read on-screen without zooming, again - redo DPI adjustment, this time put a lower DPI value. Ideally, 150 DPI should be good enough for images of 2500X2500 pixel - on a 17 inch monitor set to 1366x768 resolution.
BTW, the PDF file shall print each page at the specified DPI of that page. If all images are same DPI, you'll get a uniform printing.
Hope this helps :)
My experience in Java programming for beginner is not difficult to learn; however it is really depended on how your object-oriented programming skills are. As you posed that you had no programming experience , I guess that I recommend a web site, http://www.exampledepot.com/ , and type any java keyword such as Swing, FileInputStream, it provides a lot of practical examples that you can apply into a project.
Please, buy a java book (Sams'java 6 in 24 hours) as reference. It will give you really basic skills for java within a short time. and I sure you will have enough time to learn about the java and J2ME within 10 weeks. Good Luck.
Tiger
Use String.PadLeft like this:
var result = input.ToString().PadLeft(length, '0');
Use the tee
command:
echo "hello" | tee logfile.txt
unnest2()
as exerciseOlder versions before pg v8.4 need a user-defined unnest()
. We can adapt this old function to return elements with an index:
CREATE FUNCTION unnest2(anyarray)
RETURNS setof record AS
$BODY$
SELECT $1[i], i
FROM generate_series(array_lower($1,1),
array_upper($1,1)) i;
$BODY$ LANGUAGE sql IMMUTABLE;
var myCheckboxes = new Array();
$("input:checked").each(function() {
data['myCheckboxes[]'].push($(this).val());
});
You are pushing checkboxes to wrong array data['myCheckboxes[]']
instead of myCheckboxes.push
A better way is to use the Stopwatch class:
using System.Diagnostics;
// ...
Stopwatch sw = new Stopwatch();
sw.Start();
// ...
sw.Stop();
Console.WriteLine("Elapsed={0}",sw.Elapsed);
You should also use the style 'color' and not 'font-color'
<?php
foreach($months as $key => $month){
if(strpos($filename,$month)!==false){
echo "<style = 'color: #ff0000;'> Movie List for {$key} 2013 </style>";
}
}
?>
In general, the comments on double and single quotes are correct in other suggestions. $Variables only execute in double quotes.
Max is on he right track with the suggestion to use Windows Scripting for a way to do it without installing any additional executables on the machine. His code will work if you have the IIS SMTP service setup to forward outbound email using the "smart host" setting, or the machine also happens to be running Microsoft Exchange. Otherwise if this is not configured, you will find your emails just piling up in the message queue folder (\inetpub\mailroot\queue). So, unless you can configure this service, you also want to be able to specify the email server you want to use to send the message with. To do that, you can do something like this in your windows script file:
Set objMail = CreateObject("CDO.Message")
Set objConf = CreateObject("CDO.Configuration")
Set objFlds = objConf.Fields
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'cdoSendUsingPort
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.your-site-url.com" 'your smtp server domain or IP address goes here
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 'default port for email
'uncomment next three lines if you need to use SMTP Authorization
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "your-username"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "your-password"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'cdoBasic
objFlds.Update
objMail.Configuration = objConf
objMail.FromName = "Your Name"
objMail.From = "[email protected]"
objMail.To = "[email protected]"
objMail.Subject = "Email Subject Text"
objMail.TextBody = "The message of the email..."
objMail.Send
Set objFlds = Nothing
Set objConf = Nothing
Set objMail = Nothing
document.getElementById()
method accepts only one argument.
However, you may always set classes to the elements and use getElementsByClassName()
instead. Another option for modern browsers is to use querySelectorAll()
method:
document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4");
You get a recursion error because your attempt to access the self.__dict__
attribute inside __getattribute__
invokes your __getattribute__
again. If you use object
's __getattribute__
instead, it works:
class D(object):
def __init__(self):
self.test=20
self.test2=21
def __getattribute__(self,name):
if name=='test':
return 0.
else:
return object.__getattribute__(self, name)
This works because object
(in this example) is the base class. By calling the base version of __getattribute__
you avoid the recursive hell you were in before.
Ipython output with code in foo.py:
In [1]: from foo import *
In [2]: d = D()
In [3]: d.test
Out[3]: 0.0
In [4]: d.test2
Out[4]: 21
Update:
There's something in the section titled More attribute access for new-style classes in the current documentation, where they recommend doing exactly this to avoid the infinite recursion.
For php, \n should work for you!
You could install $ gem install foreman
, and use foreman to start your server as defined in your Procfile
like:
web: bundle exec rails -p 10524
You can check foreman
gem docs here: https://github.com/ddollar/foreman for more info
The benefit of this approach is not only can you set/change the port in the config easily and that it doesn't require much code to be added but also you can add different steps in the Procfile
that foreman will run for you so you don't have to go though them each time you want to start you application something like:
bundle: bundle install
web: bundle exec rails -p 10524
...
...
Cheers
For me echo XYZ_20200824.zip | grep -Eo '[[:digit:]]{4}[[:digit:]]{2}[[:digit:]]{2}'
was working fine but unable to store output of command into variable.
I had same issue I tried eval
but didn't got output.
Here is answer for my problem:
cmd=$(echo XYZ_20200824.zip | grep -Eo '[[:digit:]]{4}[[:digit:]]{2}[[:digit:]]{2}')
echo $cmd
My output is now 20200824
On my network just setting http_proxy didn't work for me. The following points were relevant.
1 Setting http_proxy for your user wont be preserved when you execute sudo - to preserve it, do:
sudo -E yourcommand
I got my install working by first installing cntlm local proxy. The instructions here is succinct : http://www.leg.uct.ac.za/howtos/use-isa-proxies
Instead of student number, you'd put your domain username
2 To use the cntlm local proxy, exec:
pip install --proxy localhost:3128 pygments
/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/jsp-api-6.0.16.jar
/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/servlet-api-6.0.16.jar
You should not have any server-specific libraries in the /WEB-INF/lib
. Leave them in the appserver's own library. It would only lead to collisions in the classpath. Get rid of all appserver-specific libraries in /WEB-INF/lib
(and also in JRE/lib
and JRE/lib/ext
if you have placed any of them there).
A common cause that the appserver-specific libraries are included in the webapp's library is that starters think that it is the right way to fix compilation errors of among others the javax.servlet
classes not being resolveable. Putting them in webapp's library is the wrong solution. You should reference them in the classpath during compilation, i.e. javac -cp /path/to/server/lib/servlet.jar
and so on, or if you're using an IDE, you should integrate the server in the IDE and associate the web project with the server. The IDE will then automatically take server-specific libraries in the classpath (buildpath) of the webapp project.
As of npm version 3.8.6, you can use
npm install --prefix ./install/here <package>
to install in the specified directory. NPM automatically creates node_modules
folder even when a node_modules
directory already exists in the higher up hierarchy.
You can also have a package.json
in the current directory and then install it in the specified directory using --prefix
option:
npm install --prefix ./install/here
As of npm 6.0.0, you can use
npm install --prefix ./install/here ./
to install the package.json in current directory to "./install/here" directory. There is one thing that I have noticed on Mac that it creates a symlink to parent folder inside the node_modules directory. But, it still works.
NOTE: NPM honours the path that you've specified through the --prefix
option. It resolves as per npm documentation on folders, only when npm install
is used without the --prefix
option.
Use an image
type input:
<input type="image" src="/Button1.jpg" border="0" alt="Submit" />
The full HTML:
<form id='formName' name='formName' onsubmit='redirect();return false;'>_x000D_
<div class="style7">_x000D_
<input type='text' id='userInput' name='userInput' value=''>_x000D_
<input type="image" name="submit" src="https://jekyllcodex.org/uploads/grumpycat.jpg" border="0" alt="Submit" style="width: 50px;" />_x000D_
</div>_x000D_
</form>
_x000D_
if you use the git for mac in GUI you can chose Respository->Pull or the "comm+shift+p" to "git pull" first, then publish the source.
For me it didn't work after doing all of the steps suggested in the question and in the top answer. Initially the import didn't work, and then when I restarted IntelliJ, I got these messages from the Gradle Plugin:
Gradle DSL method not found: 'annotationProcessor()'
Possible causes:<ul><li>The project 'wq-handler-service' may be using a version of the Android Gradle plug-in that does not contain the method (e.g. 'testCompile' was added in 1.1.0).
Upgrade plugin to version 2.3.2 and sync project</li><li>The project 'wq-handler-service' may be using a version of Gradle that does not contain the method.
Open Gradle wrapper file</li><li>The build file may be missing a Gradle plugin.
Apply Gradle plugin</li>
This was weird because I don't develop for Android, just using IntelliJ for Mac OS.
To be fair, my build.gradle
file had these lines in the dependencies
section, which I copied from a colleague:
compileOnly group: 'org.projectlombok', name: 'lombok', version: '1.16.20'
annotationProcessor group: 'org.projectlombok', name: 'lombok', version: '1.16.20'
After checking versions, the only thing that completely solved my problem was adding the below to the plugins
section of build.gradle
, which I found on this page:
id 'net.ltgt.apt' version '0.15'
Looks like it's a
Gradle plugin making it easier/safer to use Java annotation processors
Pay attention:
A Java char
corresponds to a UTF-16 code unit, and in some cases two consecutive char
s (a so-called surrogate pair) are needed for one real Unicode character (codepoint).
XORing two valid UTF-16 sequences (i.e. Java Strings char
by char
, or byte by byte after encoding to UTF-16) does not necessarily give you another valid UTF-16 string - you may have unpaired surrogates as a result. (It would still be a perfectly usable Java String, just the codepoint-concerning methods could get confused, and the ones that convert to other encodings for output and similar.)
The same is valid if you first convert your Strings to UTF-8 and then XOR these bytes - here you quite probably will end up with a byte sequence which is not valid UTF-8, if your Strings were not already both pure ASCII strings.
Even if you try to do it right and iterate over your two Strings by codepoint and try to XOR the codepoints, you can end up with codepoints outside the valid range (for example, U+FFFFF
(plane 15) XOR U+10000
(plane 16) = U+1FFFFF
(which would the last character of plane 31), way above the range of existing codepoints. And you could also end up this way with codepoints reserved for surrogates (= not valid ones).
If your strings only contain chars < 128, 256, 512, 1024, 2048, 4096, 8192, 16384, or 32768, then the (char-wise) XORed strings will be in the same range, and thus certainly not contain any surrogates. In the first two cases you could also encode your String as ASCII or Latin-1, respectively, and have the same XOR-result for the bytes. (You still can end up with control chars, which may be a problem for you.)
What I'm finally saying here: don't expect the result of encrypting Strings to be a valid string again - instead, simply store and transmit it as a byte[]
(or a stream of bytes). (And yes, convert to UTF-8 before encrypting, and from UTF-8 after decrypting).
Sadly, I think that JSTL doesn't support anything but an iteration through all elements to figure this out. In the past, I've used the forEach method in the core tag library:
<c:set var="contains" value="false" />
<c:forEach var="item" items="${myList}">
<c:if test="${item eq myValue}">
<c:set var="contains" value="true" />
</c:if>
</c:forEach>
After this runs, ${contains} will be equal to "true" if myList contained myValue.
This is a feature, not a bug.
See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.
From the doc (bootsrap 4):
https://getbootstrap.com/docs/4.0/utilities/flex/#justify-content
.justify-content-start
.justify-content-end
.justify-content-center
.justify-content-between
.justify-content-around
.justify-content-sm-start
.justify-content-sm-end
.justify-content-sm-center
.justify-content-sm-between
.justify-content-sm-around
.justify-content-md-start
.justify-content-md-end
.justify-content-md-center
.justify-content-md-between
.justify-content-md-around
.justify-content-lg-start
.justify-content-lg-end
.justify-content-lg-center
.justify-content-lg-between
.justify-content-lg-around
.justify-content-xl-start
.justify-content-xl-end
.justify-content-xl-center
.justify-content-xl-between
.justify-content-xl-around
I can't find a way to create a table with icons in SO, so I am uploading 2 images.
As @Renan mentioned, ng-include creates a new child scope. This scope prototypically inherits (see dashed lines below) from the HomeCtrl scope. ng-model="lineText"
actually creates a primitive scope property on the child scope, not HomeCtrl's scope. This child scope is not accessible to the parent/HomeCtrl scope:
To store what the user typed into HomeCtrl's $scope.lines array, I suggest you pass the value to the addLine function:
<form ng-submit="addLine(lineText)">
In addition, since lineText is owned by the ngInclude scope/partial, I feel it should be responsible for clearing it:
<form ng-submit="addLine(lineText); lineText=''">
Function addLine() would thus become:
$scope.addLine = function(lineText) {
$scope.chat.addLine(lineText);
$scope.lines.push({
text: lineText
});
};
Alternatives:
ng-model="someObj.lineText
; fiddlelineText
property on the HomeCtrl $scope: ng-model="$parent.lineText"
; fiddleIt is a bit involved to explain why the above two alternatives work, but it is fully explained here: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
I don't recommend using this
in the addLine() function. It becomes much less clear which scope is being accessed/manipulated.
use ng-intl-tel-input to validate mobile numbers for all countries. you can set default country also. on npm: https://www.npmjs.com/package/ng-intl-tel-input
more details: https://techpituwa.wordpress.com/2017/03/29/angular-js-phone-number-validation-with-ng-intl-tel-input/
Try xcorr
, it's a built-in function in MATLAB for cross-correlation:
c = xcorr(A_1, A_2);
However, note that it requires the Signal Processing Toolbox installed. If not, you can look into the corrcoef
command instead.
Apache Commons Lang has a StringUtils.left
method for this.
String upToNCharacters = StringUtils.left(s, n);
Use the absolute value function ABS. The syntax is
ABS ( numeric_expression )
I was able to install composer on HostGator's shared hosting. Logged in to SSH with Putty, right after login you should be in your home directory, which is usually /home/username, where username is your username obviously. Then ran the curl command posted by @niutech above. This downloaded the composer to my home directory and it's now accessible and working well.
php --ini
This will tell you exactly which php.ini file is being loaded, so you know which one to modify. I wasted a lot of time changing the wrong php.ini file because I had WAMP and XAMPP installed.
Also, don't forget to restart the WAMP server (or whatever you use) after changing php.ini.
If you're on java 6 can use NetworkInterface to check for available network interfaces. I.e. something like this:
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface interf = interfaces.nextElement();
if (interf.isUp() && !interf.isLoopback())
return true;
}
Haven't tried it myself, yet.
For you Windows XP users (who have no where
command built-in), I have written a "where like" command as a rubygem called whichr
.
To install it, install Ruby.
Then
gem install whichr
Run it like:
C:> whichr cmd_here
You need to precede the lines starting with gcc
and rm
with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line).
The result should look like this:
PROG = semsearch
all: $(PROG)
%: %.c
gcc -o $@ $< -lpthread
clean:
rm $(PROG)
Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:
PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread
clean: ; rm $(PROG)