It doesn't - the C# compiler does :)
So this code:
string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;
actually gets compiled as:
string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);
(Gah - intervening edit removed other bits accidentally.)
The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y
which then needs to be copied again as part of the concatenation of (x + y)
and z
. Instead, we get it all done in one go.
EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:
string x = "";
foreach (string y in strings)
{
x += y;
}
just ends up as equivalent to:
string x = "";
foreach (string y in strings)
{
x = string.Concat(x, y);
}
... so this does generate a lot of garbage, and it's why you should use a StringBuilder
for such cases. I have an article going into more details about the two which will hopefully answer further questions.
Let's assume you want to overwrite the same file:
import json
with open('data.json', 'r') as data_file:
data = json.load(data_file)
for element in data:
element.pop('hours', None)
with open('data.json', 'w') as data_file:
data = json.dump(data, data_file)
dict.pop(<key>, not_found=None)
is probably what you where looking for, if I understood your requirements. Because it will remove the hours
key if present and will not fail if not present.
However I am not sure I understand why it makes a difference to you whether the hours key contains some days or not, because you just want to get rid of the whole key / value pair, right?
Now, if you really want to use del
instead of pop
, here is how you could make your code work:
import json
with open('data.json') as data_file:
data = json.load(data_file)
for element in data:
if 'hours' in element:
del element['hours']
with open('data.json', 'w') as data_file:
data = json.dump(data, data_file)
EDIT So, as you can see, I added the code to write the data back to the file. If you want to write it to another file, just change the filename in the second open statement.
I had to change the indentation, as you might have noticed, so that the file has been closed during the data cleanup phase and can be overwritten at the end.
with
is what is called a context manager, whatever it provides (here the data_file file descriptor) is available ONLY within that context. It means that as soon as the indentation of the with
block ends, the file gets closed and the context ends, along with the file descriptor which becomes invalid / obsolete.
Without doing this, you wouldn't be able to open the file in write mode and get a new file descriptor to write into.
I hope it's clear enough...
SECOND EDIT
This time, it seems clear that you need to do this:
with open('dest_file.json', 'w') as dest_file:
with open('source_file.json', 'r') as source_file:
for line in source_file:
element = json.loads(line.strip())
if 'hours' in element:
del element['hours']
dest_file.write(json.dumps(element))
If you're just checking if word
is a number, that's not too hard:
#include <ctype.h>
...
string word;
bool isNumber = true;
for(string::const_iterator k = word.begin(); k != word.end(); ++k)
isNumber &&= isdigit(*k);
Optimize as desired.
Not possible. If you want to customize the dialog's visual appearance, you need to use a JS-based solution like jQuery.UI dialog.
Get the current (debug | release).
specified_configs=$$find(CONFIG, "\b(debug|release)\b")
build_subdir=$$last(specified_configs)
(May be multiple, so keep only last specified in the build):
Use it has the build subdir name
DESTDIR = $$PWD/build/$$build_subdir
I have a set of scripting functions that I use extensively on my Red Hat system. They use the system functions from /etc/init.d/functions
to print green [ OK ]
and red [FAILED]
status indicators.
You can optionally set the $LOG_STEPS
variable to a log file name if you want to log which commands fail.
step "Installing XFS filesystem tools:"
try rpm -i xfsprogs-*.rpm
next
step "Configuring udev:"
try cp *.rules /etc/udev/rules.d
try udevtrigger
next
step "Adding rc.postsysinit hook:"
try cp rc.postsysinit /etc/rc.d/
try ln -s rc.d/rc.postsysinit /etc/rc.postsysinit
try echo $'\nexec /etc/rc.postsysinit' >> /etc/rc.sysinit
next
Installing XFS filesystem tools: [ OK ]
Configuring udev: [FAILED]
Adding rc.postsysinit hook: [ OK ]
#!/bin/bash
. /etc/init.d/functions
# Use step(), try(), and next() to perform a series of commands and print
# [ OK ] or [FAILED] at the end. The step as a whole fails if any individual
# command fails.
#
# Example:
# step "Remounting / and /boot as read-write:"
# try mount -o remount,rw /
# try mount -o remount,rw /boot
# next
step() {
echo -n "$@"
STEP_OK=0
[[ -w /tmp ]] && echo $STEP_OK > /tmp/step.$$
}
try() {
# Check for `-b' argument to run command in the background.
local BG=
[[ $1 == -b ]] && { BG=1; shift; }
[[ $1 == -- ]] && { shift; }
# Run the command.
if [[ -z $BG ]]; then
"$@"
else
"$@" &
fi
# Check if command failed and update $STEP_OK if so.
local EXIT_CODE=$?
if [[ $EXIT_CODE -ne 0 ]]; then
STEP_OK=$EXIT_CODE
[[ -w /tmp ]] && echo $STEP_OK > /tmp/step.$$
if [[ -n $LOG_STEPS ]]; then
local FILE=$(readlink -m "${BASH_SOURCE[1]}")
local LINE=${BASH_LINENO[0]}
echo "$FILE: line $LINE: Command \`$*' failed with exit code $EXIT_CODE." >> "$LOG_STEPS"
fi
fi
return $EXIT_CODE
}
next() {
[[ -f /tmp/step.$$ ]] && { STEP_OK=$(< /tmp/step.$$); rm -f /tmp/step.$$; }
[[ $STEP_OK -eq 0 ]] && echo_success || echo_failure
echo
return $STEP_OK
}
The compiler warnings happen on stderr
, not stdout
, which is why you don't see them when you just redirect make
somewhere else. Instead, try this if you're using Bash:
$ make &> results.txt
The &
means "redirect stdout and stderr to this location". Other shells often have similar constructs.
You can do like this
echo date('Y-m-d H:i:s', strtotime('4 minute'));
echo date('Y-m-d H:i:s', strtotime('6 hour'));
echo date('Y-m-d H:i:s', strtotime('2 day'));
Try the snipped which is mentioned below, it works for me also.
In my layout xml
where I have my TabLayout
, have added style to the TabLayout
like below :
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
style="@style/MyCustomTabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
and in my style.xml
I have defined the style that is used in my layout xml, check code for styles added below :
<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
<item name="android:background">YOUR BACKGROUND COLOR</item>
<item name="tabTextAppearance">@style/MyCustomTabText</item>
<item name="tabSelectedTextColor">SELECTED TAB TEXT COLOR</item>
<item name="tabIndicatorColor">SELECTED TAB INDICATOR COLOR</item>
</style>
<style name="MyCustomTabText" parent="TextAppearance.AppCompat.Button">
<item name="android:textSize">YOUR TEXT SIZE</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">@android:color/white</item>
</style>
I hope it will work for you.....
Do not load the javascript inside the cdn link script tag.Use a separate script tag for loading the AngularJs scripts.
I had the same issue but I created a separate <script>
Then the error gone.
Try using cmake itself. In the build directory, run:
cmake --build .
You can bind the DOMSubtreeModified event. I add an example here:
HTML
<div id="mutable" style="width:50px;height:50px;">sjdfhksfh<div>
<div>
<button id="changeClass">Change Class</button>
</div>
JavaScript
$(document).ready(function() {
$('#changeClass').click(function() {
$('#mutable').addClass("red");
});
$('#mutable').bind('DOMSubtreeModified', function(e) {
alert('class changed');
});
});
As an alternative to alex's answer:
You could use a SVG drawing instead of a Canvas drawing. There you can add events directly to the drawn DOM objects.
see for example:
Making an svg image object clickable with onclick, avoiding absolute positioning
This can happen if your application is in a virtual directory and the path to the files is a mapped drive.
If you change the path to the files to a local drive, this will solve it, if that indeed is your problem.
It's safe to just delete the source directory and compiled package file. Find the source directory under $GOPATH/src
and the package file under $GOPATH/pkg/<architecture>
, for example: $GOPATH/pkg/windows_amd64
.
I repeatedly had the same challenge sometime ago. This problem occurs mostly when you are trying to pull from the remote repository and you have some files on your local instance conflicting with the remote version, if you are using git from an IDE such as IntelliJ, you will be prompted and allowed to make a choice if you want to retain your own changes or you prefer the changes in the remote version to overwrite yours'. If you don't make any choice then you fall into this conflict. all you need to do is run:
git merge --abort # The unresolved conflict will be cleared off
And you can continue what you were doing before the break.
why not keep it simple
cd SOME_PATH && run_some_command && cd -
the last 'cd' command will take you back to the last pwd directory. This should work on all *nix systems.
From FormData documention:
XMLHttpRequest Level 2 adds support for the new FormData interface. FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the
XMLHttpRequest
send()
method.
With an XMLHttpRequest
you can set the custom headers and then do the POST
.
You can execute any class which has a public final static main
method from a JAR file, even if the jar file has a Main-Class
defined.
Execute Main-Class:
java -jar MyJar.jar // will execute the Main-Class
Execute another class with a public static void main
method:
java -cp MyJar.jar com.mycomp.myproj.AnotherClassWithMainMethod
Note: the first uses -jar
, the second uses -cp
.
Without CSS: Use the STYLE property of text input
STYLE="text-align: right;"
You can set the z-index in css
<div style="z-index: -1"></div>
ContainsKey is what you're looking for.
Use the .c_str()
method for const char *
.
You can use &mystring[0]
to get a char *
pointer, but there are a couple of gotcha's: you won't necessarily get a zero terminated string, and you won't be able to change the string's size. You especially have to be careful not to add characters past the end of the string or you'll get a buffer overrun (and probable crash).
There was no guarantee that all of the characters would be part of the same contiguous buffer until C++11, but in practice all known implementations of std::string
worked that way anyway; see Does “&s[0]” point to contiguous characters in a std::string?.
Note that many string
member functions will reallocate the internal buffer and invalidate any pointers you might have saved. Best to use them immediately and then discard.
Without JavaScript, it's not possible to open two pages by clicking one link unless both pages are framed on the one page that opens from clicking the link. With JS it's trivial:
<p><a href="#" onclick="window.open('http://google.com');
window.open('http://yahoo.com');">Click to open Google and Yahoo</a></p>
Do note that this will be blocked by popup blockers built into web browsers but you are usually notified of this.
I'm not 100% sure if this works in all cases (needs at least Java 1.5):
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class Main
{
public class A
{
}
public class B extends A
{
}
public Map<A, B> map = new HashMap<Main.A, Main.B>();
public static void main(String[] args)
{
try
{
Field field = Main.class.getField("map");
System.out.println("Field " + field.getName() + " is of type " + field.getType().getSimpleName());
Type genericType = field.getGenericType();
if(genericType instanceof ParameterizedType)
{
ParameterizedType type = (ParameterizedType) genericType;
Type[] typeArguments = type.getActualTypeArguments();
for(Type typeArgument : typeArguments)
{
Class<?> classType = ((Class<?>)typeArgument);
System.out.println("Field " + field.getName() + " has a parameterized type of " + classType.getSimpleName());
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This will output:
Field map is of type Map
Field map has a parameterized type of A
Field map has a parameterized type of B
In MSVC, you can use the CLR override
keyword even if you're not compiling for CLR.
In g++, there's no direct way of enforcing that in all cases; other people have given good answers on how to catch signature differences using -Woverloaded-virtual
. In a future version, someone might add syntax like __attribute__ ((override))
or the equivalent using the C++0x syntax.
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
File file = getYourFile();
Path path = file.toPath();
byte[] data = Files.readAllBytes(path);
You can use the hasClass
method, eg.
$('li.menu').hasClass('active') // true|false
Or if you want to select it in one go, you can use:
$('li.menu.active')
More pythonic way:
df = data_set[['data_date', 'data_1', 'data_2']]
map(tuple,df.values)
On Windows:-
Go to File -> Settings.
And open the 'Build,Execution,Deployment'
. Then open the
Build Tools -> Gradle
Then uncheck -> Offline work on the right.
Click the OK button.
Then Rebuild the Project.
On Mac OS:-
go to Android Studio -> Preferences, and the rest is the same. OR follow steps given in the image
[
Found a SOLUTION which works for me! Add one more rule in the file proguard-android.txt
:
-keepclassmembers class * extends android.webkit.WebChromeClient {
public void openFileChooser(...);
}
That is a very strange way to organize things. If you stored in a dictionary, this is easy:
# This example should work in any version of Python.
# urls_d will contain URL keys, with counts as values, like: {'http://www.google.fr/' : 1 }
urls_d = {}
for url in list_of_urls:
if not url in urls_d:
urls_d[url] = 1
else:
urls_d[url] += 1
This code for updating a dictionary of counts is a common "pattern" in Python. It is so common that there is a special data structure, defaultdict
, created just to make this even easier:
from collections import defaultdict # available in Python 2.5 and newer
urls_d = defaultdict(int)
for url in list_of_urls:
urls_d[url] += 1
If you access the defaultdict
using a key, and the key is not already in the defaultdict
, the key is automatically added with a default value. The defaultdict
takes the callable you passed in, and calls it to get the default value. In this case, we passed in class int
; when Python calls int()
it returns a zero value. So, the first time you reference a URL, its count is initialized to zero, and then you add one to the count.
But a dictionary full of counts is also a common pattern, so Python provides a ready-to-use class: containers.Counter
You just create a Counter
instance by calling the class, passing in any iterable; it builds a dictionary where the keys are values from the iterable, and the values are counts of how many times the key appeared in the iterable. The above example then becomes:
from collections import Counter # available in Python 2.7 and newer
urls_d = Counter(list_of_urls)
If you really need to do it the way you showed, the easiest and fastest way would be to use any one of these three examples, and then build the one you need.
from collections import defaultdict # available in Python 2.5 and newer
urls_d = defaultdict(int)
for url in list_of_urls:
urls_d[url] += 1
urls = [{"url": key, "nbr": value} for key, value in urls_d.items()]
If you are using Python 2.7 or newer you can do it in a one-liner:
from collections import Counter
urls = [{"url": key, "nbr": value} for key, value in Counter(list_of_urls).items()]
From javadoc:
Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a > apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself
Here is some better usage of java for scanner
try(Scanner sc = new Scanner(System.in)) {
//Use sc as you need
} catch (Exception e) {
// handle exception
}
You can try this with python 3:
from termcolor import colored
print(colored('Hello, World!', 'green', 'on_red'))
If you are using windows operating system, the above code may not work for you. Then you can try this code:
from colorama import init
from termcolor import colored
# use Colorama to make Termcolor work on Windows too
init()
# then use Termcolor for all colored text output
print(colored('Hello, World!', 'green', 'on_red'))
Hope that helps.
I was receiving the error (I'm using Vue) and I switched my onclick="someFunction()"
to @click="someFunction"
and now they are working.
Imagine a stack of paper. The last piece put into the stack is on the top, so it is the first one to come out. This is LIFO. Adding a piece of paper is called "pushing", and removing a piece of paper is called "popping".
Imagine a queue at the store. The first person in line is the first person to get out of line. This is FIFO. A person getting into line is "enqueued", and a person getting out of line is "dequeued".
better use quoted `data`
and `date`
. AFAIR these may be reserved words
my version is:
INSERT INTO `table` ( `data` , `date` ) VALUES('".$date."',NOW()+INTERVAL 1 DAY);
Question: Is there a simple way to do this in the current release of Python?
Answer: There is no simple (direct) way to do this in the current release of Python.
Reference: Please refer to docs.python.org/2/library/datetime.html, section 8.1.2. timedelta Objects. As we may understand from that, we cannot increment month directly since it is not a uniform time unit.
Plus: If you want first day -> first day and last day -> last day mapping you should handle that separately for different months.
I had given permissions I shouldn't have to write in some folders (especially /usr/bin/), and that caused the problem. I fixed it by opening Disk Utility and running 'Repair Disk Permissions' on the Macintosh HD disk.
With @Kevin van Mierlo 's answer, you are also capable of implementing several drawers. For instance, the default menu located on the left side (start), and a further optional menu, located on the right side, which is only shown when determinate fragments are loaded.
I've been able to do that.
Java doesn't natively allow building of an exe, that would defeat its purpose of being cross-platform.
AFAIK, these are your options:
Make a runnable JAR. If the system supports it and is configured appropriately, in a GUI, double clicking the JAR will launch the app. Another option would be to write a launcher shell script/batch file which will start your JAR with the appropriate parameters
There also executable wrappers - see How can I convert my Java program to an .exe file?
Here I am going to explain not only the GROUP clause use, but also the Aggregate functions use.
The GROUP BY
clause is used in conjunction with the aggregate functions to group the result-set by one or more columns. e.g.:
-- GROUP BY with one parameter:
SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;
-- GROUP BY with two parameters:
SELECT
column_name1,
column_name2,
AGGREGATE_FUNCTION(column_name3)
FROM
table_name
GROUP BY
column_name1,
column_name2;
Remember this order:
SELECT (is used to select data from a database)
FROM (clause is used to list the tables)
WHERE (clause is used to filter records)
GROUP BY (clause can be used in a SELECT statement to collect data across multiple records and group the results by one or more columns)
HAVING (clause is used in combination with the GROUP BY clause to restrict the groups of returned rows to only those whose the condition is TRUE)
ORDER BY (keyword is used to sort the result-set)
You can use all of these if you are using aggregate functions, and this is the order that they must be set, otherwise you can get an error.
Aggregate Functions are:
MIN() returns the smallest value in a given column
MAX() returns the maximum value in a given column.
SUM() returns the sum of the numeric values in a given column
AVG() returns the average value of a given column
COUNT() returns the total number of values in a given column
COUNT(*) returns the number of rows in a table
SQL script examples about using aggregate functions:
Let's say we need to find the sale orders whose total sale is greater than $950. We combine the HAVING
clause and the GROUP BY
clause to accomplish this:
SELECT
orderId, SUM(unitPrice * qty) Total
FROM
OrderDetails
GROUP BY orderId
HAVING Total > 950;
Counting all orders and grouping them customerID and sorting the result ascendant. We combine the COUNT
function and the GROUP BY
, ORDER BY
clauses and ASC
:
SELECT
customerId, COUNT(*)
FROM
Orders
GROUP BY customerId
ORDER BY COUNT(*) ASC;
Retrieve the category that has an average Unit Price greater than $10, using AVG
function combine with GROUP BY
and HAVING
clauses:
SELECT
categoryName, AVG(unitPrice)
FROM
Products p
INNER JOIN
Categories c ON c.categoryId = p.categoryId
GROUP BY categoryName
HAVING AVG(unitPrice) > 10;
Getting the less expensive product by each category, using the MIN
function in a subquery:
SELECT categoryId,
productId,
productName,
unitPrice
FROM Products p1
WHERE unitPrice = (
SELECT MIN(unitPrice)
FROM Products p2
WHERE p2.categoryId = p1.categoryId)
The following statement groups rows with the same values in both categoryId and productId columns:
SELECT
categoryId, categoryName, productId, SUM(unitPrice)
FROM
Products p
INNER JOIN
Categories c ON c.categoryId = p.categoryId
GROUP BY categoryId, productId
My solution, in case someone finds it useful.
In Web.config:
<system.web>
<customErrors mode="On" defaultRedirect="Error" >
<error statusCode="404" redirect="~/Error/PageNotFound"/>
</customErrors>
...
</system.web>
In Controllers/ErrorController.cs
:
public class ErrorController : Controller
{
public ActionResult PageNotFound()
{
if(Request.IsAjaxRequest()) {
Response.StatusCode = (int)HttpStatusCode.NotFound;
return Content("Not Found", "text/plain");
}
return View();
}
}
Add a PageNotFound.cshtml
in the Shared
folder, and that's it.
You can use os.system command for simplicity:
import os
os.system("rm -rf dirname")
As obvious, it actually invokes system terminal to accomplish this task.
Why noy just use the theme styles in the table? i.e.
<table>
<thead class="ui-widget-header">
<tr>
<th>Id</th>
<th>Description</th>
</td>
</thead>
<tbody class="ui-widget-content">
<tr>
<td>...</td>
<td>...</td>
</tr>
.
.
.
</tbody>
</table>
And you don't need to use any code...
boolean is a primitive data type in Java and primitive data types can not be null like other primitives int, float etc, they should be containing default values if not assigned.
In Java, only objects can assigned to null, it means the corresponding object has no reference and so does not contain any representation in memory.
Hence If you want to work with object as null , you should be using Boolean class which wraps a primitive boolean type value inside its object.
These are called wrapper classes in Java
For Example:
Boolean bool = readValue(...); // Read Your Value
if (bool == null) { do This ...}
I use let
to test my HTTP 404 responses in my API specs using contexts.
To create the resource, I use let!
. But to store the resource identifier, I use let
. Take a look how it looks like:
let!(:country) { create(:country) }
let(:country_id) { country.id }
before { get "api/countries/#{country_id}" }
it 'responds with HTTP 200' { should respond_with(200) }
context 'when the country does not exist' do
let(:country_id) { -1 }
it 'responds with HTTP 404' { should respond_with(404) }
end
That keeps the specs clean and readable.
This error can occur especially when you are updating large libraries or libraries with a lot of dependencies. Composer can be quite memory hungry.
Be sure that your composer itself is updated to the latest version:
php composer.phar --self-update
You can increase the memory limit for composer temporarily by adding the composer memory limit environment variable:
COMPOSER_MEMORY_LIMIT=128MB php composer.phar update
Use the format “128M” for megabyte or “2G” for gigabyte. You can use the value “-1” to ignore the memory limit completely.
Another way would be to increase the PHP memory limit:
php -d memory_limit=512M composer.phar update ...
I have found an elegant solution that would cover most of your bases. I wrote about it initially here and answered another similar StackOverflow question here which references it.
FYI this solution also includes hardcoded fallback tags in case Javascript isn't picked up by the crawler. I haven't explicitly outlined it, but it is worth mentioning that you should be activating HTML5 mode for proper URL support.
Also note: these aren't the complete files, just the important parts of those that are relevant. If you need help writing the boilerplate for directives, services, etc. that can be found elsewhere. Anyway, here goes...
app.js
This is where you provide the custom metadata for each of your routes (title, description, etc.)
$routeProvider
.when('/', {
templateUrl: 'views/homepage.html',
controller: 'HomepageCtrl',
metadata: {
title: 'The Base Page Title',
description: 'The Base Page Description' }
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl',
metadata: {
title: 'The About Page Title',
description: 'The About Page Description' }
})
metadata-service.js (service)
Sets the custom metadata options or use defaults as fallbacks.
var self = this;
// Set custom options or use provided fallback (default) options
self.loadMetadata = function(metadata) {
self.title = document.title = metadata.title || 'Fallback Title';
self.description = metadata.description || 'Fallback Description';
self.url = metadata.url || $location.absUrl();
self.image = metadata.image || 'fallbackimage.jpg';
self.ogpType = metadata.ogpType || 'website';
self.twitterCard = metadata.twitterCard || 'summary_large_image';
self.twitterSite = metadata.twitterSite || '@fallback_handle';
};
// Route change handler, sets the route's defined metadata
$rootScope.$on('$routeChangeSuccess', function (event, newRoute) {
self.loadMetadata(newRoute.metadata);
});
metaproperty.js (directive)
Packages the metadata service results for the view.
return {
restrict: 'A',
scope: {
metaproperty: '@'
},
link: function postLink(scope, element, attrs) {
scope.default = element.attr('content');
scope.metadata = metadataService;
// Watch for metadata changes and set content
scope.$watch('metadata', function (newVal, oldVal) {
setContent(newVal);
}, true);
// Set the content attribute with new metadataService value or back to the default
function setContent(metadata) {
var content = metadata[scope.metaproperty] || scope.default;
element.attr('content', content);
}
setContent(scope.metadata);
}
};
index.html
Complete with the hardcoded fallback tags mentioned earlier, for crawlers that can't pick up any Javascript.
<head>
<title>Fallback Title</title>
<meta name="description" metaproperty="description" content="Fallback Description">
<!-- Open Graph Protocol Tags -->
<meta property="og:url" content="fallbackurl.com" metaproperty="url">
<meta property="og:title" content="Fallback Title" metaproperty="title">
<meta property="og:description" content="Fallback Description" metaproperty="description">
<meta property="og:type" content="website" metaproperty="ogpType">
<meta property="og:image" content="fallbackimage.jpg" metaproperty="image">
<!-- Twitter Card Tags -->
<meta name="twitter:card" content="summary_large_image" metaproperty="twitterCard">
<meta name="twitter:title" content="Fallback Title" metaproperty="title">
<meta name="twitter:description" content="Fallback Description" metaproperty="description">
<meta name="twitter:site" content="@fallback_handle" metaproperty="twitterSite">
<meta name="twitter:image:src" content="fallbackimage.jpg" metaproperty="image">
</head>
This should help dramatically with most search engine use cases. If you want fully dynamic rendering for social network crawlers (which are iffy on Javascript support), you'll still have to use one of the pre-rendering services mentioned in some of the other answers.
Hope this helps!
I had same issue, none of the solutions worked for me.
Open Settings Menu -> Developer Options -> USB Debugging should be on
There are many ways. You use RelativeLayout or AbsoluteLayout.
With relative, you can have the image align with parent on the left side for example and also have the text align to the parent left too... then you can use margins and padding and gravity on the text view to get it lined where you want over the image.
In Server 2008 the startup folder for individual users is here:
C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
For All Users it's here:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
Hope that helps
Suggest the following simplification: capture return value from Workbooks.Add
instead of subscripting Windows()
afterward, as follows:
Set wkb = Workbooks.Add
wkb.SaveAs ...
wkb.Activate ' instead of Windows(expression).Activate
General Philosophy Advice:
Avoid use Excel's built-ins: ActiveWorkbook, ActiveSheet, and Selection: capture return values, and, favor qualified expressions instead.
Use the built-ins only once and only in outermost macros(subs) and capture at macro start, e.g.
Set wkb = ActiveWorkbook
Set wks = ActiveSheet
Set sel = Selection
During and within macros do not rely on these built-in names, instead capture return values, e.g.
Set wkb = Workbooks.Add 'instead of Workbooks.Add without return value capture
wkb.Activate 'instead of Activeworkbook.Activate
Also, try to use qualified expressions, e.g.
wkb.Sheets("Sheet3").Name = "foo" ' instead of Sheets("Sheet3").Name = "foo"
or
Set newWks = wkb.Sheets.Add
newWks.Name = "bar" 'instead of ActiveSheet.Name = "bar"
Use qualified expressions, e.g.
newWks.Name = "bar" 'instead of `xyz.Select` followed by Selection.Name = "bar"
These methods will work better in general, give less confusing results, will be more robust when refactoring (e.g. moving lines of code around within and between methods) and, will work better across versions of Excel. Selection, for example, changes differently during macro execution from one version of Excel to another.
Also please note that you'll likely find that you don't need to .Activate
nearly as much when using more qualified expressions. (This can mean the for the user the screen will flicker less.) Thus the whole line Windows(expression).Activate
could simply be eliminated instead of even being replaced by wkb.Activate
.
(Also note: I think the .Select statements you show are not contributing and can be omitted.)
(I think that Excel's macro recorder is responsible for promoting this more fragile style of programming using ActiveSheet, ActiveWorkbook, Selection, and Select so much; this style leaves a lot of room for improvement.)
In this context, the word "stub" is used in place of "mock", but for the sake of clarity and precision, the author should have used "mock", because "mock" is a sort of stub, but for testing. To avoid further confusion, we need to define what a stub is.
In the general context, a stub is a piece of program (typically a function or an object) that encapsulates the complexity of invoking another program (usually located on another machine, VM, or process - but not always, it can also be a local object). Because the actual program to invoke is usually not located on the same memory space, invoking it requires many operations such as addressing, performing the actual remote invocation, marshalling/serializing the data/arguments to be passed (and same with the potential result), maybe even dealing with authentication/security, and so on. Note that in some contexts, stubs are also called proxies (such as dynamic proxies in Java).
A mock is a very specific and restrictive kind of stub, because a mock is a replacement of another function or object for testing. In practice we often use mocks as local programs (functions or objects) to replace a remote program in the test environment. In any case, the mock may simulate the actual behaviour of the replaced program in a restricted context.
Most famous kinds of stubs are obviously for distributed programming, when needing to invoke remote procedures (RPC) or remote objects (RMI, CORBA). Most distributed programming frameworks/libraries automate the generation of stubs so that you don't have to write them manually. Stubs can be generated from an interface definition, written with IDL for instance (but you can also use any language to define interfaces).
Typically, in RPC, RMI, CORBA, and so on, one distinguishes client-side stubs, which mostly take care of marshaling/serializing the arguments and performing the remote invocation, and server-side stubs, which mostly take care of unmarshaling/deserializing the arguments and actually execute the remote function/method. Obviously, client stubs are located on the client side, while sever stubs (often called skeletons) are located on the server side.
Writing good efficient and generic stubs becomes quite challenging when dealing with object references. Most distributed object frameworks such as RMI and CORBA deal with distributed objects references, but that's something most programmers avoid in REST environments for instance. Typically, in REST environments, JavaScript programmers make simple stub functions to encapsulate the AJAX invocations (object serialization being supported by JSON.parse
and JSON.stringify
). The Swagger Codegen project provides an extensive support for automatically generating REST stubs in various languages.
If you're just using a vanilla form (not a ModelForm), you can set a Field initial value ( https://docs.djangoproject.com/en/2.2/ref/forms/fields/#django.forms.Field.initial ) like
class MyForm(forms.Form):
my_field = forms.BooleanField(initial=True)
If you're using a ModelForm, you can set a default value on the model field ( https://docs.djangoproject.com/en/2.2/ref/models/fields/#default ), which will apply to the resulting ModelForm, like
class MyModel(models.Model):
my_field = models.BooleanField(default=True)
Finally, if you want to dynamically choose at runtime whether or not your field will be selected by default, you can use the initial parameter to the form when you initialize it:
form = MyForm(initial={'my_field':True})
Here is a sample to find if there are match elements in another list
List<int> nums1 = new List<int> { 2, 4, 6, 8, 10 };
List<int> nums2 = new List<int> { 1, 3, 6, 9, 12};
if (nums1.Any(x => nums2.Any(y => y == x)))
{
Console.WriteLine("There are equal elements");
}
else
{
Console.WriteLine("No Match Found!");
}
Directly from ngStyle
docs:
Expression which evals to an object whose keys are CSS style names and values are corresponding values for those CSS keys.
<div ng-style="{'width': '20px', 'height': '20px', ...}"></div>
So you could do this:
<div ng-style="{'background-color': data.backgroundCol}"></div>
Hope this helps!
You can use 'onclick' attribute like this :
<a ... href="javascript: onclick();" ...>...</a>
In the C++ standard, cout
is defined in the std
namespace, so you need to either say std::cout
or put
using namespace std;
in your code in order to get at it.
However, this was not always the case, and in the past cout
was just in the global namespace (or, later on, in both global and std
). I would therefore conclude that your classes used an older C++ compiler.
I have an Angular4 application, even for me also it was not working in IE11 browser, i have done below changes, now its working correctly. Just add below code in the index.html file
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
Just you need to uncomment these below lines from polyfills.ts file
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';
These above 2 steps will solve your problem, please let me know if anything will be there. Thanks!!!
You don't need custom directive here. Just use ng-include src attribute. It's compiled so you can put code inside. See plunker with solution for your issue.
<div ng-repeat="week in [1,2]">
<div ng-repeat="day in ['monday', 'tuesday']">
<ng-include src="'content/before-'+ week + '-' + day + '.html'"></ng-include>
</div>
</div>
Even if it is really discouraged to use merge cells in Excel (use Center Across Selection
for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).
Hence, you can get the value of merged cells in range B4:B11
in several ways:
Range("B4").Value
Range("B4:B11").Cells(1).Value
Range("B4:B11").Cells(1,1).Value
You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty
.
Also note that Range("B4:B11").Value
won't work (raises an execution error number 13 if you try to Debug.Print
it) because it returns an array.
In case you have still the error after providing component dialog class in entryComponents
, try to restart ng serve
- it worked for me.
You say:
For another, lists can be returned from functions even though you never passed in a List when you called the function, and even though the function doesn't contain a List constructor, e.g.,
x = strsplit(LETTERS[1:10], "") # passing in an object of type 'character'
class(x)
# => 'list'
And I guess you suggest that this is a problem(?). I'm here to tell you why it's not a problem :-). Your example is a bit simple, in that when you do the string-split, you have a list with elements that are 1 element long, so you know that x[[1]]
is the same as unlist(x)[1]
. But what if the result of strsplit
returned results of different length in each bin. Simply returning a vector (vs. a list) won't do at all.
For instance:
stuff <- c("You, me, and dupree", "You me, and dupree",
"He ran away, but not very far, and not very fast")
x <- strsplit(stuff, ",")
xx <- unlist(strsplit(stuff, ","))
In the first case (x
: which returns a list), you can tell what the 2nd "part" of the 3rd string was, eg: x[[3]][2]
. How could you do the same using xx
now that the results have been "unraveled" (unlist
-ed)?
Moral of the story:
Inherit only if you want to override some behavior.
Or rather it should be read as:
Inherit less, interface more.
Change in your html with adding the function on the button click
<input type="button" value="Clear" onclick="javascript:eraseText();">
<textarea id='output' rows=20 cols=90></textarea>
Try this in your js file:
function eraseText() {
document.getElementById("output").value = "";
}
I've encountered this problem when the build is abruptly closed before it is loaded. No process would show up in the Task Manager, but if you navigate to the executable generated in the project folder and try to delete it, Windows claims that the application is in use. (If not, just delete the file and rebuild, which generates a new executable) In Windows(Visual Studio 2019), the file is located in this directory by default:
%USERPROFILE%\source\repos\ProjectFolderName\Debug
To end the allegedly running process, open the command prompt and type in the following command:
taskkill /F /IM ApplicationName.exe
This forces any running instance to be terminated. Rebuild and execute!
You can right-click on the project, click on export, type 'jar', choose 'Runnable JAR File Export'. There you have the option 'Extract required libraries into generated JAR'.
Android will not update support libraries after 28.0.0
.
This will be the last feature release under the android.support packaging, and developers are encouraged to migrate to AndroidX 1.0.0.
So use library AndroidX.
androidx
or any library, because alpha, beta, rc can have bugs which you dont want to ship with your app.In your case
dependencies {
implementation 'androidx.appcompat:appcompat:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.1'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.cardview:cardview:1.0.0'
}
My solution was just simple as: have you tried turning it off and on again? So I restarted the computer and the issue was gone.
Convert.Tostring() function handles the NULL whereas the .ToString() method does not. visit here.
Filter your script tags and run each of them with eval
var tmp= document.createElement('div');
tmp.innerHTML = '<script>alert("hello")></script>';
[...tmp.children].filter(x => x.nodeName === 'SCRIPT').forEach(x => eval(x.innerText));
Use the in
keyword.
if 'apples' in d:
if d['apples'] == 20:
print('20 apples')
else:
print('Not 20 apples')
If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get
function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None
instead):
if d.get('apples', 0) == 20:
print('20 apples.')
else:
print('Not 20 apples.')
In addition to what others have said, you can also expand your selection using pattern searches.
For example, v/foo will select from your current position to the next instance of "foo." If you actually wanted to expand to the next instance of "foo," on line 35, for example, just press n to expand selection to the next instance, and so on.
I don't often do it, but I know that some people use marks extensively to make visual selections. For example, if I'm on line 5 and I want to select to line 35, I might press ma to place mark a
on line 5, then :35 to move to line 35. Shift + v to enter linewise visual mode, and finally `a to select back to mark a
.
Zamples is another site where you write a java code and run it online. Here you have possibility to choose jdk version also. http://www.zamples.com/JspExplorer/index.jsp?format=jdk16cl
MFMailComposeViewController is the way to go after the release of iPhone OS 3.0 software. You can look at the sample code or the tutorial I wrote.
ECMAscript 6 introduced Object.assign()
to achieve this natively in Javascript.
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
MDN documentation on Object.assign()
var o1 = { a: 1 };_x000D_
var o2 = { b: 2 };_x000D_
var o3 = { c: 3 };_x000D_
_x000D_
var obj = Object.assign({}, o1, o2, o3);_x000D_
console.log(obj); // { a: 1, b: 2, c: 3 }
_x000D_
Object.assign
is supported in many modern browsers but not yet all of them. Use a transpiler like Babel and Traceur to generate backwards-compatible ES5 JavaScript.
printf
accepts a variable number of arguments. Those can only have Plain Old Data (POD) types. Code that passes anything other than POD to printf
only compiles because the compiler assumes you got your format right. %s
means that the respective argument is supposed to be a pointer to a char
. In your case it is an std::string
not const char*
. printf
does not know it because the argument type goes lost and is supposed to be restored from the format parameter. When turning that std::string
argument into const char*
the resulting pointer will point to some irrelevant region of memory instead of your desired C string. For that reason your code prints out gibberish.
While printf
is an excellent choice for printing out formatted text, (especially if you intend to have padding), it can be dangerous if you haven't enabled compiler warnings. Always enable warnings because then mistakes like this are easily avoidable. There is no reason to use the clumsy std::cout
mechanism if the printf
family can do the same task in a much faster and prettier way. Just make sure you have enabled all warnings (-Wall -Wextra
) and you will be good. In case you use your own custom printf
implementation you should declare it with the __attribute__
mechanism that enables the compiler to check the format string against the parameters provided.
I was looking for something along what you wanted, but wanted to put it back into a variable.
So this is what I did
variable = ['hello this is x' x ', this is now y' y ', finally this is d:' d]
basically
variable = [str1 str2 str3 str4 str5 str6]
To post files as from byte arrays:
private static string UploadFilesToRemoteUrl(string url, IList<byte[]> files, NameValueCollection nvc) {
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
var request = (HttpWebRequest) WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
var postQueue = new ByteArrayCustomQueue();
var formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
foreach (string key in nvc.Keys) {
var formitem = string.Format(formdataTemplate, key, nvc[key]);
var formitembytes = Encoding.UTF8.GetBytes(formitem);
postQueue.Write(formitembytes);
}
var headerTemplate = "\r\n--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
"Content-Type: application/zip\r\n\r\n";
var i = 0;
foreach (var file in files) {
var header = string.Format(headerTemplate, "file" + i, "file" + i + ".zip");
var headerbytes = Encoding.UTF8.GetBytes(header);
postQueue.Write(headerbytes);
postQueue.Write(file);
i++;
}
postQueue.Write(Encoding.UTF8.GetBytes("\r\n--" + boundary + "--"));
request.ContentLength = postQueue.Length;
using (var requestStream = request.GetRequestStream()) {
postQueue.CopyToStream(requestStream);
requestStream.Close();
}
var webResponse2 = request.GetResponse();
using (var stream2 = webResponse2.GetResponseStream())
using (var reader2 = new StreamReader(stream2)) {
var res = reader2.ReadToEnd();
webResponse2.Close();
return res;
}
}
public class ByteArrayCustomQueue {
private LinkedList<byte[]> arrays = new LinkedList<byte[]>();
/// <summary>
/// Writes the specified data.
/// </summary>
/// <param name="data">The data.</param>
public void Write(byte[] data) {
arrays.AddLast(data);
}
/// <summary>
/// Gets the length.
/// </summary>
/// <value>
/// The length.
/// </value>
public int Length { get { return arrays.Sum(x => x.Length); } }
/// <summary>
/// Copies to stream.
/// </summary>
/// <param name="requestStream">The request stream.</param>
/// <exception cref="System.NotImplementedException"></exception>
public void CopyToStream(Stream requestStream) {
foreach (var array in arrays) {
requestStream.Write(array, 0, array.Length);
}
}
}
Sure, you just call it from within the SP, there's no special syntax.
Ex:
PROCEDURE some_sp
AS
BEGIN
some_other_sp('parm1', 10, 20.42);
END;
If the procedure is in a different schema than the one the executing procedure is in, you need to prefix it with schema name.
PROCEDURE some_sp
AS
BEGIN
other_schema.some_other_sp('parm1', 10, 20.42);
END;
If you want to add attributes, including the class, you need to set runat="server"
on the tag.
<div id="classMe" runat="server"></div>
Then in the code-behind:
classMe.Attributes.Add("class", "some-class")
The same way you do it in other db system, you can use the name of the db for identifying double named tables. unique tablenames can used directly.
select * from ttt.table_name;
or if table name in all attached databases is unique
select * from my_unique_table_name;
But I think the of of sqlite-shell is only for manual lookup or manual data manipulation and therefor this way is more inconsequential
normally you would use sqlite-command-line in a script
It only worked with me when I used sudo:
sudo pip install --upgrade google-api-python-client
Use setTimeout function with either of the following
// simulates similar behavior as an HTTP redirect
window.location.replace("http://www.google.com");
// simulates similar behavior as clicking on a link
window.location.href = "http://www.google.com";
setTimeout(function(){
window.location.replace("http://www.google.com");
}, 1000)
For a Fragment you can simply add
getActivity().onBackPressed();
to your code
I built on the last answer and used display:table
for an outer div, and display:table-cell
for inner divs.
This was the only thing that worked for me using CSS.
If you use Java >= 7, you could improve the accepted solution using try with resources:
private byte[] convertToBytes(Object object) throws IOException {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos)) {
out.writeObject(object);
return bos.toByteArray();
}
}
And the other way around:
private Object convertFromBytes(byte[] bytes) throws IOException, ClassNotFoundException {
try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream in = new ObjectInputStream(bis)) {
return in.readObject();
}
}
I would like to add required attribute in case user disabled javascript:
<input type="text" id="textbox" required/>
It works on all modern browsers.
This is common issue and its looking for .cmd
file from your root directory where you installed babel-cli
. Try the below command.
./node_modules/.bin/babel.cmd
Once you are able to see your source code in the command prompt. Your next step is to install one more npm module babel-preset-es2015
.
Follow the below answer to install babel-preset-es2015
and see why babel need this.
You can get the exact age using timesstamp:
const getAge = (dateOfBirth, dateToCalculate = new Date()) => {
const dob = new Date(dateOfBirth).getTime();
const dateToCompare = new Date(dateToCalculate).getTime();
const age = (dateToCompare - dob) / (365 * 24 * 60 * 60 * 1000);
return Math.floor(age);
};
Is there a way to limit a regex to 100 characters WITH regex?
Your example suggests that you'd like to grab a number from inside the regex and then use this number to place a maximum length on another part that is matched later in the regex. This usually isn't possible in a single pass. Your best bet is to have two separate regular expressions:
If you just want to limit the number of characters matched by an expression, most regular expressions support bounds by using braces. For instance,
\d{3}-\d{3}-\d{4}
will match (US) phone numbers: exactly three digits, then a hyphen, then exactly three digits, then another hyphen, then exactly four digits.
Likewise, you can set upper or lower limits:
\d{5,10}
means "at least 5, but not more than 10 digits".
Update: The OP clarified that he's trying to limit the value, not the length. My new answer is don't use regular expressions for that. Extract the value, then compare it against the maximum you extracted from the size parameter. It's much less error-prone.
I was having the same problem until I read Jon Skeet's answer about the debugger displaying a single backslash with a double backslash even though the string may have a single backslash. I was not aware of that. So I changed my code from
text2 = text1.Replace(@"\\", @"/");
to
text2 = text1.Replace(@"\", @"/");
and that solved the problem. Note: I'm interfacing and R.Net which uses single forward slashes in path strings.
onProgressChanged() should be called on every progress changed, not just on first and last touch (that why you have onStartTrackingTouch() and onStopTrackingTouch() methods).
Make sure that your SeekBar have more than 1 value, that is to say your MAX>=3.
In your onCreate:
yourSeekBar=(SeekBar) findViewById(R.id.yourSeekBar);
yourSeekBar.setOnSeekBarChangeListener(new yourListener());
Your listener:
private class yourListener implements SeekBar.OnSeekBarChangeListener {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// Log the progress
Log.d("DEBUG", "Progress is: "+progress);
//set textView's text
yourTextView.setText(""+progress);
}
public void onStartTrackingTouch(SeekBar seekBar) {}
public void onStopTrackingTouch(SeekBar seekBar) {}
}
Please share some code and the Log results for furter help.
Use the str.rindex
method.
>>> 'hello'.rindex('l')
3
>>> 'hello'.index('l')
2
Do it this way (make necessary changes in code)..
SqlConnection con = new SqlConnection(GetConnectionString());
con.Open();
SqlCommand cmd = new SqlCommand("CheckUser", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("username", username.Text);
SqlParameter p2 = new SqlParameter("password", password.Text);
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
SqlDataReader rd = cmd.ExecuteReader();
if(rd.HasRows)
{
//do the things
}
else
{
lblinfo.Text = "abc";
}
I don't think it's a matter of being Pythonic or elegant. It's a matter of preventing exceptions as much as you can. Exceptions are meant to handle errors that might occur in code or events you have no control over.
In this case, you have full control when checking if an item is an attribute or in a dictionary, so avoid nested exceptions and stick with your second attempt.
Here's a ruby script that uses nokogiri -- http://nokogiri.rubyforge.org/nokogiri/
require 'nokogiri'
doc = Nokogiri::HTML(table_string)
doc.xpath('//table//tr').each do |row|
row.xpath('td').each do |cell|
print '"', cell.text.gsub("\n", ' ').gsub('"', '\"').gsub(/(\s){2,}/m, '\1'), "\", "
end
print "\n"
end
Worked for my basic test case.
You can use subSequence , it's same as substr in C
Str.subSequence(int Start , int End)
if you don't want to create a UDF in VBA or you can't, this could be an alternative.
=Cell("Filename",A1)
this will give you the full file name, and from this you could get the user name with something like this:
=Mid(A1,Find("\",A1,4)+1;Find("\";A1;Find("\";A1;4))-2)
This Formula runs only from a workbook saved earlier.
You must start from 4th position because of the first slash from the drive.
Specific to the navigation icon, this is the correct order
// get the actionbar as Toolbar and set it up
Toolbar toolbar = (Toolbar) findViewById(R.id.signIn_toolbar);
setSupportActionBar(toolbar);
Inform the Toolbar to provide back navigation. This will set the icon to the default material icon
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Later override the icon with the custom one, in my case the Holo back icon
toolbar.setNavigationIcon(R.drawable.ic_chevron_left_white_36dp);
Fixing the seed is essential when we try to optimize a function that involves randomly generated numbers (e.g. in simulation based estimation). Loosely speaking, if we do not fix the seed, the variation due to drawing different random numbers will likely cause the optimization algorithm to fail.
Suppose that, for some reason, you want to estimate the standard deviation (sd) of a mean-zero normal distribution by simulation, given a sample. This can be achieved by running a numerical optimization around steps
The following functions do this, once without step 1., once including it:
# without fixing the seed
simllh <- function(sd, y, Ns){
simdist <- density(rnorm(Ns, mean = 0, sd = sd))
llh <- sapply(y, function(x){ simdist$y[which.min((x - simdist$x)^2)] })
return(-sum(log(llh)))
}
# same function with fixed seed
simllh.fix.seed <- function(sd,y,Ns){
set.seed(48)
simdist <- density(rnorm(Ns,mean=0,sd=sd))
llh <- sapply(y,function(x){simdist$y[which.min((x-simdist$x)^2)]})
return(-sum(log(llh)))
}
We can check the relative performance of the two functions in discovering the true parameter value with a short Monte Carlo study:
N <- 20; sd <- 2 # features of simulated data
est1 <- rep(NA,1000); est2 <- rep(NA,1000) # initialize the estimate stores
for (i in 1:1000) {
as.numeric(Sys.time())-> t; set.seed((t - floor(t)) * 1e8 -> seed) # set the seed to random seed
y <- rnorm(N, sd = sd) # generate the data
est1[i] <- optim(1, simllh, y = y, Ns = 1000, lower = 0.01)$par
est2[i] <- optim(1, simllh.fix.seed, y = y, Ns = 1000, lower = 0.01)$par
}
hist(est1)
hist(est2)
The resulting distributions of the parameter estimates are:
When we fix the seed, the numerical search ends up close to the true parameter value of 2 far more often.
I am running on FreeBSD 11.1, the freebsd jail virtualization concept makes the operating system optimal. The current version of Git I am using is 2.15.1, I also prefer to run everything on shell scripts. With that in mind I modified the suggestions above as followed:
git push: .git/hooks/pre-commit
#! /bin/sh -
#
# A hook script called by "git commit" with no arguments. The hook should
# exit with non-zero status after issuing an appropriate message if it wants
# to stop the commit.
SELF_DIR=$(git rev-parse --show-toplevel);
DATABASE=$SELF_DIR/.permissions;
# Clear the permissions database file
> $DATABASE;
printf "Backing-up file permissions...\n";
OLDIFS=$IFS;
IFS=$'\n';
for FILE in $(git ls-files);
do
# Save the permissions of all the files in the index
printf "%s;%s\n" $FILE $(stat -f "%Lp;%u;%g" $FILE) >> $DATABASE;
done
IFS=$OLDIFS;
# Add the permissions database file to the index
git add $DATABASE;
printf "OK\n";
git pull: .git/hooks/post-merge
#! /bin/sh -
SELF_DIR=$(git rev-parse --show-toplevel);
DATABASE=$SELF_DIR/.permissions;
printf "Restoring file permissions...\n";
OLDIFS=$IFS;
IFS=$'\n';
while read -r LINE || [ -n "$LINE" ];
do
FILE=$(printf "%s" $LINE | cut -d ";" -f 1);
PERMISSIONS=$(printf "%s" $LINE | cut -d ";" -f 2);
USER=$(printf "%s" $LINE | cut -d ";" -f 3);
GROUP=$(printf "%s" $LINE | cut -d ";" -f 4);
# Set the file permissions
chmod $PERMISSIONS $FILE;
# Set the file owner and groups
chown $USER:$GROUP $FILE;
done < $DATABASE
IFS=$OLDIFS
pritnf "OK\n";
exit 0;
If for some reason you need to recreate the script the .permissions file output should have the following format:
.gitignore;644;0;0
For a .gitignore file with 644 permissions given to root:wheel
Notice I had to make a few changes to the stat options.
Enjoy,
One of the numerous niceties of Ruby is the possibility to extend existing classes with your own methods. That's called "class reopening" or monkey-patching (the meaning of the latter can vary, though).
So, take a look here:
car = {:make => "bmw", :year => "2003"}
# => {:make=>"bmw", :year=>"2003"}
car.to_json
# NoMethodError: undefined method `to_json' for {:make=>"bmw", :year=>"2003"}:Hash
# from (irb):11
# from /usr/bin/irb:12:in `<main>'
require 'json'
# => true
car.to_json
# => "{"make":"bmw","year":"2003"}"
As you can see, requiring json
has magically brought method to_json
to our Hash
.
Use this:
#include <stdlib.h>
#include <string.h>
int main()
{
const char *d1 = "11";
int d1int = atoi(d1);
printf("d1 = %d\n", d1);
return 0;
}
etc.
You can override the onDraw method of your view and draw the circle.
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, radius, paint);
}
For a better reference on drawing custom views check out the official Android documentation.
http://developer.android.com/training/custom-views/custom-drawing.html
The code you're using is also going to include a fadeout effect. Is this what you want to achieve? If not, it might make more sense to just add the following INSIDE "Small.php".
<meta http-equiv="refresh" content="15" >
This adds a refresh every 15seconds to the small.php page which should mean if called by PHP into another page, only that "frame" will reload.
Let us know if it worked/solved your problem!?
-Brad
Your web pages are served by an application pool. If you disable/stop the application pool, and anyone tries to browse the application, you will get a Service Unavailable. It can happen due to multiple reasons...
Your application may have crashed [check the event viewer and see if you can find event logs in your Application/System log]
Your application may be crashing very frequently. If an app pool crashes for 5 times in 5 minutes [check your application pool settings for rapid fail], your application pool is disabled by IIS and you will end up getting this message.
In either case, the issue is that your worker process is failing and you should troubleshoot it from crash perspective.
What is a Crash (technically)... in ASP.NET and what to do if it happens?
You need to store the returned function and call it to unsubscribe from the event.
var deregisterListener = $scope.$on("onViewUpdated", callMe);
deregisterListener (); // this will deregister that listener
This is found in the source code :) at least in 1.0.4. I'll just post the full code since it's short
/**
* @param {string} name Event name to listen on.
* @param {function(event)} listener Function to call when the event is emitted.
* @returns {function()} Returns a deregistration function for this listener.
*/
$on: function(name, listener) {
var namedListeners = this.$$listeners[name];
if (!namedListeners) {
this.$$listeners[name] = namedListeners = [];
}
namedListeners.push(listener);
return function() {
namedListeners[indexOf(namedListeners, listener)] = null;
};
},
Also, see the docs.
May be will be useful. Just all queries send via ws to node
<VirtualHost *:80>
ServerName www.domain2.com
<Location "/">
ProxyPass "ws://localhost:3001/"
</Location>
</VirtualHost>
The overall dimensions of a range are in its Width
and Height
properties.
Dim r As Range
Set r = ActiveSheet.Range("A4:H12")
Debug.Print r.Width
Debug.Print r.Height
You can use the extension method AsEnumerable in Assembly System.Core and System.Linq namespace :
List<Book> list = new List<Book>();
return list.AsEnumerable();
This will, as said on this MSDN link change the type of the List in compile-time. This will give you the benefits also to only enumerate your collection we needed (see MSDN example for this).
Here's the full text article from hubbardr's dead link to my blog.
I found the following snippet while reading the source for Tempfile#initialize
in the Ruby core library:
begin
tmpname = File.join(tmpdir, make_tmpname(basename, n))
lock = tmpname + '.lock'
n += 1
end while @@cleanlist.include?(tmpname) or
File.exist?(lock) or File.exist?(tmpname)
At first glance, I assumed the while
modifier would be evaluated before the contents of begin...end
, but that is not the case. Observe:
>> begin
?> puts "do {} while ()"
>> end while false
do {} while ()
=> nil
As you would expect, the loop will continue to execute while the modifier is true.
>> n = 3
=> 3
>> begin
?> puts n
>> n -= 1
>> end while n > 0
3
2
1
=> nil
While I would be happy to never see this idiom again, begin...end
is quite powerful. The following is a common idiom to memoize a one-liner method with no params:
def expensive
@expensive ||= 2 + 2
end
Here is an ugly, but quick way to memoize something more complex:
def expensive
@expensive ||=
begin
n = 99
buf = ""
begin
buf << "#{n} bottles of beer on the wall\n"
# ...
n -= 1
end while n > 0
buf << "no more bottles of beer"
end
end
glOrtho describes a transformation that produces a parallel projection. The current matrix (see glMatrixMode) is multiplied by this matrix and the result replaces the current matrix, as if glMultMatrix were called with the following matrix as its argument:
OpenGL documentation (my bold)
The numbers define the locations of the clipping planes (left, right, bottom, top, near and far).
The "normal" projection is a perspective projection that provides the illusion of depth. Wikipedia defines a parallel projection as:
Parallel projections have lines of projection that are parallel both in reality and in the projection plane.
Parallel projection corresponds to a perspective projection with a hypothetical viewpoint—e.g., one where the camera lies an infinite distance away from the object and has an infinite focal length, or "zoom".
Splitting a string by whitespace is very simple:
print $_, "\n" for split ' ', 'file1.gz file1.gz file3.gz';
This is a special form of split
actually (as this function usually takes patterns instead of strings):
As another special case,
split
emulates the default behavior of the command line toolawk
when thePATTERN
is either omitted or a literal string composed of a single space character (such as' '
or"\x20"
). In this case, any leading whitespace inEXPR
is removed before splitting occurs, and thePATTERN
is instead treated as if it were/\s+/
; in particular, this means that any contiguous whitespace (not just a single space character) is used as a separator.
Here's an answer for the original question (with a simple string without any whitespace):
Perhaps you want to split on .gz
extension:
my $line = "file1.gzfile1.gzfile3.gz";
my @abc = split /(?<=\.gz)/, $line;
print $_, "\n" for @abc;
Here I used (?<=...)
construct, which is look-behind assertion, basically making split at each point in the line preceded by .gz
substring.
If you work with the fixed set of extensions, you can extend the pattern to include them all:
my $line = "file1.gzfile2.txtfile2.gzfile3.xls";
my @exts = ('txt', 'xls', 'gz');
my $patt = join '|', map { '(?<=\.' . $_ . ')' } @exts;
my @abc = split /$patt/, $line;
print $_, "\n" for @abc;
Answer 1 worked perfectly for me. I tested it on a new MID 10' tablet. Here are the lines I added in the .inf file and it installed without a problem:
;Google MID
%SingleAdbInterface% = USB_INSTALL, USB\Vid_18d1&Pid_0003&MI_01
%CompositeAdbInterface% = USB_INSTALL, USB\Vid_18d1&Pid_0003&Rev_0230&MI_01
You may come across this message/error, after installing epel-release. The quick fix is to update your SSL certificates:
yum -y upgrade ca-certificates
Chances are the above error may also occur while certificate update, if so, just disable the epel
repo i.e. use the following command:
yum -y upgrade ca-certificates --disablerepo=epel
Once the certificates will be updated, you'll be able to use yum normally, even the epel repo will work fine. In case you're getting this same error for a different repo, just put it's name against the --disablerepo=<repo-name>
flag.
Note: use sudo
if you're not the root
user.
I found it on this page: http://eslint.org/docs/user-guide/configuring
In package.json, this works:
"eslintConfig": {
"globals": {
"window": true
}
}
See: Multiple-line-syntax
It also support variables in multiline string, for example:
String name="zzg";
String lines = ""/**~!{
SELECT *
FROM user
WHERE name="$name"
}*/;
System.out.println(lines);
Output:
SELECT *
FROM user
WHERE name="zzg"
If you are using CentOS the built in yum
repositories don't seem to have git
included and as such, you will need to add an additional repository to the system. For my servers I found that the Webtatic repository seems to be reasonably up to date and the installation for git
will then be as follows:
# Add the repository
rpm -Uvh http://repo.webtatic.com/yum/centos/5/latest.rpm
# Install the latest version of git
yum install --enablerepo=webtatic git-all
To work around Missing Dependency: perl(Git)
errors:
yum install --enablerepo=webtatic --disableexcludes=main git-all
Bootstrap sets a .in
class on the Collapse element to trigger the animation – to open it. If you simply remove the .in
class, the animation doesn't run, but will hide the element – not exactly what you want.
Likely faster to run an if
statement to check if the default bootstrap class .in
has been set on the element.
So this code just says:
if my element has the class
.in
applied, close it by triggering the default Bootstrap animation. Otherwise run the default Bootstrap action/animation of opening it
$('#navbar a').on('click touchstart', function() {
// if .in class is set on element, the element is visible – you want to hide it
if ($('#navbar').hasClass('in')) {
// collapse toggle will remove the .in class and animate the element closed
$('#navbar').collapse('toggle');
}
})
whatever yyy is undefined or null, it will return true
if (typeof yyy == 'undefined' || !yyy) {
console.log('yes');
} else {
console.log('no');
}
yes
if (!(typeof yyy == 'undefined' || !yyy)) {
console.log('yes');
} else {
console.log('no');
}
no
Also consider that if you click a button, the target of the event listener is not necessaily the button itself, but whatever content inside the button you clicked on. You can reference the element to which you assigned the listener using the currentTarget property. Here is a pretty solution in modern ES using a single statement:
document.querySelectorAll(".myClassName").forEach(i => i.addEventListener(
"click",
e => {
alert(e.currentTarget.dataset.myDataContent);
}));
window.history.pushState({urlPath:'/page1'},"",'/page1')
Only works after page is loaded, and when you will click on refresh it doesn't mean that there is any real URL.
What you should do here is knowing to which URL you are getting redirected when you reload this page. And on that page you can get the conditions by getting the current URL and making all of your conditions.
In this specific case (mod 7), we still can replace %7 with bitwise operators:
// Return X%7 for X >= 0.
int mod7(int x)
{
while (x > 7) x = (x&7) + (x>>3);
return (x == 7)?0:x;
}
It works because 8%7 = 1. Obviously, this code is probably less efficient than a simple x%7, and certainly less readable.
https://support.procore.com/faq/what-is-the-difference-between-sp-and-idp-initiated-sso
There is much more to this but this is a high level overview on which is which.
Procore supports both SP- and IdP-initiated SSO:
Identity Provider Initiated (IdP-initiated) SSO. With this option, your end users must log into your Identity Provider's SSO page (e.g., Okta, OneLogin, or Microsoft Azure AD) and then click an icon to log into and open the Procore web application. To configure this solution, see Configure IdP-Initiated SSO for Microsoft Azure AD, Configure Procore for IdP-Initated Okta SSO, or Configure IdP-Initiated SSO for OneLogin. OR Service Provider Initiated (SP-initiated) SSO. Referred to as Procore-initiated SSO, this option gives your end users the ability to sign into the Procore Login page and then sends an authorization request to the Identify Provider (e.g., Okta, OneLogin, or Microsoft Azure AD). Once the IdP authenticates the user's identify, the user is logged into Procore. To configure this solution, see Configure Procore-Initiated SSO for Microsoft Azure Active Directory, Configure Procore-Initiated SSO for Okta, or Configure Procore-Initiated SSO for OneLogin.
In addition to what John Skeet said, here's an overview of the Java 7 project. It includes a list and description of the features.
Note: JDK 7 was released on July 28, 2011, so you should now go to the official java SE site.
From the grep(1)
man page:
-l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match. (-l is specified by POSIX.)
In my case the error occurred when I renamed a DLL after building it (using Visual Studio 2015), so that it fits the name expected by an executable, which depended on the DLL. After the renaming the list of exported symbols displayed by Dependency Walker was empty, and the said error message "The application was unable to start correctly" was displayed.
So it could be fixed by changing the output file name in the Visual Studio linker options.
This is a build path issue.
Make sure your bin folder is not included in your build path.
Right click on your project -> go to properties -> Build Path.
Make sure that Honeycomb library is in your libs/
folder and not in your source folder.
Include the libraries in libs/
individually in the build path.
BTW, you may want to bring in the android-support-v4
library to get Ice Cream Sandwich support instead of the Honeycomb support library.
If you don't want to use jsonify
for some reason, you can do what it does manually. Call flask.json.dumps
to create JSON data, then return a response with the application/json
content type.
from flask import json
@app.route('/summary')
def summary():
data = make_summary()
response = app.response_class(
response=json.dumps(data),
mimetype='application/json'
)
return response
flask.json
is distinct from the built-in json
module. It will use the faster simplejson
module if available, and enables various integrations with your Flask app.
To keep your window open in case of exception (yet, while printing the exception)
if __name__ == '__main__':
try:
## your code, typically one function call
except Exception:
import sys
print sys.exc_info()[0]
import traceback
print traceback.format_exc()
print "Press Enter to continue ..."
raw_input()
To keep the window open in any case:
if __name__ == '__main__':
try:
## your code, typically one function call
except Exception:
import sys
print sys.exc_info()[0]
import traceback
print traceback.format_exc()
finally:
print "Press Enter to continue ..."
raw_input()
For Python3 you'll have to use input()
in place of raw_input()
, and of course adapt the print
statements.
if __name__ == '__main__':
try:
## your code, typically one function call
except BaseException:
import sys
print(sys.exc_info()[0])
import traceback
print(traceback.format_exc())
print("Press Enter to continue ...")
input()
To keep the window open in any case:
if __name__ == '__main__':
try:
## your code, typically one function call
except BaseException:
import sys
print(sys.exc_info()[0])
import traceback
print(traceback.format_exc())
finally:
print("Press Enter to continue ...")
input()
to Vilx-:
var table = row.parentNode;
while ( table && table.tagName != 'TABLE' )
table = table.parentNode;
and what if row.parentNode
is TBODY
?
You should check it out first, and after that
do while
by .tBodies
, probably
To elaborate on @Bakuriu's answer above, I've found that this enables me to catch a runtime warning in a similar fashion to how I would catch an error warning, printing out the warning nicely:
import warnings
with warnings.catch_warnings():
warnings.filterwarnings('error')
try:
answer = 1 / 0
except Warning as e:
print('error found:', e)
You will probably be able to play around with placing of the warnings.catch_warnings() placement depending on how big of an umbrella you want to cast with catching errors this way.
You can use implode to return your array with a string separator.
$withComma = implode(",", $array);
echo $withComma;
// Will display apple,banana,orange
UPDATED: assuming C# 6, the chances are that your case can be expressed as an exception filter. This is the ideal approach from a performance perspective assuming your requirement can be expressed in terms of it, e.g.:
try
{
}
catch ( Web2PDFException ex ) when ( ex.Code == 52 )
{
}
Assuming C# < 6, the most efficient is to catch a specific Exception
type and do handling based on that. Any catch-all handling can be done separately
try
{
}
catch ( Web2PDFException ex )
{
}
or
try
{
}
catch ( Web2PDFException ex )
{
}
catch ( Exception ex )
{
}
or (if you need to write a general handler - which is generally a bad idea, but if you're sure it's best for you, you're sure):
if( err is Web2PDFException)
{
}
or (in certain cases if you need to do some more complex type hierarchy stuff that cant be expressed with is
)
if( err.GetType().IsAssignableFrom(typeof(Web2PDFException)))
{
}
or switch to VB.NET or F# and use is
or Type.IsAssignableFrom
in Exception Filters
Try the following script:
#!/bin/bash
pgrep $1 2>&1 > /dev/null
if [ $? -eq 0 ]
then
{
echo " "$1" PROCESS RUNNING "
ps -ef | grep $1 | grep -v grep | awk '{print $2}'| xargs kill -9
}
else
{
echo " NO $1 PROCESS RUNNING"
};fi
DataFrame['Col_name'].replace("None", np.nan, inplace=True)
If you are using eclipse to start the server then check for the server location being used and the deployment path:
In my case changing this to Tomcat installation
instead of workspace metadata
worked for me.
With regular expressions
import re
s="""
qwertyuiop
asdfghjkl
zxcvbnm
token qwerty
asdfghjklñ
"""
>>> items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:
... print x
...
token qwerty
Assuming that you want to group the data before you generate the key with the sequence, it sounds like you want something like
INSERT INTO HISTORICAL_CAR_STATS (
HISTORICAL_CAR_STATS_ID,
YEAR,
MONTH,
MAKE,
MODEL,
REGION,
AVG_MSRP,
CNT)
SELECT MY_SEQ.nextval,
year,
month,
make,
model,
region,
avg_msrp,
cnt
FROM (SELECT '2010' year,
'12' month,
'ALL' make,
'ALL' model,
REGION,
sum(AVG_MSRP*COUNT)/sum(COUNT) avg_msrp,
sum(cnt) cnt
FROM HISTORICAL_CAR_STATS
WHERE YEAR = '2010'
AND MONTH = '12'
AND MAKE != 'ALL'
GROUP BY REGION)
I'm not able to comment divega's post, but among the different solutions presented here, divega's solution produces the best SQL. Both performance wise and length wise. I just checked with SQL Server Profiler and by looking at the execution plan (with "SET STATISTICS PROFILE ON").
You have root, but you still need to remount /system to be read/write
$ adb shell
$ su
$ mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
Go here for more information: Mount a filesystem read-write.
Import all Angular Material modules in Angular 9.
Create material.module.ts file in your_project/src/app/ directory and paste this code.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatRadioModule } from '@angular/material/radio';
import { MatSelectModule } from '@angular/material/select';
import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatMenuModule } from '@angular/material/menu';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatBadgeModule } from '@angular/material/badge';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatListModule } from '@angular/material/list';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatCardModule } from '@angular/material/card';
import { MatStepperModule } from '@angular/material/stepper';
import { MatTabsModule } from '@angular/material/tabs';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatChipsModule } from '@angular/material/chips';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatDialogModule } from '@angular/material/dialog';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
import { MatSortModule } from '@angular/material/sort';
import { MatPaginatorModule } from '@angular/material/paginator';
@NgModule( {
imports: [
CommonModule,
BrowserAnimationsModule,
MatCheckboxModule,
MatCheckboxModule,
MatButtonModule,
MatInputModule,
MatAutocompleteModule,
MatDatepickerModule,
MatFormFieldModule,
MatRadioModule,
MatSelectModule,
MatSliderModule,
MatSlideToggleModule,
MatMenuModule,
MatSidenavModule,
MatBadgeModule,
MatToolbarModule,
MatListModule,
MatGridListModule,
MatCardModule,
MatStepperModule,
MatTabsModule,
MatExpansionModule,
MatButtonToggleModule,
MatChipsModule,
MatIconModule,
MatProgressSpinnerModule,
MatProgressBarModule,
MatDialogModule,
MatTooltipModule,
MatSnackBarModule,
MatTableModule,
MatSortModule,
MatPaginatorModule
],
exports: [
MatButtonModule,
MatToolbarModule,
MatIconModule,
MatSidenavModule,
MatBadgeModule,
MatListModule,
MatGridListModule,
MatInputModule,
MatFormFieldModule,
MatSelectModule,
MatRadioModule,
MatDatepickerModule,
MatChipsModule,
MatTooltipModule,
MatTableModule,
MatPaginatorModule
],
providers: [
MatDatepickerModule,
]
} )
export class AngularMaterialModule { }
map
rockets and add 10 to its launches:
var rockets = [_x000D_
{ country:'Russia', launches:32 },_x000D_
{ country:'US', launches:23 },_x000D_
{ country:'China', launches:16 },_x000D_
{ country:'Europe(ESA)', launches:7 },_x000D_
{ country:'India', launches:4 },_x000D_
{ country:'Japan', launches:3 }_x000D_
];_x000D_
rockets.map((itm) => {_x000D_
itm.launches += 10_x000D_
return itm_x000D_
})_x000D_
console.log(rockets)
_x000D_
If you don't want to modify rockets
you can do:
var plusTen = []
rockets.forEach((itm) => {
plusTen.push({'country': itm.country, 'launches': itm.launches + 10})
})
it is because of using web address, You can not use http to write data. don't use : http:// or https:// in your location for upload files or save data or somting like that. instead of of using $_SERVER["HTTP_REFERER"] use $_SERVER["DOCUMENT_ROOT"]. for example :
wrong :
move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["HTTP_REFERER"].'/uploads/images/1.jpg')
correct:
move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["DOCUMENT_ROOT"].'/uploads/images/1.jpg')
<LinearLayout
android:id="@+id/LinearLayouts02"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="bottom|end">
<TextView
android:id="@+id/texts1"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="2"
android:text="@string/forgotpass"
android:padding="7dp"
android:gravity="bottom|center_horizontal"
android:paddingLeft="10dp"
android:layout_marginBottom="30dp"
android:bottomLeftRadius="10dp"
android:bottomRightRadius="50dp"
android:fontFamily="sans-serif-condensed"
android:textColor="@color/colorAccent"
android:textStyle="bold"
android:textSize="16sp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp"/>
</LinearLayout>
To declare a string literal as an output column, leave the Table
off and just use Test
. It doesn't need to be associated with a table among your joins, since it will be accessed only by its column alias. When using a metadata function like getColumnMeta()
, the table name will be an empty string because it isn't associated with a table.
SELECT
`field1`,
`field2`,
'Test' AS `field3`
FROM `Test`;
Note: I'm using single quotes above. MySQL is usually configured to honor double quotes for strings, but single quotes are more widely portable among RDBMS.
If you must have a table alias name with the literal value, you need to wrap it in a subquery with the same name as the table you want to use:
SELECT
field1,
field2,
field3
FROM
/* subquery wraps all fields to put the literal inside a table */
(SELECT field1, field2, 'Test' AS field3 FROM Test) AS Test
Now field3
will come in the output as Test.field3
.
Using inline styles:
<input type="text" style="text-align: right"/>
or, put it in a style sheet, like so:
<style>
.rightJustified {
text-align: right;
}
</style>
and reference the class:
<input type="text" class="rightJustified"/>
<div class="form-group">
<label for="file">Choose File</label><br /> <input type="file" id="file" (change)="uploadFiles($event.target.files)">
</div>
<button type="button" (click)="RequestUpload()">Ok</button>
public formData = new FormData();
ReqJson: any = {};
uploadFiles( file ) {
console.log( 'file', file )
for ( let i = 0; i < file.length; i++ ) {
this.formData.append( "file", file[i], file[i]['name'] );
}
}
RequestUpload() {
this.ReqJson["patientId"] = "12"
this.ReqJson["requesterName"] = "test1"
this.ReqJson["requestDate"] = "1/1/2019"
this.ReqJson["location"] = "INDIA"
this.formData.append( 'Info', JSON.stringify( this.ReqJson ) )
this.http.post( '/Request', this.formData )
.subscribe(( ) => {
});
}
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class Request {
private static String UPLOADED_FOLDER = "c://temp//";
@PostMapping("/Request")
@ResponseBody
public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("Info") String Info) {
System.out.println("Json is" + Info);
if (file.isEmpty()) {
return "No file attached";
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
return "Succuss";
}
}
We have to create a folder "temp" in C drive, then this code will print the Json in console and save the uploaded file in the created folder
Try using vbcrlf
for a newline
msgbox "This is how" & vbcrlf & "to get a new line"
You can also do like this,
<form method='POST'>
{{form1.as_p}}
<button type="submit" name="btnform1">Save Changes</button>
</form>
<form method='POST'>
{{form2.as_p}}
<button type="submit" name="btnform2">Save Changes</button>
</form>
CODE
if request.method=='POST' and 'btnform1' in request.POST:
do something...
if request.method=='POST' and 'btnform2' in request.POST:
do something...
In VS 2019, this works with ease:
[Route("api/[controller]/[action]")] //above the controller class
And in the code:
[HttpGet]
[ActionName("GetSample1")]
public Ilist<Sample1> GetSample1()
{
return getSample1();
}
[HttpGet]
[ActionName("GetSample2")]
public Ilist<Sample2> GetSample2()
{
return getSample2();
}
[HttpGet]
[ActionName("GetSample3")]
public Ilist<Sample3> GetSample3()
{
return getSample3();
}
[HttpGet]
[ActionName("GetSample4")]
public Ilist<Sample4> GetSample4()
{
return getSample4();
}
You can have multiple gets like above mentioned.
<?php
echo preg_replace( '#<li[^>]+>#', '<li class="col-sm-4">',
wp_nav_menu(
array(
'menu' => $nav_menu,
'container' => false,
'container_class' => false,
'menu_class' => false,
'items_wrap' => '%3$s',
'depth' => 1,
'echo' => false
)
)
);
?>
In my experience, don't use ffmpeg for splitting/join.
MP4Box, is faster and light than ffmpeg. Please tryit.
Eg if you want to split a 1400mb MP4 file into two parts a 700mb you can use the following cmdl:
MP4Box -splits 716800 input.mp4
eg for concatenating two files you can use:
MP4Box -cat file1.mp4 -cat file2.mp4 output.mp4
Or if you need split by time, use -splitx StartTime:EndTime
:
MP4Box -add input.mp4 -splitx 0:15 -new split.mp4
If your input rows are lists rather than dictionaries, then the following is a simple solution:
import pandas as pd
list_of_lists = []
list_of_lists.append([1,2,3])
list_of_lists.append([4,5,6])
pd.DataFrame(list_of_lists, columns=['A', 'B', 'C'])
# A B C
# 0 1 2 3
# 1 4 5 6
def flatten_it(d):
if isinstance(d, list) or isinstance(d, tuple):
return tuple([flatten_it(item) for item in d])
elif isinstance(d, dict):
return tuple([(flatten_it(k), flatten_it(v)) for k, v in sorted(d.items())])
else:
return d
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'b': 1}
print set(flatten_it(dict1)) - set(flatten_it(dict2)) # set([('b', 2), ('c', 3)])
# or
print set(flatten_it(dict2)) - set(flatten_it(dict1)) # set([('b', 1)])
Using the DISTINCT flag will remove duplicate rows.
SELECT DISTINCT
C.Content_ID,
C.Content_Title,
M.Media_Id
FROM tbl_Contents C
LEFT JOIN tbl_Media M ON M.Content_Id = C.Content_Id
ORDER BY C.Content_DatePublished ASC
From $http.get
docs, the second parameter is a configuration object:
get(url, [config]);
Shortcut method to perform
GET
request.
You may change your code to:
$http.get('accept.php', {
params: {
source: link,
category_id: category
}
});
Or:
$http({
url: 'accept.php',
method: 'GET',
params: {
source: link,
category_id: category
}
});
As a side note, since Angular 1.6: .success
should not be used anymore, use .then
instead:
$http.get('/url', config).then(successCallback, errorCallback);
The override
keyword serves two purposes:
To explain the latter:
class base
{
public:
virtual int foo(float x) = 0;
};
class derived: public base
{
public:
int foo(float x) override { ... } // OK
}
class derived2: public base
{
public:
int foo(int x) override { ... } // ERROR
};
In derived2
the compiler will issue an error for "changing the type". Without override
, at most the compiler would give a warning for "you are hiding virtual method by same name".
As previously mentioned - in case of a project, Makefile
or otherwise, this is a project configuration issue, where you'll likely need to specify other flags too.
But what about one-off programs, where you would normally just write g++ file.cpp && ./a.out
?
Well, I would much like to have some #pragma
to turn in on at source level, or maybe a default extension - say .cxx
or .C11
or whatever, trigger it by default. But as of today, there is no such feature.
But, as you probably are working in a manual environment (i.e. shell), you can just have an alias in you .bashrc
(or whatever):
alias g++11="g++ -std=c++0x"
or, for newer G++ (and when you want to feel "real C++11")
alias g++11="g++ -std=c++11"
You can even alias to g++
itself, if you hate C++03 that much ;)
I was interested in setting up graphics for Code Blocks when I ran into a this error: (took me 2 hrs to solve it)
I guess you need to have a bit of luck with this. In my case i just changed the order of contents in Settings menu->Compiler and Debugger->Global compiler settings->Linker settings->Other Linker Options: The working sequence is: -lmingw32 -lSDL -lSDLmain
I believe the following work in version 0.11 and above. To check the version:
$ ipython --version
It may be worth adding this information to your question.
Solution:
You need to find the file ipython_notebook_config.py
. Depending on your installation process this should be in somewhere like
.config/ipython/profile_default/ipython_notebook_config.py
where .config
is in your home directory.
Once you have located this file find the following lines
# Subset of matplotlib rcParams that should be different for the inline backend.
# c.InlineBackend.rc = {'font.size': 10, 'figure.figsize': (6.0, 4.0), 'figure.facecolor': 'white', 'savefig.dpi': 72, 'figure.subplot.bottom': 0.125, 'figure.edgecolor': 'white'}
Uncomment this line c.InlineBack...
and define your default figsize in the second dictionary entry.
Note that this could be done in a python script (and hence interactively in IPython) using
pylab.rcParams['figure.figsize'] = (10.0, 8.0)
Import gives you access to other modules in your program. You can't decide to import a text file. If you want to read from a file that's in the same directory, you can look at this. Here's another StackOverflow post about it.
Change the order you're including your scripts (jQuery first):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="./javascript.js"></script>
<script
src="http://maps.googleapis.com/maps/api/js?key=YOUR_APIKEY&sensor=false">
</script>
its simple let us assume you have made an state full class by extending Component which contains following
class DisableButton extends Components
{
constructor()
{
super();
// now set the initial state of button enable and disable to be false
this.state = {isEnable: false }
}
// this function checks the length and make button to be enable by updating the state
handleButtonEnable(event)
{
const value = this.target.value;
if(value.length > 0 )
{
// set the state of isEnable to be true to make the button to be enable
this.setState({isEnable : true})
}
}
// in render you having button and input
render()
{
return (
<div>
<input
placeholder={"ANY_PLACEHOLDER"}
onChange={this.handleChangePassword}
/>
<button
onClick ={this.someFunction}
disabled = {this.state.isEnable}
/>
<div/>
)
}
}
var dt = DateTime.Now;
var unixTime = ((DateTimeOffset)dt).ToUnixTimeSeconds();
// 1510396991
var dt = DateTimeOffset.FromUnixTimeSeconds(1510396991);
// [11.11.2017 10:43:11 +00:00]
Python 2.7 does not implement the int.to- very slow_bytes() method.
I tried 3 methods:
All these methods are very inefficient for two reasons:
SELECT CONVERT_TZ() will work for that.but its not working for me.
Why, what error do you get?
SELECT CONVERT_TZ(displaytime,'GMT','MET');
should work if your column type is timestamp, or date
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_convert-tz
Test how this works:
SELECT CONVERT_TZ(a_ad_display.displaytime,'+00:00','+04:00');
Check your timezone-table
SELECT * FROM mysql.time_zone;
SELECT * FROM mysql.time_zone_name;
http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html
If those tables are empty, you have not initialized your timezone tables. According to link above you can use mysql_tzinfo_to_sql
program to load the Time Zone Tables. Please try this
shell> mysql_tzinfo_to_sql /usr/share/zoneinfo
or if not working read more: http://dev.mysql.com/doc/refman/5.5/en/mysql-tzinfo-to-sql.html
Put the input name between single quotes so that the brackets []
are treated as a string
var multi_members="";
$("input[name='bayi[]']:checked:enabled").each(function() {
multi_members=$(this).val()+","+multi_members;
});
print(os.path.join(os.path.dirname(__file__)))
You can also use this way
have at look at the static methods DateTime.Parse()
and DateTime.TryParse()
. They will allow you to pass in your date string and a format string, and get a DateTime object in return.
byte[] data = dbEntity.getBlobData();
response.getOutputStream().write();
I think this is better since you already have an existing OutputStream in the response object. no need to create a new OutputStream.
It is possible to do everything you want. Aaron's answer was not quite complete.
His approach is correct, up to creating the temporary table in the inner query. Then, you need to insert the results into a table in the outer query.
The following code snippet grabs the first line of a file and inserts it into the table @Lines:
declare @fieldsep char(1) = ',';
declare @recordsep char(1) = char(10);
declare @Lines table (
line varchar(8000)
);
declare @sql varchar(8000) = '
create table #tmp (
line varchar(8000)
);
bulk insert #tmp
from '''+@filename+'''
with (FirstRow = 1, FieldTerminator = '''+@fieldsep+''', RowTerminator = '''+@recordsep+''');
select * from #tmp';
insert into @Lines
exec(@sql);
select * from @lines
please test this code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
div
{
display:none;
color:black
width:100px;
height:100px;
background:white;
animation:myfirst 9s;
-moz-animation:myfirst 9s; /* Firefox */
-webkit-animation:myfirst 5s; /* Safari and Chrome */
}
@keyframes myfirst
{
0% {background:blue;}
25% {background:yellow;}
50% {background:blue;}
100% {background:green;}
}
@-moz-keyframes myfirst /* Firefox */
{
0% {background:white;}
50% {background:blue;}
100% {background:green;}
}
@-webkit-keyframes myfirst /* Safari and Chrome */
{
0% {background:red;}
25% {background:yellow;}
50% {background:blue;}
100% {background:green;}
}
a:hover + div{
display:inline;
}
</style>
</head>
<body>
<a href="#">Hover over me!</a>
<div>the color is changing now</div>
<div></div>
</body>
</html>
function get_attribute(){ alert( $(this).attr("data-id") ); }
Read more at https://www.developerscripts.com/how-get-value-of-data-attribute-in-jquery
SELECT
CONNECTIONPROPERTY('net_transport') AS net_transport,
CONNECTIONPROPERTY('protocol_type') AS protocol_type,
CONNECTIONPROPERTY('auth_scheme') AS auth_scheme,
CONNECTIONPROPERTY('local_net_address') AS local_net_address,
CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port,
CONNECTIONPROPERTY('client_net_address') AS client_net_address
The code here Will give you the IP Address;
This will work for a remote client request to SQL 2008 and newer.
If you have Shared Memory connections allowed, then running above on the server itself will give you
<local machine>
' will be shown in 'client_net_address'.'client_net_address' is the address of the computer that the request originated from, whereas 'local_net_address' would be the SQL server (thus NULL over Shared Memory connections), and the address you would give to someone if they can't use the server's NetBios name or FQDN for some reason.
I advice strongly against using this answer. Enabling the shell out is a very bad idea on a production SQL Server.
css
div {
width: 100px;
height: 100px;
border-radius: 50%;
background: red;
}
html
<div></div>
Here is a O(n*n) approach that uses O(1) space.
void removeDuplicates(char* strIn)
{
int numDups = 0, prevIndex = 0;
if(NULL != strIn && *strIn != '\0')
{
int len = strlen(strIn);
for(int i = 0; i < len; i++)
{
bool foundDup = false;
for(int j = 0; j < i; j++)
{
if(strIn[j] == strIn[i])
{
foundDup = true;
numDups++;
break;
}
}
if(foundDup == false)
{
strIn[prevIndex] = strIn[i];
prevIndex++;
}
}
strIn[len-numDups] = '\0';
}
}
The hash/linq approaches above are what you would generally use in real life. However in interviews they usually want to put some constraints e.g. constant space which rules out hash or no internal api - which rules out using LINQ.
If you can install the latest Python (2.7.9 and up) Pip is now bundled with it.
See: https://docs.python.org/2.7//installing/index.html
If not :
Update (from the release notes):
Beginning with v1.5.1, pip does not require setuptools prior to running get-pip.py. Additionally, if setuptools (or distribute) is not already installed, get-pip.py will install setuptools for you.
I now run the regular:
curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | sudo python
Here are the official installation instructions: http://pip.readthedocs.org/en/latest/installing.html#install-pip
EDIT 25-Jul-2013:
Changed URL for setuptools install.
EDIT 10-Feb-2014:
Removed setuptools install (thanks @Ciantic)
EDIT 26-Jun-2014:
Updated URL again (thanks @LarsH)
EDIT 1-Mar-2015:
Pip is now bundled with Python
double a = 1.000001;
double b = 0.000001;
System.out.println( a.compareTo(b) );
Returns:
-1 : 'a' is numerically less than 'b'.
0 : 'a' is equal to 'b'.
1 : 'a' is greater than 'b'.
ULTIMATE SOLUTION Detecting if a radio button has been checked using onChang method JQUERY > 3.6
$('input[type=radio][name=YourRadioName]').change(()=>{
alert("Hello"); });
Getting the value of the clicked radio button
var radioval=$('input[type=radio][name=YourRadioName]:checked').val();
Just do;
System.IO.FileInfo fi = null;
try {
fi = new System.IO.FileInfo(fileName);
}
catch (ArgumentException) { }
catch (System.IO.PathTooLongException) { }
catch (NotSupportedException) { }
if (ReferenceEquals(fi, null)) {
// file name is not valid
} else {
// file name is valid... May check for existence by calling fi.Exists.
}
For creating a FileInfo
instance the file does not need to exist.
In your html you can pass in an array for the name i.e
<input type="text" name="address[]" />
This way php will receive an array of addresses.
You can use margin. See the example:
li{
margin: 10px 0;
}
this
refers to the current instance of the class (object) your equals-method belongs to. When you test this
against an object, the testing method (which is equals(Object obj)
in your case) will check wether or not the object is equal to the current instance (referred to as this
).
An example:
Object obj = this; this.equals(obj); //true Object obj = this; new Object().equals(obj); //false
For me, I define some properties:
disabledFirstOption = true;
get isIEOrEdge(): boolean {
return /msie\s|trident\/|edge\//i.test(window.navigator.userAgent)
}
Then in the constructor and ngOnInit
constructor() {
this.disabledFirstOption = false;
}
ngOnInit() {
setTimeout(() => {
this.disabledFirstOption = true;
});
}
And in the template I add this as the first option inside the select element
<option *ngIf="isIEOrEdge" [value]="undefined" [disabled]="disabledFirstOption" selected></option>
If you allow to select the first option you can just remove the usage of the property disabledFirstOption
Create as many comparators as necessary. After, call the method "thenComparing" for each order category. It's a way of doing by Streams. See:
//Sort by first and last name
System.out.println("\n2.Sort list of person objects by firstName then "
+ "by lastName then by age");
Comparator<Person> sortByFirstName
= (p, o) -> p.firstName.compareToIgnoreCase(o.firstName);
Comparator<Person> sortByLastName
= (p, o) -> p.lastName.compareToIgnoreCase(o.lastName);
Comparator<Person> sortByAge
= (p, o) -> Integer.compare(p.age,o.age);
//Sort by first Name then Sort by last name then sort by age
personList.stream().sorted(
sortByFirstName
.thenComparing(sortByLastName)
.thenComparing(sortByAge)
).forEach(person->
System.out.println(person));
Look: Sort user defined object on multiple fields – Comparator (lambda stream)
Dataframes have a sort_index
method which returns a copy by default. Pass inplace=True
to operate in place.
import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())
Gives me:
A
1 4
29 2
100 1
150 5
234 3
$msg="You Enter Wrong Username OR Password"; $responso=json_encode($msg);
echo "{\"status\" : \"400\", \"responce\" : \"603\", \"message\" : \"You Enter Wrong Username OR Password\", \"feed\":".str_replace("<p>","",$responso). "}";
If you are not sure if local db is installed, or not sure which database name you should use to connect to it - try running 'sqllocaldb info' command - it will show you existing localdb databases.
Now, as far as I know, local db should be installed together with Visual Studio 2015. But probably it is not required feature, and if something goes wrong or it cannot be installed for some reason - Visual Studio installation continues still (note that is just my guess). So to be on the safe side don't rely on it will always be installed together with VS.
Dockers use images which are build in layers. This adds a lot in terms of portability, sharing, versioning and other features. These images are very easy to port or transfer and since they are in layers, changes in subsequent versions are added in form of layers over previous layers. So, while porting many a times you don't need to port the base layers. Dockers have containers which run these images with execution environment contained, they add changes as new layers providing easy version control.
Apart from that Docker Hub is a good registry with thousands of public images, where you can find images which have OS and other softwares installed. So, you can get a pretty good head start for your application.
JVM : A specification which describes the the way/resources to run a java program. Actually executes the byte code and make java platform independent. In doing so, it is different for different platform. JVM for windows cannot work as JVM for UNIX.
JRE : Implementation of JVM. (JVM + run time libraries)
JDK : JRE + java compiler and other essential tools to build a java program from scratch
I don't understand why you're using FirstOrDefault(x=> x.ID == key)
when this could retrieve results much faster if you use Find(key)
. If you are querying with the Primary key of the table, the rule of thumb is to always use Find(key)
. FirstOrDefault
should be used for predicate stuff like (x=> x.Username == username)
etc.
this did not deserve a downvote as the heading of the question was not specific to linq on DB or Linq to List/IEnumerable etc.
String.contains(String)
or String.indexOf(String)
- suggested
"abc".contains("Z"); // false - correct
"zzzz".contains("Z"); // false - correct
"Z".contains("Z"); // true - correct
"and".contains(""); // true - correct
"and".contains(""); // false - correct
"and".indexOf(""); // 0 - correct
"and".indexOf(""); // -1 - correct
String.indexOf(int)
and carefully considered String.indexOf(char)
with char to int
widening
"and".indexOf("".charAt(0)); // 0 though incorrect usage has correct output due to portion of correct data
"and".indexOf("".charAt(0)); // 0 -- incorrect usage and ambiguous result
"and".indexOf("".codePointAt(0)); // -1 -- correct usage and correct output
char
or Character
considered as single character?No. In the context of unicode characters, char
or Character
can sometimes be part of a single character
and should not be treated as a complete single character
logically.
Any system supporting character encodings for Unicode characters should consider unicode's codepoint as single character.
So Java should do that very clear & loud rather than exposing too much of internal implementation details to users.
String
class is bad at abstraction (though it requires confusingly good amount of understanding of its encapsulations to understand the abstraction
and hence an anti-pattern
).
char
usage?char
can be only be mapped to a character in Basic Multilingual Plane.
Only codePoint - int
can cover the complete range of Unicode characters.
char
is internally treated as 16-bit
unsigned value and could not represent all the unicode characters using UTF-16 internal representation using only 2-bytes
. Sometimes, values in a 16-bit
range have to be combined with another 16-bit
value to correctly define character.
Without getting too verbose, the usage of indexOf
, charAt
, length
and such methods should be more explicit. Sincerely hoping Java will add new UnicodeString
and UnicodeCharacter
classes with clearly defined abstractions.
contains
and not indexOf(int)
char
in java.char
is not sufficientindexOf
takes in an int
, char
to int
conversion masks this from the user and user might do something like str.indexOf(someotherstr.charAt(0))
(unless the user is aware of the exact context)CharSequence
(aka String
) is better public static void main(String[] args) {
System.out.println("and".indexOf("".charAt(0))); // 0 though incorrect usage has correct output due to portion of correct data
System.out.println("and".indexOf("".charAt(0))); // 0 -- incorrect usage and ambiguous result
System.out.println("and".indexOf("".codePointAt(0))); // -1 -- correct usage and correct output
System.out.println("and".contains("")); // true - correct
System.out.println("and".contains("")); // false - correct
}