In MySQL, certain words like SELECT
, INSERT
, DELETE
etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.
As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):
Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.
...
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.
...
The identifier quote character is the backtick ("
`
"):
A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.
You have two options.
The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.
Doing this has a couple of advantages:
It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.
The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.
Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.
If renaming the table or column isn't possible, wrap the offending identifier in backticks (`
) as described in the earlier quote from 10.2 Schema Object Names.
An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):
mysql> CREATE TABLE interval (begin INT, end INT); ERROR 1064 (42000): You have an error in your SQL syntax. near 'interval (begin INT, end INT)'
mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)
Similarly, the query from the question can be fixed by wrapping the keyword key
in backticks, as shown below:
INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)"; ^ ^
The @ symbol allows you to use reserved word. For example:
int @class = 15;
The above works, when the below wouldn't:
int class = 15;
Oracle does use double-quotes, but you most likely need to place the object name in upper case, e.g. "TABLE". By default, if you create an object without double quotes, e.g.
CREATE TABLE table AS ...
Oracle would create the object as upper case. However, the referencing is not case sensitive unless you use double-quotes!
Java class final and method final -> sealed. Java member variable final -> readonly for runtime constant, const for compile time constant.
No equivalent for Local Variable final and method argument final
(rewritten 2015-07-28)
The default behavior of Eclipse when compiling code with errors in it, is to generate byte code throwing the exception you see, allowing the program to be run. This is possible as Eclipse uses its own built-in compiler, instead of javac
from the JDK which Apache Maven uses, and which fails the compilation completely for errors. If you use Eclipse on a Maven project which you are also working with using the command line mvn
command, this may happen.
The cure is to fix the errors and recompile, before running again.
The setting is marked with a red box in this screendump:
Based on the same idea as Super Type Tokens, you could create a typed id to use instead of a string:
public abstract class TypedID<T extends Animal> {
public final Type type;
public final String id;
protected TypedID(String id) {
this.id = id;
Type superclass = getClass().getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
}
}
But I think this may defeat the purpose, since you now need to create new id objects for each string and hold on to them (or reconstruct them with the correct type information).
Mouse jerry = new Mouse();
TypedID<Dog> spike = new TypedID<Dog>("spike") {};
TypedID<Duck> quacker = new TypedID<Duck>("quacker") {};
jerry.addFriend(spike, new Dog());
jerry.addFriend(quacker, new Duck());
But you can now use the class in the way you originally wanted, without the casts.
jerry.callFriend(spike).bark();
jerry.callFriend(quacker).quack();
This is just hiding the type parameter inside the id, although it does mean you can retrieve the type from the identifier later if you wish.
You'd need to implement the comparison and hashing methods of TypedID too if you want to be able to compare two identical instances of an id.
Validate with checkdate function:
$date = '2019-02-30';
$date_parts = explode( '-', $date );
if(checkdate( $date_parts[1], $date_parts[2], $date_parts[0] )){
//date is valid
}else{
//date is invalid
}
First, you need to convert your string to NSDate with its format. Then, you change the dateFormatter
to your simple format and convert it back to a String.
Swift 3
let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateObj = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: dateObj!))")
The printed result is: Dateobj: 10-22-2015
For a similar problem, (my problem was to show UTF-8 characters from MySQL on a command prompt),
I solved it like this:
I changed the font of command prompt to Lucida Console. (This step must be irrelevant for your situation. It has to do only with what you see on the screen and not with what is really the character).
I changed the codepage to Windows-1253. You do this on the command prompt by "chcp 1253". It worked for my case where I wanted to see UTF-8.
Int[] number ={1,2,3,4,5,6,7,8,9,10};
Int? Result = null;
foreach(Int i in number)
{
If(!Result.HasValue || i< Result)
{
Result =i;
}
}
Console.WriteLine(Result);
}
You don't need regular expressions. Python has a built-in string method that does what you need:
mystring.replace(" ", "_")
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
You can use this also
const { ObjectId } = require('mongodb');
const _id = ObjectId("4eb6e7e7e9b7f4194e000001");
it's simplest way to do it
I see timeouts used for this a lot, but in the context of an event, can't you look at coordinates, like this?:
function areXYInside(e){
var w=e.target.offsetWidth;
var h=e.target.offsetHeight;
var x=e.offsetX;
var y=e.offsetY;
return !(x<0 || x>=w || y<0 || y>=h);
}
Depending on context, you may need to make sure (this==e.target) before calling areXYInside(e).
fyi- I'm looking at using this approach inside a dragLeave handler, in order to confirm that the dragLeave event wasn't triggered by going into a child element. If you don't somehow check that you're still inside the parent element, you might mistakenly take action that's meant only for when you truly leave the parent.
EDIT: this is a nice idea, but does not work consistently enough. Perhaps with some small tweaks.
Also, note that you can add to a namespace. This is clearer with an example, what I mean is that you can have:
namespace MyNamespace
{
double square(double x) { return x * x; }
}
in a file square.h
, and
namespace MyNamespace
{
double cube(double x) { return x * x * x; }
}
in a file cube.h
. This defines a single namespace MyNamespace
(that is, you can define a single namespace across multiple files).
earl's answer gives you the solution, but I thought I'd add what the problem is that's causing your IllegalStateException
. You're calling group(1)
without having first called a matching operation (such as find()
). This isn't needed if you're just using $1
since the replaceAll()
is the matching operation.
Use Not IsNull(Fields!W_O_Count.Value)
While performance issues are valid the real reasons in practice that you should avoid storing images in a database are for database management reasons. Your database will grow very rapidly and databases cost much more than simple file storage. Database backups and restores are much more expensive and time-consuming than file backup restores. In a pinch, you can restore a smaller database much more quickly than one bloated with images. Compare 1 TB of file storage on Azure to a 1 TB database and you'll see the vast difference in cost.
There's a lot of talks going on regarding the simplicity of asmx web services over WCF. Let me clarify few points here.
Not to forget that I was one of those guys who liked asmx services more than WCF, but that time I was not well aware of WCF services and its capabilities. I was scared of the WCF configurations. But I dared and and tried writing few WCF services of my own, and when I learnt more of WCF, now I have no inhibitions about WCF and I recommend them to anyone & everyone. Happy coding!!!
Aside from the other answers...
I've found them helpful as a stepping-stone in refactoring god-classes. If a class has multiple responsibilities (especially if it's a very large code-file) then I find it beneficial to add 1x partial class per-responsibility as a first-pass for organizing and then refactoring the code.
This helps greatly because it can help with making the code much more readable without actually effecting the executing behavior. It also can help identify when a responsibility is easy to refactor out or is tightly tangled with other aspects.
However--to be clear--this is still bad code, at the end of development you still want one responsibility per-class (NOT per partial class). It's just a stepping-stone :)
package main
import (
"fmt"
)
func a() {
x := []int{}
x = append(x, 0)
x = append(x, 1) // commonTags := labelsToTags(app.Labels)
y := append(x, 2) // Tags: append(commonTags, labelsToTags(d.Labels)...)
z := append(x, 3) // Tags: append(commonTags, labelsToTags(d.Labels)...)
fmt.Println(y, z)
}
func b() {
x := []int{}
x = append(x, 0)
x = append(x, 1)
x = append(x, 2) // commonTags := labelsToTags(app.Labels)
y := append(x, 3) // Tags: append(commonTags, labelsToTags(d.Labels)...)
z := append(x, 4) // Tags: append(commonTags, labelsToTags(d.Labels)...)
fmt.Println(y, z)
}
func main() {
a()
b()
}
First guess could be
[0, 1, 2] [0, 1, 3]
[0, 1, 2, 3] [0, 1, 2, 4]
but in fact it results in
[0, 1, 2] [0, 1, 3]
[0, 1, 2, 4] [0, 1, 2, 4]
More details see https://allegro.tech/2017/07/golang-slices-gotcha.html
Spring annotations will work fine if you remove enctype="multipart/form-data"
.
@RequestParam(value="txtEmail", required=false)
You can even get the parameters from the request
object .
request.getParameter(paramName);
Use a form in case the number of attributes are large. It will be convenient. Tutorial to get you started.
Configure the Multi-part resolver if you want to receive enctype="multipart/form-data"
.
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="250000"/>
</bean>
Refer the Spring documentation.
The best way to use is white-space: nowrap;
This will align the text to one line.
Well, it's JavaScript, so what you have in 'value' is a Number, which can be an integer or a float. But there's not really a difference in JavaScript. From Learning JavaScript:
The Number Data Type
Number data types in JavaScript are floating-point numbers, but they may or may not have a fractional component. If they don’t have a decimal point or fractional component, they’re treated as integers—base-10 whole numbers in a range of –253 to 253.
Based on the example here: http://drupal.org/node/550488
The following will probably work in .htaccess
<IfModule mod_expires.c>
# Enable expirations.
ExpiresActive On
# Cache all files for 2 weeks after access (A).
ExpiresDefault A1209600
<FilesMatch (\.js|\.html)$>
ExpiresActive Off
</FilesMatch>
</IfModule>
make sure you have these permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Then make some activity and register a LocationListener
package com.example.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class LocationActivity extends SherlockFragmentActivity implements LocationListener {
private GoogleMap map;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); //You can also use LocationManager.GPS_PROVIDER and LocationManager.PASSIVE_PROVIDER
}
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
@Override
public void onProviderEnabled(String provider) { }
@Override
public void onProviderDisabled(String provider) { }
}
map.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
Open navigation.phtml
app/design/frontend/yourtheme/default/template/customer/account/navigation.phtml
replace
<?php $_links = $this->getLinks(); ?>
with unset link which you want to remove
<?php
$_count = count($_links);
unset($_links['account']); // Account Information
unset($_links['account_edit']); // Account Information
unset($_links['address_book']); // Address Book
unset($_links['orders']); // My Orders
unset($_links['billing_agreements']); // Billing Agreements
unset($_links['recurring_profiles']); // Recurring Profiles
unset($_links['reviews']); // My Product Reviews
unset($_links['wishlist']); // My Wishlist
unset($_links['OAuth Customer Tokens']); // My Applications
unset($_links['newsletter']); // Newsletter Subscriptions
unset($_links['downloadable_products']); // My Downloadable Products
unset($_links['tags']); // My Tags
unset($_links['invitations']); // My Invitations
unset($_links['enterprise_customerbalance']); // Store Credit
unset($_links['enterprise_reward']); // Reward Points
unset($_links['giftregistry']); // Gift Registry
unset($_links['enterprise_giftcardaccount']); // Gift Card Link
?>
At least in Android Studio 2.2.3 with default key mapping, to comment or uncomment a select text, same hotkeys are used as Toggle. Using the hotkeys changes the state from comment to uncomment, and next time Uncomment to comment on next and vice versa.
1. Comment / uncomment a block of code
Comment sample: /* --- Code block ---- */
Hotkey: Ctrl + Shift + "/"
Using the same key combinations again will "toggle" commenting or uncommenting the selection.
2. Comment / uncomment a line of code
Comment sample: // -- Code ---
Hotkey: Ctrl + "/"
Using the same key combinations again will "toggle" commenting or uncommenting the selection.
Note: Key mapping can be changed to different schemes like eclipse, visual studio... or to the custom hotkeys in File -> Settings -> Keymap
Using the title attribute:
<a href="#" title="Tooltip here">Link</a>
_x000D_
You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:
In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file"
field, ostensibly for backward compatibility reasons.
So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.
$.each(top_brands, function(index, el) {
for (var key in el) {
if (el.hasOwnProperty(key)) {
brand_options.append($("<option />").val(key).text(key+ " " + el[key]));
}
}
});
But if your data structure is var top_brands = {'Adidas': 100, 'Nike': 50};
, then thing will be much more simple.
for (var key in top_brands) {
if (top_brands.hasOwnProperty(key)) {
brand_options.append($("<option />").val(key).text(key+ " " + el[key]));
}
}
Or use the jquery each:
$.each(top_brands, function(key, value) {
brand_options.append($("<option />").val(key).text(key + " " + value));
});
You can put the graphic in a pseudo-element with its own dimensional context:
#graphic {
position: relative;
width: 200px;
height: 100px;
}
#graphic::before {
position: absolute;
content: '';
z-index: -1;
width: 200px;
height: 50px;
background-image: url(image.jpg);
}
#graphic {_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
position: relative;_x000D_
}_x000D_
#graphic::before {_x000D_
content: '';_x000D_
_x000D_
position: absolute;_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
z-index: -1;_x000D_
_x000D_
background-image: url(http://placehold.it/500x500/); /* Image is 500px by 500px, but only 200px by 50px is showing. */_x000D_
}
_x000D_
<div id="graphic">lorem ipsum</div>
_x000D_
Browser support is good, but if you need to support IE8, use a single colon :before
. IE has no support for either syntax in versions prior to that.
You may have a try for https://github.com/cls1991/pef. It will remove package with its all dependencies.
The easiest way to be sure that you have created the runnable JAR file correctly, with the appropriate manifest file, is to use Eclipse to build it for you. In your Eclipse project, you basically just select File/Export from the menu, and follow the prompts.
That way, you can be sure that your JAR file is correct and will know to look elsewhere if there is still an issue. The process is described in full in FAQ How do I create an executable JAR file for a stand-alone SWT program?.
lib
.lib\__init__.py
.In lib\BoxTime.py
, write a function foo()
like this:
def foo():
print "foo!"
In your client code in the directory above lib
, write:
from lib import BoxTime
BoxTime.foo()
Run your client code. You will get:
foo!
Much later -- in linux, it would look like this:
% cd ~/tmp
% mkdir lib
% touch lib/__init__.py
% cat > lib/BoxTime.py << EOF
heredoc> def foo():
heredoc> print "foo!"
heredoc> EOF
% tree lib
lib
+-- BoxTime.py
+-- __init__.py
0 directories, 2 files
% python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from lib import BoxTime
>>> BoxTime.foo()
foo!
I had the same problem. I think the best solution is to use log.exception, which will automatically print out stack trace and error message, such as:
try:
pass
log.info('Success')
except:
log.exception('Failed')
It is worth pointing out that if you use json_decode(file_get_contents("php://input"))
(as others have mentioned), this will fail if the string is not valid JSON.
This can be simply resolved by first checking if the JSON is valid. i.e.
function isValidJSON($str) {
json_decode($str);
return json_last_error() == JSON_ERROR_NONE;
}
$json_params = file_get_contents("php://input");
if (strlen($json_params) > 0 && isValidJSON($json_params))
$decoded_params = json_decode($json_params);
Edit: Note that removing strlen($json_params)
above may result in subtle errors, as json_last_error()
does not change when null
or a blank string is passed, as shown here:
http://ideone.com/va3u8U
Do like this
List<Object[]> list = HQL.list(); // get your lsit here but in Object array
your query is : "SELECT houses.id, addresses.country, addresses.region,..."
for(Object[] obj : list){
String houseId = String.valueOf(obj[0]); // houseId is at first place in your query
String country = String.valueof(obj[1]); // country is at second and so on....
.......
}
this way you can get the mixed objects with ease, but you should know in advance at which place what value you are getting or you can just check by printing the values to know. sorry for the bad english I hope this help
how about something like this ...
a.register:link{
color:#FFFFFF;
}
SQL Server allows the following (be careful to use single quotes instead of double)
UPDATE User
SET UserId = 12345
, Name = 'J Doe'
, Location = 'USA'
, Bio='my bio
spans
multiple
lines!'
WHERE UserId = 12345
I found this AddRow plugin quite useful for managing table rows. Though, Luke's solution would be the best fit if you just need to add a new row.
As an alternative to the other answers, you can try symbolic links.
Create the symbolic link first and install the application based on the link. (Depending on the case, this may be way easier to do, for instance when the application has n mentions of the target folder throughout its code)
A symbolic link will create something similar to a shortcut to a folder, but seen as an actual folder by other applications.
This is how you do it:
cmd
as administrator mklink /D "C:\LinkToProgramFiles" "C:\Program Files"
And then, you start using "C:\LinkToProgramFiles" in the applications that can't handle spaces. (This link can be seen in Windows Explorer as a folder with the symbol of a shortcut)
Be very careful not to create circular links if you start playing too much with this.
I was facing same issue not able to post form without ajax. but found solution , hope it can help and someones time.
<form name="paymentitrform" id="paymentitrform" class="payment"
method="post"
action="abc.php">
<input name="email" value="" placeholder="email" />
<input type="hidden" name="planamount" id="planamount" value="0">
<input type="submit" onclick="form_submit() " value="Continue Payment" class="action"
name="planform">
</form>
You can submit post form, from bootstrap modal using below javascript/jquery code : call the below function onclick of input submit button
function form_submit() {
document.getElementById("paymentitrform").submit();
}
& "C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe" C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode
or
[System.Diagnostics.Process]::Start("C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe", "C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode")
UPDATE: sorry I missed "(I invoked the command using the "&" operator)" sentence. I had this problem when I was evaluating the path dynamically. Try Invoke-Expression construction:
Invoke-Expression "& `"C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe`" C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode"
var txt = '{"cart":{"sType":1, "produto":[{"pType":1, "pName":"produto original", "valor": 10.00},{"pType":1, "pName":"produto selecionado", "valor": 11.00}]}}';
var obj = JSON.parse(txt);
obj.cart.produto[0]['pName']='nome alterado';
obj.cart.produto[obj.cart.produto.length]={"pType":9, "pName":"produto adicionado", "valor": 19.00};
console.log(obj);
console.log(JSON.stringify(obj));
// compondo objeto JSON
var txt = '{"cart":{"sType":1, "product":[{"pType":1, "pName":"product genuine1", "pValue": 10.00},{"pType":1, "pName":"product genuine2", "pValue": 11.00}]}}';
// criando o objeto
var obj = JSON.parse(txt);
console.log('//log do objeto original');
console.log(obj);
// alterando o valor de uma "key", no caso a pName do produto[0]
obj.cart.product[0]['pName']='nome alterado';
// adicionando uma nova array
obj.cart.product[obj.cart.product.length]={"pType":9, "pName":"produto adicionado", "pValue": 19.00};
console.log('//log do objeto alterado');
console.log(obj);
console.log('//log do objeto alterado em txt');
console.log(JSON.stringify(obj));
// no html
document.getElementById('print').innerText = JSON.stringify(obj);
_x000D_
<html>
<body>
<h2>Manipulando um objeto</h2>
<p id="print"></p>
</body>
</html>
_x000D_
@Rynant 's solution worked for me. I had a couple of additional requirements though:
Here's what I got working (finally):
[PS script code]
& runner.bat bat_to_run.bat logfile.txt
[runner.bat]
@echo OFF
REM This script can be executed from within a powershell script so that the bat file
REM passed as %1 will not cause execution to halt if PAUSE is encountered.
REM If {logfile} is included, bat file output will be appended to logfile.
REM
REM Usage:
REM runner.bat [path of bat script to execute] {logfile}
if not [%2] == [] GOTO APPEND_OUTPUT
@echo | call %1
GOTO EXIT
:APPEND_OUTPUT
@echo | call %1 1> %2 2>&1
:EXIT
I managed to construct a regex from all other answers.
(25[0-5]|2[0-4][0-9]|[1][0-9][0-9]|[1-9][0-9]|[0-9]?)(\.(25[0-5]|2[0-4][0-9]|[1][0-9][0-9]|[1-9][0-9]|[0-9]?)){3}
Use currentValue
instead, as the type of currentValue is EventTarget & HTMLInputElement
.
I've found version 0.7.1 Alpha of PuTTY Connection Manager to be the most stable (it was previously hidden on the forums). It's available from PuTTY Connection Manager – Website Down.
Add relative path option:
function getDirContents($dir, $relativePath = false)
{
$fileList = array();
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach ($iterator as $file) {
if ($file->isDir()) continue;
$path = $file->getPathname();
if ($relativePath) {
$path = str_replace($dir, '', $path);
$path = ltrim($path, '/\\');
}
$fileList[] = $path;
}
return $fileList;
}
print_r(getDirContents('/path/to/dir'));
print_r(getDirContents('/path/to/dir', true));
Output:
Array
(
[0] => /path/to/dir/test1.html
[1] => /path/to/dir/test.html
[2] => /path/to/dir/index.php
)
Array
(
[0] => test1.html
[1] => test.html
[2] => index.php
)
The config file is just an XML file, you can open it by:
private static XmlDocument loadConfigDocument()
{
XmlDocument doc = null;
try
{
doc = new XmlDocument();
doc.Load(getConfigFilePath());
return doc;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
catch (Exception ex)
{
return null;
}
}
and later retrieving values by:
// retrieve appSettings node
XmlNode node = doc.SelectSingleNode("//appSettings");
Change your method to look like this:
String curloc = current.toString();
String itemdesc = item.mDescription;
ArrayList<String> passing = new ArrayList<String>();
passing.add(itemdesc);
passing.add(curloc);
new calc_stanica().execute(passing); //no need to pass in result list
And change your async task implementation
public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(baraj_mapa.this);
dialog.setTitle("Calculating...");
dialog.setMessage("Please wait...");
dialog.setIndeterminate(true);
dialog.show();
}
protected ArrayList<String> doInBackground(ArrayList<String>... passing) {
ArrayList<String> result = new ArrayList<String>();
ArrayList<String> passed = passing[0]; //get passed arraylist
//Some calculations...
return result; //return result
}
protected void onPostExecute(ArrayList<String> result) {
dialog.dismiss();
String minim = result.get(0);
int min = Integer.parseInt(minim);
String glons = result.get(1);
String glats = result.get(2);
double glon = Double.parseDouble(glons);
double glat = Double.parseDouble(glats);
GeoPoint g = new GeoPoint(glon, glat);
String korisni_linii = result.get(3);
}
UPD:
If you want to have access to the task starting context, the easiest way would be to override onPostExecute in place:
new calc_stanica() {
protected void onPostExecute(ArrayList<String> result) {
// here you have access to the context in which execute was called in first place.
// You'll have to mark all the local variables final though..
}
}.execute(passing);
nib is fine. If in doubt, refer to the Python style guide.
From PEP 8:
Package and Module Names Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.
Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module names be chosen to be fairly short -- this won't be a problem on Unix, but it may be a problem when the code is transported to older Mac or Windows versions, or DOS.
When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. _socket).
If the language you use accepts {}
, you can use [0-9]{4,6}
.
If not, you'll have to use [0-9][0-9][0-9][0-9][0-9]?[0-9]?
.
/Using the Internal Regex used in creating the "new EmailAddressAttribute();" component in .Net4.5 >>> using System.ComponentModel.DataAnnotations; //To Validate an Email Address......Tested and Working.
public bool IsEmail(string email)
{
if (String.IsNullOrEmpty(email))
{ return false; }
try
{
Regex _regex = new Regex("^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])" +
"+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)" +
"((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|" +
"[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\u" +
"FDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|" +
"(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|" +
"[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900" +
"-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFF" +
"EF])))\\.?$", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled);
return _regex.IsMatch(email);
}
catch (RegexMatchTimeoutException)
{
return false;
}
}
Also, You can use this:
http://msdn.microsoft.com/en-us/library/01escwtf(v=vs.110).aspx
And make sure your route in the list of routes:
./manage.py show_urls | grep path_or_name
What is stateless??
Once the request is made and the response is rendered back to the client the connection will be dropped or terminated. The server will forget all about the requester.
Why stateless??
The web chooses to go for the stateless protocol. It was a genius choice because the original goal of the web was to allow documents(web pages) to be served to extremely large no. of people using very basic hardware for the server.
Maintaining a long-running connection would have been extremely resource-intensive.
If the web were chosen the stateful protocol then the load on the server would have been increased to maintain the visitor's connection.
For business/Gsuite apps or whatever they call them, you can specify the domain (had problem with 500 errors with the original answer when logged into multiple Google accounts).
<iframe
src="https://drive.google.com/a/YOUR_COMPANY_DOMAIN/embeddedfolderview?id=FOLDER-ID"
style="width:100%; height:600px; border:0;"
>
</iframe>
CSS
solution works without a glitch!
https://www.w3schools.com/code/tryit.asp?filename=GJ4PCJMVQ4LN https://www.w3schools.com/code/tryit.asp?filename=GJ4PPLCCEBRG
.col-info:hover>.popoverIcon {
visibility: visible;
}
}
.popoverIcon {
visibility: hidden;
}
_x000D_
<div *ngFor="let i of [1,2,3,4]">
<div class="col-info">
<span class=" popoverIcon ">Show {{i}}</span>
</div>
</div>
_x000D_
I got this error when using Visual Studio 2013
with Microsoft SQL Server Management Studio 2016
trying to update database with Entity Framework migrations
The fix was to install Microsoft SQL Server Management Studio 2012 SP1
as Visual Studio 2013 was missing the necessary libraries to connect to the SQL Server database.
I put together this detailed page with all the steps I took.
In angular only one page is requested from server, that is index.html. And index.html and assets folder are on same directory. while putting image in any component give src value like assets\image.png
. This will work fine because browser will make request to server for that image and webpack will be able serve that image.
There is the Windows API Code Pack. It's got a lot of shell related stuff, including the CommonOpenFileDialog
class (in the Microsoft.WindowsAPICodePack.Dialogs
namespace). This is the perfect solution - the usual open dialog with only folders displayed.
Here is an example of how to use it:
CommonOpenFileDialog cofd = new CommonOpenFileDialog();
cofd.IsFolderPicker = true;
cofd.ShowDialog();
Unfortunately Microsoft no longer ships this package, but several people have unofficially uploaded binaries to NuGet. One example can be found here. This package is just the shell-specific stuff. Should you need it, the same user has several other packages which offer more functionality present in the original package.
Please, try to find something like:
./website/config/app.php and set 'debug' => env('APP_DEBUG', false) as 'true' 'debug' => env('APP_DEBUG', true)
Most languages have path parsing functions that will give you this already. If you have the ability, I'd recommend using what comes to you for free out-of-the-box.
Assuming / is the path delimiter...
^(.*/)([^/]*)$
The first group will be whatever the directory/path info is, the second will be the filename. For example:
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
i made a little change to this code to save entry of a radio button but unable to save the text which appears in text box after selecting the radio button.
the code is below:-
<!DOCTYPE html>
<html>
<head>
<style>
form * {
display: block;
margin: 10px;
}
</style>
<script language="Javascript" >
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' +
encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
</script>
</head>
<body>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="name" value="test.txt">
<textarea rows=3 cols=50 name="text">PLEASE WRITE ANSWER HERE. </textarea>
<input type="radio" name="radio" value="Option 1" onclick="getElementById('problem').value=this.value;"> Option 1<br>
<input type="radio" name="radio" value="Option 2" onclick="getElementById('problem').value=this.value;"> Option 2<br>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="problem" id="problem">
<input type="submit" value="SAVE">
</form>
</body>
</html>
Using 'minifyEnabled'
instead of 'runProguard'
works properly.
Previous code:
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
Current code:
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
Hope this helps.
You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:
https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899
In this example, question 1, "Name", has an ID of 726721210
, while question 2, "Birthday" is 787184751
. Questions 3 and 4 are blank.
You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:
function buildUrls() {
var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1"); // Email, Name, Birthday
var data = ss.getDataRange().getValues();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
var url = template.replace('##Name##',escape(data[i][1]))
.replace('##Birthday##',data[i][2].yyyymmdd()); // see yyyymmdd below
Logger.log(url); // You could do something more useful here.
}
};
This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.
Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.
Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0]
is "Name", [1]
is "Birthday", and so on.
We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.
(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)
/**
* Use Form API to generate pre-filled form URLs
*/
function betterBuildUrls() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Sheet1");
var data = ss.getDataRange().getValues(); // Data for pre-fill
var formUrl = ss.getFormUrl(); // Use form attached to sheet
var form = FormApp.openByUrl(formUrl);
var items = form.getItems();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
// Create a form response object, and prefill it
var formResponse = form.createResponse();
// Prefill Name
var formItem = items[0].asTextItem();
var response = formItem.createResponse(data[i][1]);
formResponse.withItemResponse(response);
// Prefill Birthday
formItem = items[1].asDateItem();
response = formItem.createResponse(data[i][2]);
formResponse.withItemResponse(response);
// Get prefilled form URL
var url = formResponse.toPrefilledUrl();
Logger.log(url); // You could do something more useful here.
}
};
Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd
. This helper function extends the Date object with a new method to handle the conversion.
When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975
you could use 5/9/1975
.)
// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
For those who like it short, here's an other one using Array.reduce
which will not cause stack overflow:
var base64 = btoa(
new Uint8Array(arrayBuffer)
.reduce((data, byte) => data + String.fromCharCode(byte), '')
);
you could change the innerHtml on an element
function produceMessage(){
var msg= 'Hello<br />';
document.getElementById('someElement').innerHTML = msg;
}
The problem with camel case is that there are often different interpretations of words - for example, checkinService vs checkInService. Going along with Aaron's answer, it is difficult with auto-completion if you have many similarly named repos to have to constantly check if the person who created the repo you care about used a certain breakdown of the upper and lower cases. avoid upper case.
His point about dashes is also well-advised.
A third option, for a pipelined one-liner is to nest the -replaces:
PS> ("ABC" -replace "B","C") -replace "C","D"
ADD
And:
PS> ("ABC" -replace "C","D") -replace "B","C"
ACD
This preserves execution order, is easy to read, and fits neatly into a pipeline. I prefer to use parentheses for explicit control, self-documentation, etc. It works without them, but how far do you trust that?
-Replace is a Comparison Operator, which accepts an object and returns a presumably modified object. This is why you can stack or nest them as shown above.
Please see:
help about_operators
For MAC os user:
I have faced this issue many times. The key here is to set these environment variables before installing mysqlclient by pip command. For my case, they are like below:
export LDFLAGS="-L/usr/local/opt/[email protected]/lib"
export CPPFLAGS="-I/usr/local/opt/[email protected]/include"
Try below code
public enum SalaryHeadMasterEnum {
BASIC_PAY("basic pay"),
MEDICAL_ALLOWANCE("Medical Allowance");
private String name;
private SalaryHeadMasterEnum(String stringVal) {
name=stringVal;
}
public String toString(){
return name;
}
public static String getEnumByString(String code){
for(SalaryHeadMasterEnum e : SalaryHeadMasterEnum.values()){
if(e.name.equals(code)) return e.name();
}
return null;
}
}
Now you can use below code to retrieve the Enum by Value
SalaryHeadMasterEnum.getEnumByString("Basic Pay")
Use Below code to get ENUM as String
SalaryHeadMasterEnum.BASIC_PAY.name()
Use below code to get string Value for enum
SalaryHeadMasterEnum.BASIC_PAY.toString()
Just pass parameter
like
body - The content(query) from the customer
subject - subject that defined in mail subject
username - nothing name anything
mail - mail (required)
public static bool SendMail(String body, String subject, string username, String mail)
{
bool isSendSuccess = false;
try
{
var fromEmailAddress = ConfigurationManager.AppSettings["FromEmailAddress"].ToString();
var fromEmailDisplayName = ConfigurationManager.AppSettings["FromEmailDisplayName"].ToString();
var fromEmailPassword = ConfigurationManager.AppSettings["FromEmailPassword"].ToString();
var smtpHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
var smtpPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();
MailMessage message = new MailMessage(new MailAddress(fromEmailAddress, fromEmailDisplayName),
new MailAddress(mail, username));
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = body;
var client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(fromEmailAddress, fromEmailPassword);
client.Host = smtpHost;
client.EnableSsl = false;
client.Port = !string.IsNullOrEmpty(smtpPort) ? Convert.ToInt32(smtpPort) : 0;
client.Send(message);
isSendSuccess = true;
}
catch (Exception ex)
{
throw (new Exception("Mail send failed to loginId " + mail + ", though registration done."+ex.ToString()+"\n"+ex.StackTrace));
}
return isSendSuccess;
}
if your using go daddy server this work . add this in web.config
<appSettings>
---other ---setting
<add key="FromEmailAddress" value="[email protected]" />
<add key="FromEmailDisplayName" value="anyname" />
<add key="FromEmailPassword" value="mypassword@" />
<add key="SMTPHost" value="relay-hosting.secureserver.net" />
<add key="SMTPPort" value="25" />
</appSettings>
if you are using localhost or vps server change this configuration to this
<appSettings>
---other ---setting
<add key="FromEmailAddress" value="[email protected]" />
<add key="FromEmailDisplayName" value="anyname" />
<add key="FromEmailPassword" value="mypassword@" />
<add key="SMTPHost" value="smtp.gmail.com" />
<add key="SMTPPort" value="587" />
</appSettings>
change the code
client.EnableSsl = true;
if your are using gmail please enable secure app. using this link https://myaccount.google.com/lesssecureapps?pli=1&rapt=AEjHL4Pd6h3XxE663Flvd-FfeRXxW_eNrIsGTBlZklgkAHZEeuHvheCQuZ1-djB9uIWaB-2EV7hyLCU0dWKA7D0JzYKe4ZRkuA
For Android Studio:
If you haven't built the APK at least once, you might not find the /Outputs/APK folder. Go to Build in Android Studio and one of the last three options is Build APK, select that. It will then create that folder and you will find your APK file there.
As of January 31, 2013 Github markdown supports relative links to files.
[a relative link](markdown_file.md)
However, there are a few deficiencies that have been discussed in this comment thread.
As an alternative, you can use Gitdown to construct full URLs to the repository and even make them branch aware, e.g.
{"gitdown": "gitinfo", "name": "url"} // https://github.com/gajus/gitdown
{"gitdown": "gitinfo", "name": "branch"} // master
Gitdown is a GitHub markdown preprocessor. It streamlines common tasks associated with maintaining a documentation page for a GitHub repository, e.g. generating table of contents, including variables, generating URLs and getting information about the repository itself at the time of processing the input. Gitdown seamlessly integrates with your building scripts.
I am the author of the Gitdown library.
Create-react-app Version 2+ answer
For recent (> v2) versions of create-react-app (and possible older as well), add the following line to your package.json, then rebuild.
"homepage": "./"
You should now see the build/index.html will have relative links ./static/...
instead of links to the server root: /static/...
.
Short answers:
Q1: Yes.
Q2: Doesn't matter which you use.
Long answer:
A select ... for update
will (as it implies) select certain rows but also lock them as if they have already been updated by the current transaction (or as if the identity update had been performed). This allows you to update them again in the current transaction and then commit, without another transaction being able to modify these rows in any way.
Another way of looking at it, it is as if the following two statements are executed atomically:
select * from my_table where my_condition;
update my_table set my_column = my_column where my_condition;
Since the rows affected by my_condition
are locked, no other transaction can modify them in any way, and hence, transaction isolation level makes no difference here.
Note also that transaction isolation level is independent of locking: setting a different isolation level doesn't allow you to get around locking and update rows in a different transaction that are locked by your transaction.
What transaction isolation levels do guarantee (at different levels) is the consistency of data while transactions are in progress.
The exit()
function is a type of function with a return type without an argument. It's defined by the stdlib header file.
You need to use ( exit(0) or exit(EXIT_SUCCESS))
or (exit(non-zero)
or exit(EXIT_FAILURE) )
.
In html5 you can do using the full expression:
<select required="required">
I don't know why the short expression doesn't work, but try this one. It will solve.
Since you are using .Result
or .Wait
or await
this will end up causing a deadlock in your code.
you can use ConfigureAwait(false)
in async
methods for preventing deadlock
like this:
var result = await httpClient.GetAsync("http://stackoverflow.com", HttpCompletionOption.ResponseHeadersRead)
.ConfigureAwait(false);
you can use
ConfigureAwait(false)
wherever possible for Don't Block Async Code .
Yes, sure!
There...
$bin = decbin(ord($char));
... and back again.
$char = chr(bindec($bin));
I agree with @maverik above, I prefer not to hide the details with a typedef. Especially when you are trying to understand what is going on. I also prefer to see everything instead of a partial code snippet. With that said, here is a malloc and free of a complex structure.
The code uses the ms visual studio leak detector so you can experiment with the potential leaks.
#include "stdafx.h"
#include <string.h>
#include "msc-lzw.h"
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
// 32-bit version
int hash_fun(unsigned int key, int try_num, int max) {
return (key + try_num) % max; // the hash fun returns a number bounded by the number of slots.
}
// this hash table has
// key is int
// value is char buffer
struct key_value_pair {
int key; // use this field as the key
char *pValue; // use this field to store a variable length string
};
struct hash_table {
int max;
int number_of_elements;
struct key_value_pair **elements; // This is an array of pointers to mystruct objects
};
int hash_insert(struct key_value_pair *data, struct hash_table *hash_table) {
int try_num, hash;
int max_number_of_retries = hash_table->max;
if (hash_table->number_of_elements >= hash_table->max) {
return 0; // FULL
}
for (try_num = 0; try_num < max_number_of_retries; try_num++) {
hash = hash_fun(data->key, try_num, hash_table->max);
if (NULL == hash_table->elements[hash]) { // an unallocated slot
hash_table->elements[hash] = data;
hash_table->number_of_elements++;
return RC_OK;
}
}
return RC_ERROR;
}
// returns the corresponding key value pair struct
// If a value is not found, it returns null
//
// 32-bit version
struct key_value_pair *hash_retrieve(unsigned int key, struct hash_table *hash_table) {
unsigned int try_num, hash;
unsigned int max_number_of_retries = hash_table->max;
for (try_num = 0; try_num < max_number_of_retries; try_num++) {
hash = hash_fun(key, try_num, hash_table->max);
if (hash_table->elements[hash] == 0) {
return NULL; // Nothing found
}
if (hash_table->elements[hash]->key == key) {
return hash_table->elements[hash];
}
}
return NULL;
}
// Returns the number of keys in the dictionary
// The list of keys in the dictionary is returned as a parameter. It will need to be freed afterwards
int keys(struct hash_table *pHashTable, int **ppKeys) {
int num_keys = 0;
*ppKeys = (int *) malloc( pHashTable->number_of_elements * sizeof(int) );
for (int i = 0; i < pHashTable->max; i++) {
if (NULL != pHashTable->elements[i]) {
(*ppKeys)[num_keys] = pHashTable->elements[i]->key;
num_keys++;
}
}
return num_keys;
}
// The dictionary will need to be freed afterwards
int allocate_the_dictionary(struct hash_table *pHashTable) {
// Allocate the hash table slots
pHashTable->elements = (struct key_value_pair **) malloc(pHashTable->max * sizeof(struct key_value_pair)); // allocate max number of key_value_pair entries
for (int i = 0; i < pHashTable->max; i++) {
pHashTable->elements[i] = NULL;
}
// alloc all the slots
//struct key_value_pair *pa_slot;
//for (int i = 0; i < pHashTable->max; i++) {
// // all that he could see was babylon
// pa_slot = (struct key_value_pair *) malloc(sizeof(struct key_value_pair));
// if (NULL == pa_slot) {
// printf("alloc of slot failed\n");
// while (1);
// }
// pHashTable->elements[i] = pa_slot;
// pHashTable->elements[i]->key = 0;
//}
return RC_OK;
}
// This will make a dictionary entry where
// o key is an int
// o value is a character buffer
//
// The buffer in the key_value_pair will need to be freed afterwards
int make_dict_entry(int a_key, char * buffer, struct key_value_pair *pMyStruct) {
// determine the len of the buffer assuming it is a string
int len = strlen(buffer);
// alloc the buffer to hold the string
pMyStruct->pValue = (char *) malloc(len + 1); // add one for the null terminator byte
if (NULL == pMyStruct->pValue) {
printf("Failed to allocate the buffer for the dictionary string value.");
return RC_ERROR;
}
strcpy(pMyStruct->pValue, buffer);
pMyStruct->key = a_key;
return RC_OK;
}
// Assumes the hash table has already been allocated.
int add_key_val_pair_to_dict(struct hash_table *pHashTable, int key, char *pBuff) {
int rc;
struct key_value_pair *pKeyValuePair;
if (NULL == pHashTable) {
printf("Hash table is null.\n");
return RC_ERROR;
}
// Allocate the dictionary key value pair struct
pKeyValuePair = (struct key_value_pair *) malloc(sizeof(struct key_value_pair));
if (NULL == pKeyValuePair) {
printf("Failed to allocate key value pair struct.\n");
return RC_ERROR;
}
rc = make_dict_entry(key, pBuff, pKeyValuePair); // a_hash_table[1221] = "abba"
if (RC_ERROR == rc) {
printf("Failed to add buff to key value pair struct.\n");
return RC_ERROR;
}
rc = hash_insert(pKeyValuePair, pHashTable);
if (RC_ERROR == rc) {
printf("insert has failed!\n");
return RC_ERROR;
}
return RC_OK;
}
void dump_hash_table(struct hash_table *pHashTable) {
// Iterate the dictionary by keys
char * pValue;
struct key_value_pair *pMyStruct;
int *pKeyList;
int num_keys;
printf("i\tKey\tValue\n");
printf("-----------------------------\n");
num_keys = keys(pHashTable, &pKeyList);
for (int i = 0; i < num_keys; i++) {
pMyStruct = hash_retrieve(pKeyList[i], pHashTable);
pValue = pMyStruct->pValue;
printf("%d\t%d\t%s\n", i, pKeyList[i], pValue);
}
// Free the key list
free(pKeyList);
}
int main(int argc, char *argv[]) {
int rc;
int i;
struct hash_table a_hash_table;
a_hash_table.max = 20; // The dictionary can hold at most 20 entries.
a_hash_table.number_of_elements = 0; // The intial dictionary has 0 entries.
allocate_the_dictionary(&a_hash_table);
rc = add_key_val_pair_to_dict(&a_hash_table, 1221, "abba");
if (RC_ERROR == rc) {
printf("insert has failed!\n");
return RC_ERROR;
}
rc = add_key_val_pair_to_dict(&a_hash_table, 2211, "bbaa");
if (RC_ERROR == rc) {
printf("insert has failed!\n");
return RC_ERROR;
}
rc = add_key_val_pair_to_dict(&a_hash_table, 1122, "aabb");
if (RC_ERROR == rc) {
printf("insert has failed!\n");
return RC_ERROR;
}
rc = add_key_val_pair_to_dict(&a_hash_table, 2112, "baab");
if (RC_ERROR == rc) {
printf("insert has failed!\n");
return RC_ERROR;
}
rc = add_key_val_pair_to_dict(&a_hash_table, 1212, "abab");
if (RC_ERROR == rc) {
printf("insert has failed!\n");
return RC_ERROR;
}
rc = add_key_val_pair_to_dict(&a_hash_table, 2121, "baba");
if (RC_ERROR == rc) {
printf("insert has failed!\n");
return RC_ERROR;
}
// Iterate the dictionary by keys
dump_hash_table(&a_hash_table);
// Free the individual slots
for (i = 0; i < a_hash_table.max; i++) {
// all that he could see was babylon
if (NULL != a_hash_table.elements[i]) {
free(a_hash_table.elements[i]->pValue); // free the buffer in the struct
free(a_hash_table.elements[i]); // free the key_value_pair entry
a_hash_table.elements[i] = NULL;
}
}
// Free the overall dictionary
free(a_hash_table.elements);
_CrtDumpMemoryLeaks();
return 0;
}
It was giving 415 Http response Code as error,
So I added
httppost.addHeader("Content-Type", "text/xml; charset=utf-8");
Everything alright now, Http: 200
If i understood correctly the easiest way is to use regular expression as it provides you lots of flexibility but the other simple method is to use for loop following is the code with example I also counted the occurrence of word and stored in dictionary..
s = """An... essay is, generally, a piece of writing that gives the author's own
argument — but the definition is vague,
overlapping with those of a paper, an article, a pamphlet, and a short story. Essays
have traditionally been
sub-classified as formal and informal. Formal essays are characterized by "serious
purpose, dignity, logical
organization, length," whereas the informal essay is characterized by "the personal
element (self-revelation,
individual tastes and experiences, confidential manner), humor, graceful style,
rambling structure, unconventionality
or novelty of theme," etc.[1]"""
d = {} # creating empty dic
words = s.split() # spliting string and stroing in list
for word in words:
new_word = ''
for c in word:
if c.isalnum(): # checking if indiviual chr is alphanumeric or not
new_word = new_word + c
print(new_word, end=' ')
# if new_word not in d:
# d[new_word] = 1
# else:
# d[new_word] = d[new_word] +1
print(d)
please rate this if this answer is useful!
Prior to running python, type cd
in the commmand line, and it will tell you the directory you are currently in. When python runs, it can only access files in this directory. hello.py
needs to be in this directory, so you can move hello.py
from its existing location to this folder as you would move any other file in Windows or you can change directories and run python in the directory hello.py
is.
Edit: Python cannot access the files in the subdirectory unless a path to it provided. You can access files in any directory by providing the path. python C:\Python27\Projects\hello.p
go to configuration Manager under properties for your solution. Then make sure all projects and getting built, and this won't be a problem.
Might not be exactly what the OP was looking for, but this page is where I found myself after looking for the problem, so sharing this for everyone with similar issue :)
Stack's fit
property did the trick for my needs. Otherwise Image inside (OctoImageIn my case) was padded and providing other Image.fit
values did not give any effect.
Stack(
fit: StackFit.expand,
children: [
Image(
image: provider,
fit: BoxFit.cover,
),
// other irrelevent children here
]
);
Do you want to print the entire list or you want to iterate through each element of the list? Either way to print anything meaningful your Dog
class need to override the toString()
method (as mentioned in other answers) from the Object
class to return a valid result.
public class Print {
public static void main(final String[] args) {
List<Dog> list = new ArrayList<Dog>();
Dog e = new Dog("Tommy");
list.add(e);
list.add(new Dog("tiger"));
System.out.println(list);
for(Dog d:list) {
System.out.println(d);
// prints [Tommy, tiger]
}
}
private static class Dog {
private final String name;
public Dog(final String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
}
The output of this code is:
[Tommy, tiger]
Tommy
tiger
Just in case someone gets here with the same issue I had, which is not specifically addressed in previous comments.
I had margin: auto
on the inner element which caused it to stick to the bottom of it's parent (or the outer element).
What fixed it for me was changing the margin to margin: 0 auto;
.
If you have access to your apache install and trust third-party code, you can use the apache upload progress module (if you use apache; there's also a nginx upload progress module).
Otherwise, you'd have to write a script that you can hit out of band to request the status of the file (checking the filesize of the tmp file for instance).
There's some work going on in firefox 3 I believe to add upload progress support to the browser, but that's not going to get into all the browsers and be widely adopted for a while (more's the pity).
The push
command has a -n
/--dry-run
option which will compute what needs to be pushed but not actually do it. Does that work for you?
For converting date to string check this thread
Convert java.util.Date to String
And for converting string to date try this,
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class StringToDate
{
public static void main(String[] args) throws ParseException
{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
String strDate = "14/03/2003 08:05:10";
System.out.println("Date - " + sdf.parse(strDate));
}
}
^[+]?([0-9]{1,2})*[.,]([0-9]{1,1})?$
This will match:
You could use IsEmpty()
function like this:
...
Set rRng = Sheet1.Range("A10")
If IsEmpty(rRng.Value) Then ...
you could also use following:
If ActiveCell.Value = vbNullString Then ...
The opposite is using :not
e.g.
selection:not(:hover) { rules }
You can use the following regex globally:
\[(.*?)\]
Explanation:
\[
: [
is a meta char and needs to be escaped if you want to match it literally.(.*?)
: match everything in a non-greedy way and capture it.\]
: ]
is a meta char and needs to be escaped if you want to match it literally.Edit: seems I was wrong in assuming you could not get the element. As others have posted here, you can get it with:
$('#element').get(0);
I have verified this actually returns the DOM element that was matched.
Assuming that you have JAXB installed Go to the following directory C:\Program Files\jaxb\bin open command window here
> xjc -wsdl http://localhost/mywsdl/MyDWsdl.wsdl C:\Users\myname\Desktop
C:\Users\myname\Desktop is the ouput folder you can change that to your preference
http://localhost/mywsdl/MyDWsdl.wsdl is the link to the WSDL
You need ReDim
:
m = 5
n = 8
Dim my_array()
ReDim my_array(1 To m, 1 To n)
For i = 1 To m
For j = 1 To n
my_array(i, j) = i * j
Next
Next
For i = 1 To m
For j = 1 To n
Cells(i, j) = my_array(i, j)
Next
Next
As others have pointed out, your actual problem would be better solved with ranges. You could try something like this:
Dim r1 As Range
Dim r2 As Range
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
totalRow = ws1.Range("A1").End(xlDown).Row
totalCol = ws1.Range("A1").End(xlToRight).Column
Set r1 = ws1.Range(ws1.Cells(1, 1), ws1.Cells(totalRow, totalCol))
Set r2 = ws2.Range(ws2.Cells(1, 1), ws2.Cells(totalRow, totalCol))
r2.Value = r1.Value
There is a better algorithm, which needs at most 6 iterations to converge to maximum precision for double numbers:
#include <math.h>
double sqrt(double x) {
if (x <= 0)
return 0; // if negative number throw an exception?
int exp = 0;
x = frexp(x, &exp); // extract binary exponent from x
if (exp & 1) { // we want exponent to be even
exp--;
x *= 2;
}
double y = (1+x)/2; // first approximation
double z = 0;
while (y != z) { // yes, we CAN compare doubles here!
z = y;
y = (y + x/y) / 2;
}
return ldexp(y, exp/2); // multiply answer by 2^(exp/2)
}
Algorithm starts with 1 as first approximation for square root value.
Then, on each step, it improves next approximation by taking average between current value y
and x/y
. If y
= sqrt(x)
, it will be the same. If y
> sqrt(x)
, then x/y
< sqrt(x)
by about the same amount. In other words, it will converge very fast.
UPDATE: To speed up convergence on very large or very small numbers, changed sqrt()
function to extract binary exponent and compute square root from number in [1, 4)
range. It now needs frexp()
from <math.h>
to get binary exponent, but it is possible to get this exponent by extracting bits from IEEE-754 number format without using frexp()
.
The modulo operator %
in C and C++ is defined for two integers, however, there is an fmod()
function available for usage with doubles.
For utl_file.open(location,filename,mode) , we need to give directory name for location but not path. For Example:DATA_FILE_DIR , this is the directory name and check out the directory path for that particular directory name.
Python 2 didn't have closures - it had workarounds that resembled closures.
There are plenty of examples in answers already given - copying in variables to the inner function, modifying an object on the inner function, etc.
In Python 3, support is more explicit - and succinct:
def closure():
count = 0
def inner():
nonlocal count
count += 1
print(count)
return inner
Usage:
start = closure()
start() # prints 1
start() # prints 2
start() # prints 3
The nonlocal
keyword binds the inner function to the outer variable explicitly mentioned, in effect enclosing it. Hence more explicitly a 'closure'.
You can now simply do Instant.parse("2015-04-28T14:23:38.521Z")
and get the correct thing now, especially since you should be using Instant
instead of the broken java.util.Date
with the most recent versions of Java.
You should be using DateTimeFormatter
instead of SimpleDateFormatter
as well.
The explanation below is still valid as as what the format represents. But it was written before Java 8 was ubiquitous so it uses the old classes that you should not be using if you are using Java 8 or higher.
Z
as demonstrated:In the pattern the
T
is escaped with'
on either side.The pattern for the
Z
at the end is actuallyXXX
as documented in the JavaDoc forSimpleDateFormat
, it is just not very clear on actually how to use it sinceZ
is the marker for the oldTimeZone
information as well.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class Q2597083
{
/**
* All Dates are normalized to UTC, it is up the client code to convert to the appropriate TimeZone.
*/
public static final TimeZone UTC;
/**
* @see <a href="http://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations">Combined Date and Time Representations</a>
*/
public static final String ISO_8601_24H_FULL_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
/**
* 0001-01-01T00:00:00.000Z
*/
public static final Date BEGINNING_OF_TIME;
/**
* 292278994-08-17T07:12:55.807Z
*/
public static final Date END_OF_TIME;
static
{
UTC = TimeZone.getTimeZone("UTC");
TimeZone.setDefault(UTC);
final Calendar c = new GregorianCalendar(UTC);
c.set(1, 0, 1, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
BEGINNING_OF_TIME = c.getTime();
c.setTime(new Date(Long.MAX_VALUE));
END_OF_TIME = c.getTime();
}
public static void main(String[] args) throws Exception
{
final SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
sdf.setTimeZone(UTC);
System.out.println("sdf.format(BEGINNING_OF_TIME) = " + sdf.format(BEGINNING_OF_TIME));
System.out.println("sdf.format(END_OF_TIME) = " + sdf.format(END_OF_TIME));
System.out.println("sdf.format(new Date()) = " + sdf.format(new Date()));
System.out.println("sdf.parse(\"2015-04-28T14:23:38.521Z\") = " + sdf.parse("2015-04-28T14:23:38.521Z"));
System.out.println("sdf.parse(\"0001-01-01T00:00:00.000Z\") = " + sdf.parse("0001-01-01T00:00:00.000Z"));
System.out.println("sdf.parse(\"292278994-08-17T07:12:55.807Z\") = " + sdf.parse("292278994-08-17T07:12:55.807Z"));
}
}
sdf.format(BEGINNING_OF_TIME) = 0001-01-01T00:00:00.000Z
sdf.format(END_OF_TIME) = 292278994-08-17T07:12:55.807Z
sdf.format(new Date()) = 2015-04-28T14:38:25.956Z
sdf.parse("2015-04-28T14:23:38.521Z") = Tue Apr 28 14:23:38 UTC 2015
sdf.parse("0001-01-01T00:00:00.000Z") = Sat Jan 01 00:00:00 UTC 1
sdf.parse("292278994-08-17T07:12:55.807Z") = Sun Aug 17 07:12:55 UTC 292278994
See mozilla.org's write-up on how CORS works.
You'll need your server to send back the proper response headers, something like:
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, PUT, GET, OPTIONS
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization
Bear in mind you can use "*"
for Access-Control-Allow-Origin
that will only work if you're trying to pass Authentication data. In that case, you need to explicitly list the origin domains you want to allow. To allow multiple domains, see this post
Opacity gives you translucency or transparency. See an example Fiddle here.
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; /* IE 8 */
filter: alpha(opacity=50); /* IE 5-7 */
-moz-opacity: 0.5; /* Netscape */
-khtml-opacity: 0.5; /* Safari 1.x */
opacity: 0.5; /* Good browsers */
Note: these are NOT CSS3 properties
See http://css-tricks.com/snippets/css/cross-browser-opacity/
<uses-sdk tools:node="replace" />
No longer works.
change uses-sdk
to
<uses-sdk tools:overrideLibrary="com.packagename.of.libary.with.conflict" />
and add
xmlns:tools="http://schemas.android.com/tools"
in the AndroidManifest.xml file
To add margins directly to items (some items allow direct editing of margins), you can do:
LayoutParams lp = ((ViewGroup) something).getLayoutParams();
if( lp instanceof MarginLayoutParams )
{
((MarginLayoutParams) lp).topMargin = ...;
((MarginLayoutParams) lp).leftMargin = ...;
//... etc
}
else
Log.e("MyApp", "Attempted to set the margins on a class that doesn't support margins: "+something.getClass().getName() );
...this works without needing to know about / edit the surrounding layout. Note the "instanceof" check in case you try and run this against something that doesn't support margins.
The Request.Form.Keys collection will be empty if none of your html inputs have NAMEs. It's easy to forget to put them there after you've been doing .NET for a while. Just name them and you'll be good to go.
I encountered this issue, and I found that when there huge amount of data getting exchanged between a service and an application,(This involves transferring lots of thumbnails). Actually data size was around 500kb, and the IPC transaction buffer size is set to 1024KB. I am not sure why it exceeded the transaction buffer.
This also can occur, when you pass lot of data through intent extras
When you get this exception in your application, please analyze your code.
How to handle when you get this exception
If possible, split the big operation in to small chunks, for example, instead of calling applyBatch() with 1000 operations, call it with 100 each.
Do not exchange huge data (>1MB) between services and application
I dont know how to do this, but, Do not query android, which can return huge data :-)
From the documentation for strtotime()
:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
In your date string, you have 12-16-2013
. 16
isn't a valid month, and hence strtotime()
returns false
.
Since you can't use DateTime class, you could manually replace the -
with /
using str_replace()
to convert the date string into a format that strtotime()
understands:
$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16
The assert() function can diagnose program bugs. In C, it is defined in <assert.h>
, and in C++ it is defined in <cassert>
. Its prototype is
void assert(int expression);
The argument expression can be anything you want to test--a variable or any C expression. If expression evaluates to TRUE, assert() does nothing. If expression evaluates to FALSE, assert() displays an error message on stderr and aborts program execution.
How do you use assert()? It is most frequently used to track down program bugs (which are distinct from compilation errors). A bug doesn't prevent a program from compiling, but it causes it to give incorrect results or to run improperly (locking up, for example). For instance, a financial-analysis program you're writing might occasionally give incorrect answers. You suspect that the problem is caused by the variable interest_rate taking on a negative value, which should never happen. To check this, place the statement
assert(interest_rate >= 0); at locations in the program where interest_rate is used. If the variable ever does become negative, the assert() macro alerts you. You can then examine the relevant code to locate the cause of the problem.
To see how assert() works, run the sample program below. If you enter a nonzero value, the program displays the value and terminates normally. If you enter zero, the assert() macro forces abnormal program termination. The exact error message you see will depend on your compiler, but here's a typical example:
Assertion failed: x, file list19_3.c, line 13 Note that, in order for assert() to work, your program must be compiled in debug mode. Refer to your compiler documentation for information on enabling debug mode (as explained in a moment). When you later compile the final version in release mode, the assert() macros are disabled.
int x;
printf("\nEnter an integer value: ");
scanf("%d", &x);
assert(x >= 0);
printf("You entered %d.\n", x);
return(0);
Enter an integer value: 10
You entered 10.
Enter an integer value: -1
Error Message: Abnormal program termination
Your error message might differ, depending on your system and compiler, but the general idea is the same.
I use this function to calculate cpu usage. Hope it can help you.
private float readUsage() {
try {
RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
String load = reader.readLine();
String[] toks = load.split(" +"); // Split on one or more spaces
long idle1 = Long.parseLong(toks[4]);
long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
+ Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
try {
Thread.sleep(360);
} catch (Exception e) {}
reader.seek(0);
load = reader.readLine();
reader.close();
toks = load.split(" +");
long idle2 = Long.parseLong(toks[4]);
long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
+ Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
return (float)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));
} catch (IOException ex) {
ex.printStackTrace();
}
return 0;
}
If you just want to rearrange dates from oldest to newest in r etc. you can always do:
dataframe <- dataframe[nrow(dataframe):1,]
It's saved me exporting in and out from excel just for sort on Yahoo Finance data.
//Swift 4.0 Remove spaces and new lines
extension String {
func trim() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
if you want to beautify the appearance of your pagination, I use the class from bootstrap to make it more simple and easy
@if ($students->lastPage() > 1)
<ul class="pagination ml-auto">
<li class="{{ ($students->currentPage() == 1) ? ' disabled' : '' }} page-item">
<a class=" page-link " href="{{ $students->url(1) }}" aria-label="Previous">
<span aria-hidden="true">«</span>
<span class="sr-only">Previous</span>
</a>
</li>
@for ($i = 1; $i <= $students->lastPage(); $i++)
<li class="{{ ($students->currentPage() == $i) ? ' active' : '' }} page-item">
<a class=" page-link " href="{{ $students->url($i) }}">{{ $i }}</a>
</li>
@endfor
<li class="{{ ($students->currentPage() == $students->lastPage()) ? ' disabled' : '' }} page-item">
<a href="{{ $students->url($students->currentPage()+1) }}" class="page-link" aria-label="Next">
<span aria-hidden="true">»</span>
<span class="sr-only">Next</span>
</a>
</li>
</ul>
@endif
Usually I handle my operations within a transaction. As I've experienced, it is not enough to set the context command timeout, but the transaction needs a constructor with a timeout parameter. I had to set both time out values for it to work properly.
int? prevto = uow.Context.Database.CommandTimeout;
uow.Context.Database.CommandTimeout = 900;
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromSeconds(900))) {
...
}
At the end of the function I set back the command timeout to the previous value in prevto.
Using EF6
The solution is
@RequestMapping(value = "processing", method = RequestMethod.GET)
public @ResponseBody ProcessResponse processData(@RequestParam("workflow") final String workflow,
@RequestParam("conf") final String value, @RequestParam("dc") final String dc, HttpServletRequest request) {
System.out.println(workflow);
System.out.println(value);
System.out.println(dc);
System.out.println(request.getRemoteAddr());
// some other code
}
Add HttpServletRequest request
to your method definition and then use the Servlet API
Spring Documentation here said in
15.3.2.3 Supported handler method arguments and return types
Handler methods that are annotated with @RequestMapping can have very flexible signatures.
Most of them can be used in arbitrary order (see below for more details).
Request or response objects (Servlet API). Choose any specific request or response type,
for example ServletRequest or HttpServletRequest
Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.
As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:
var clone = _.clone(data, true);
data[1].values.d = 'x';
_.isEqual(data, clone) === false
_.isEqual(data, clone) === true
I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.
Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).
If you are using your EditText in Dialog or creating dynamically and You can't set it from xml then this example will help you in setting that type of key board while you are using dynamic Edit Text etc
myEditTxt.setInputType(InputType.TYPE_CLASS_NUMBER);
where myEditTxt is the dynamic EDIT TEXT object(name)
No, there isn't.
Only if you need to support ancient versions of Internet Explorer.
The modern approach is to do margin: 0 auto
in your CSS.
Example here: http://jsfiddle.net/bKRMY/
HTML:
<p>Hello the following image is centered</p>
<p class="pic"><img src="https://twimg0-a.akamaihd.net/profile_images/440228301/StackoverflowLogo_reasonably_small.png"/></p>
<p>Did it work?</p>
CSS:
p.pic {
width: 48px;
margin: 0 auto;
}
The only issue here is that the width of the paragraph must be the same as the width of the image. If you don't put a width on the paragraph, it will not work, because it will assume 100% and your image will be aligned left, unless of course you use text-align:center
.
Try out the fiddle and experiment with it if you like.
This is too late but posting my experience for people looking at it later:-
In MS VS 2010 I had the same issue. It got resolved by putting quotes to post build copy command args which contained spaces!
In Project Properties --> Configuration Properties --> Build Events --> Post-Build Event --> Command Line
change:
copy $(ProjectDir)a\b\c $(OutputPath)
to
copy "$(ProjectDir)a\b\c" "$(OutputPath)"
Here is another method using .loc
to replace inf with nan on a Series:
s.loc[(~np.isfinite(s)) & s.notnull()] = np.nan
So, in response to the original question:
df = pd.DataFrame(np.ones((3, 3)), columns=list('ABC'))
for i in range(3):
df.iat[i, i] = np.inf
df
A B C
0 inf 1.000000 1.000000
1 1.000000 inf 1.000000
2 1.000000 1.000000 inf
df.sum()
A inf
B inf
C inf
dtype: float64
df.apply(lambda s: s[np.isfinite(s)].dropna()).sum()
A 2
B 2
C 2
dtype: float64
There is a lot of confusion about Repositories and Projects. In the past both terms were used pretty much interchangeably by the users and the GitHub's very own documentation. This is reflected by some of the answers and comments here that explain the subtle differences between those terms and when the one was preferred over the other. The difference were always subtle, e.g. like the issue tracker being part of the project but not part of the repository which might be thought of as a strictly git thing etc.
Currently repos and projects refer to a different kinds of entities that have separate APIs:
Since then it is no longer correct to call the repo a project or vice versa. Note that it is often confused in the official documentation and it is unfortunate that a term that was already widely used has been chosen as the name of the new entity but this is the case and we have to live with that.
The consequence is that repos and projects are usually confused and every time you read about GitHub projects you have to wonder if it's really about the projects or about repos. Had they chosen some other name or an abbreviation like "proj" then we could know that what is discussed is the new type of entity, a precise object with concrete properties, or a general speaking repo-like projectish kind of thingy.
The term that is usually unambiguous is "project board".
The first endpoint in the documentation of the Projects API:
is described as: List repository projects. It means that a repository can have many projects. So those two cannot mean the same thing. It includes Response if projects are disabled:
{
"message": "Projects are disabled for this repo",
"documentation_url": "https://developer.github.com/v3"
}
which means that some repos can have projects disabled. Again, those cannot be the same thing when a repo can have projects disabled.
There are some other interesting endpoints:
POST /repos/:owner/:repo/projects
POST /orgs/:org/projects
but there is no:
POST /users/:user/projects
Which leads us to another difference:
1. Repositories can belong to users or organizations
2. Projects can belong to repositories or organizations
or, more importantly:
1. Projects can belong to repositories but not the other way around
2. Projects can belong to organizations but not to users
3. Repositories can belong to organizations and to users
See also:
I know it's confusing. I tried to explain it as precisely as I could.
Just use
WHERE RAND() < 0.1
to get 10% of the records or
WHERE RAND() < 0.01
to get 1% of the records, etc.
I think the problem is you have to use the ! to unbundle identifier
I have
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
if segue!.identifier == "Details" {
let viewController:ViewController = segue!.destinationViewController as ViewController
let indexPath = self.tableView.indexPathForSelectedRow()
viewController.pinCode = self.exams[indexPath.row]
}
}
My understanding is that without the ! you just get a true or false value
I faced a similar issue. Try to follow the below steps: Manually delete the .m2 folder. Refer to the settings.xml file and check if the repository details are proper, like id and url tags. Also make sure you are connected to same network and check if the URL is accessible from browser. And lastly keep maven projects in /home/User/.
Parameters passed to the C program executable is nothing but an array of string(or character pointer),so memory would have been already allocated for these input parameter before your program access these parameters,so no need to allocate buffer,and that way you can avoid error handling code in your program as well(Reduce chances of segfault :)).
Popen.communicate
will set the returncode
attribute when it's done(*). Here's the relevant documentation section:
Popen.returncode
The child return code, set by poll() and wait() (and indirectly by communicate()).
A None value indicates that the process hasn’t terminated yet.
A negative value -N indicates that the child was terminated by signal N (Unix only).
So you can just do (I didn't test it but it should work):
import subprocess as sp
child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)
streamdata = child.communicate()[0]
rc = child.returncode
(*) This happens because of the way it's implemented: after setting up threads to read the child's streams, it just calls wait
.
Example:
['Thanks You',
'Its fine no problem',
'Are you sure']
code block:
import pandas as pd
df = pd.DataFrame(lst)
Output:
0
0 Thanks You
1 Its fine no problem
2 Are you sure
It is not recommended to remove the column names of the panda dataframe. but if you still want your data frame without header(as per the format you posted in the question) you can do this:
df = pd.DataFrame(lst)
df.columns = ['']
Output will be like this:
0 Thanks You
1 Its fine no problem
2 Are you sure
or
df = pd.DataFrame(lst).to_string(header=False)
But the output will be a list instead of a dataframe:
0 Thanks You
1 Its fine no problem
2 Are you sure
Hope this helps!!
Although it is a late answer, I would say this will help you...
$query = $this->db
->select('user_id, count(user_id) AS num_of_time')
->group_by('user_id')
->order_by('num_of_time', 'desc')
->get('tablename', 10);
print_r($query->result());
"Requery" is indeed what you what you want to run, but you could do that in Form A's "On Got Focus" event. If you have code in your Form_Load, perhaps you can move it to Form_Got_Focus.
You can create constants in many different ways:
const myString = "hello"
const pi = 3.14 // untyped constant
const life int = 42 // typed constant (can use only with ints)
You can also create a enum constant:
const (
First = 1
Second = 2
Third = 4
)
You can not create constants of maps, arrays and it is written in effective go:
Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans. Because of the compile-time restriction, the expressions that define them must be constant expressions, evaluatable by the compiler. For instance, 1<<3 is a constant expression, while math.Sin(math.Pi/4) is not because the function call to math.Sin needs to happen at run time.
No use script tag only.
Solution with |
:
script
| if (10 == 10) {
| alert("working")
| }
Or with a .
:
script.
if (10 == 10) {
alert("working")
}
I managed to make it work with alpha28 like this:
import {Component, View} from 'angular2/angular2';
@Component({
selector: 'circle',
properties: ['color: color'],
})
@View({
template: `<style>
.circle{
width:50px;
height: 50px;
border-radius: 25px;
}
</style>
<div class="circle" [style.background-color]="changeBackground()">
<content></content>
</div>
`
})
export class Circle {
color;
constructor(){
}
changeBackground(): string {
return this.color;
}
}
and called it like this <circle color='yellow'></circle>
also check this out, for example we wanna count t
echo "test" | awk -v RS='t' 'END{print NR-1}'
or in python
python -c 'print "this is for test".count("t")'
or even better, we can make our script dynamic with awk
echo 'test' | awk '{for (i=1 ; i<=NF ; i++) array[$i]++ } END{ for (char in array) print char,array[char]}' FS=""
in this case output is like this :
e 1
s 1
t 2
C++ provides a good mechanism to manage the life time of an object though class/struct constructs. This is one of the best features of C++ over other languages.
When you have member variables exposed through ref or pointer it violates the encapsulation in principle. This idiom enables the consumer of the class to change the state of an object of A without it(A) having any knowledge or control of it. It also enables the consumer to hold on to a ref/pointer to A's internal state, beyond the life time of the object of A. This is bad design. Instead the class could be refactored to hold a ref/pointer to the shared object (not own it) and these could be set using the constructor (Mandate the life time rules). The shared object's class may be designed to support multithreading/concurrency as the case may apply.
It's an unportable way to remove all data from the input buffer till the next newline. I've seen it used in cases like that:
char c;
char s[32];
puts("Type a char");
c=getchar();
fflush(stdin);
puts("Type a string");
fgets(s,32,stdin);
Without the fflush()
, if you type a character, say "a", and the hit enter, the input buffer contains "a\n", the getchar()
peeks the "a", but the "\n" remains in the buffer, so the next fgets()
will find it and return an empty string without even waiting for user input.
However, note that this use of fflush()
is unportable. I've tested right now on a Linux machine, and it does not work, for example.
Just as a heads up to those still searching for this.
ConstraintLayout 1.0.1 and lower have been deprecated by maven.
For a list of available constraint layouts that can be downloaded, see below:
https://maven.google.com/web/index.html?q=Constrain#com.android.support.constraint:constraint-layout
The easiest solution at the moment, is to change
implementation 'com.android.support.constraint:constraint-layout:1.0.0-beta1'
to
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
docker inspect -f '{{ json .Mounts }}' containerid | jq '.[]'
Create controller go to cmd and the type php artisan make:controller auth\LoginController
'speed up thread
dim lpThreadId as long
dim test as long
dim ptrt as long
'initparams
ptrt=varptr(lpThreadId)
Add = CODEPTR(thread)
'opensocket(191.9.202.255) change depending on configuration
numSock = Sock.Connect("191.9.202.255", 1958)
'port recieving
numSock1=sock.open(5963)
'create thread
hThread= CreateThread (byval 0&,byval 16384, Add , byval 0&, ByVal 1958, ptrt )
edit3.text=str$(hThread)
' use
Declare Function CreateThread Lib "kernel32" Alias "CreateThread" (lpThreadAttributes As long, ByVal dwStackSize As Long, lpStartAddress As Long, lpParameter As long, ByVal dwCreationFlags As Long, lpThreadId As Long) As Long
Here :)
function isSet(iVal){
return (iVal!=="" && iVal!=null && iVal!==undefined && typeof(iVal) != "undefined") ? 1 : 0;
} // Returns 1 if set, 0 false
So generally this has been solved, but you might get this error message because the date you use is not in the correct format.
I know this is an old post, but whenever I run this I get NA all the way down my date column. My dates are in this format 20150521 – NealC Jun 5 '15 at 16:06
If you have dates of this format just check the format of your dates with:
str(sides$date)
If the format is not a character, then convert it:
as.character(sides$date)
For as.Date, you won't need an origin any longer, because this is supplied for numeric values only. Thus you can use (assuming you have the format of NealC):
as.Date(as.character(sides$date),format="%Y%m%d")
I hope this might help some of you.
List<String> mockedList = mock(List.class);
List<String> l = new ArrayList();
l.add("someElement");
mockedList.addAll(l);
ArgumentCaptor<List> argumentCaptor = ArgumentCaptor.forClass(List.class);
verify(mockedList).addAll(argumentCaptor.capture());
List<String> capturedArgument = argumentCaptor.<List<String>>getValue();
assertThat(capturedArgument, hasItem("someElement"));
There you go , i hope this helps
here is the CSS also
#video_box{
float:left;
}
#video_overlays {
position:absolute;
float:left;
width:640px;
min-height:370px;
background-color:#000;
z-index:300000;
}
Your reference to "0x31 = 1" makes me think you're actually trying to convert ASCII values to strings - in which case you should be using something like Encoding.ASCII.GetString(Byte[])
Here's one example, given to me by @jleahy: Suppose you have a collection of tasks, executed asynchronously, and managed by an std::shared_ptr<Task>
. You may want to do something with those tasks periodically, so a timer event may traverse a std::vector<std::weak_ptr<Task>>
and give the tasks something to do. However, simultaneously a task may have concurrently decided that it is no longer needed and die. The timer can thus check whether the task is still alive by making a shared pointer from the weak pointer and using that shared pointer, provided it isn't null.
Some of my pet peeves with Maven:
The XML definition is super clumsy and verbose. Have they never heard of attributes?
In its default configuration, it always scours the 'net on every operation. Regardless of whether this is useful for anything, it looks extremely silly to need Internet access for "clean".
Again in the default, if I'm not careful to specify exact version numbers, it will pull the very latest updates off the 'net, regardless of whether these newest versions introduce dependency errors. In other words, you're placed at the mercy of other peoples' dependency management.
The solution to all this network access is to turn it off by adding the -o
option. But you have to remember to turn it off if you really want to do dependency updating!
Another solution is to install your own "source control" server for dependencies. Surprise: Most projects already have source control, only that works with no additional setup!
Maven builds are incredibly slow. Fiddling with network updates alleviates this, but Maven builds are still slow. And horribly verbose.
The Maven plugin (M2Eclipse) integrates most poorly with Eclipse. Eclipse integrates reasonably smoothly with version control software and with Ant. Maven integration is very clunky and ugly by comparison. Did I mention slow?
Maven continues to be buggy. Error messages are unhelpful. Too many developers are suffering from this.
If you don't have non-ASCII characters (codepoints 128 and above) in your file, UTF-8 without BOM is the same as ASCII, byte for byte - so Notepad++ will guess wrong.
What you need to do is to specify the character encoding when serving the AJAX response - e.g. with PHP, you'd do this:
header('Content-Type: application/json; charset=utf-8');
The important part is to specify the charset with every JS response - else IE will fall back to user's system default encoding, which is wrong most of the time.
Easiest solution is to add onWheel={ event => event.currentTarget.blur() }}
on input itself.
If you have the column it's very easy.
Using the designer, you could set the column as an identity (1,1): right click on the table ? design ? in part left (right click) ? properties ? in identity columns, select #column.
Properties:
Identity column:
Open up your git bash and type
echo $HOME
This shall be the same folder as you get when you open your command window (cmd) and type
echo %USERPROFILE%
And – of course – the .ssh
folder shall be present on THAT directory.
No, it's not possible, browsers have their own ways to implement tooltip. All you can do is to create some div that behaves like an HTML tooltip (mostly it's just 'show on hover') with Javascript, and then style it the way you want.
With this, you wouldn't have to worry about browser's zooming in or out, since the text inside the tooltip div is an actual HTML, it would scale accordingly.
See Jonathan's post for some good resource.
How about something as simple as:
function negative(number){
return number < 0;
}
The * 1
part is to convert strings to numbers.
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Selected)
{
foreach (DataGridViewCell cell in row.Cells)
{
int index = cell.ColumnIndex;
if (index == 0)
{
value = cell.Value.ToString();
//do what you want with the value
}
}
}
}
I had the very same problem recently with Android Studio 1.3. The only working solution was to remove the .gradle and .idea folders and re-import the project into Android Studio.
Another simple solution could be to use a structure or simple data class that contains the parameters as properties; that way you can have all the default values and behaviors set up ahead of time, passing the "parameter class" in as the single constructor parameter:
public class FooParams
{
public int Size...
protected myCustomStruct _ReasonForLife ...
}
public class Foo
{
private FooParams _myParams;
public Foo(FooParams myParams)
{
_myParams = myParams;
}
}
This avoids the mess of multiple constructors (sometimes) and gives strong typing, default values, and other benefits not provided by a parameter array. It also makes it easy to carry forward since anything that inherits from Foo can still get to, or even add to, FooParams as needed. You still need to copy the constructor, but you always (most of the time) only (as a general rule) ever (at least, for now) need one constructor.
public class Bar : Foo
{
public Bar(FooParams myParams) : base(myParams) {}
}
I really like the overloaded Initailize() and Class Factory Pattern approaches better, but sometimes you just need to have a smart constructor. Just a thought.
You need spaces:
if [ "$s1" == "$s2" ]
I had the same issue. My mistake was that I used @Service annotation on the Service Interface. The @Service annotation should be applied to the ServiceImpl class.
There's a bit of confusion in your question:
Date
datatype doesn't save the time zone component. This piece of information is truncated and lost forever when you insert a TIMESTAMP WITH TIME ZONE
into a Date
.TO_CHAR
function. In Oracle, a Date
has no format: it is a point in time.TO_TIMESTAMP_TZ
to convert a VARCHAR2
to a TIMESTAMP
, but this won't convert a Date
to a TIMESTAMP
.FROM_TZ
to add the time zone information to a TIMESTAMP
(or a Date
).CST
is a time zone but CDT
is not. CDT
is a daylight saving information.CST/CDT
(-05:00
) and CST/CST
(-06:00
) will have different values obviously, but the time zone CST
will inherit the daylight saving information depending upon the date by default.So your conversion may not be as simple as it looks.
Assuming that you want to convert a Date
d
that you know is valid at time zone CST/CST
to the equivalent at time zone CST/CDT
, you would use:
SQL> SELECT from_tz(d, '-06:00') initial_ts,
2 from_tz(d, '-06:00') at time zone ('-05:00') converted_ts
3 FROM (SELECT cast(to_date('2012-10-09 01:10:21',
4 'yyyy-mm-dd hh24:mi:ss') as timestamp) d
5 FROM dual);
INITIAL_TS CONVERTED_TS
------------------------------- -------------------------------
09/10/12 01:10:21,000000 -06:00 09/10/12 02:10:21,000000 -05:00
My default timestamp format has been used here. I can specify a format explicitely:
SQL> SELECT to_char(from_tz(d, '-06:00'),'yyyy-mm-dd hh24:mi:ss TZR') initial_ts,
2 to_char(from_tz(d, '-06:00') at time zone ('-05:00'),
3 'yyyy-mm-dd hh24:mi:ss TZR') converted_ts
4 FROM (SELECT cast(to_date('2012-10-09 01:10:21',
5 'yyyy-mm-dd hh24:mi:ss') as timestamp) d
6 FROM dual);
INITIAL_TS CONVERTED_TS
------------------------------- -------------------------------
2012-10-09 01:10:21 -06:00 2012-10-09 02:10:21 -05:00
I don't have enough rep to comment here, so I'm submitting a new answer to improve on dogbane's answer. The dot . in the regexp
[[ sed-4.2.2.tar.bz2 =~ tar.bz2$ ]] && echo matched
will actually match any character, not only the literal dot between 'tar.bz2', for example
[[ sed-4.2.2.tar4bz2 =~ tar.bz2$ ]] && echo matched
[[ sed-4.2.2.tar§bz2 =~ tar.bz2$ ]] && echo matched
or anything that doesn't require escaping with '\'. The strict syntax should then be
[[ sed-4.2.2.tar.bz2 =~ tar\.bz2$ ]] && echo matched
or you can go even stricter and also include the previous dot in the regex:
[[ sed-4.2.2.tar.bz2 =~ \.tar\.bz2$ ]] && echo matched
For :hover
to override :visited
, and to make sure :visited
is the same as the initial color, :hover
must come after :visited
.
So if you want to disable the color change, a:visited
must come before a:hover
. Like this:
a { color: gray; }
a:visited { color: orange; }
a:hover { color: red; }
To disable :visited
change you would style it with non-pseudo class:
a, a:visited { color: gray; }
a:hover { color: red; }
GRANT ALL PRIVILEGES ON *.* TO 'user'@'ipadress'
Strings in c# are immutable. When in your code you do strgroupids.TrimEnd(',');
or strgroupids.TrimEnd(new char[] { ',' });
the strgroupids
string is not modified.
You need to do something like strgroupids = strgroupids.TrimEnd(',');
instead.
To quote from here:
Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.
For rails 5.1+ callbacks
As of Ruby on Rails 5.1, the attribute_changed?
and attribute_was
ActiveRecord methods will be deprecated
Use saved_change_to_attribute?
instead of attribute_changed?
@user.saved_change_to_street1? # => true/false
More examples here
You can specify the -o $@ option to your compile command to force the output of the compile command to take on the name of the target. For example, if you have:
...and you want to place the object files in:
...then you can compile cpp/class.cpp and cpp/driver.cpp separately into obj/class.o and obj/driver.o, and then link, with the following Makefile:
CC=c++
FLAGS=-std=gnu++11
INCS=-I./headers
SRC=./cpp
OBJ=./obj
EXE=./exe
${OBJ}/class.o: ${SRC}/class.cpp
${CC} ${FLAGS} ${INCS} -c $< -o $@
${OBJ}/driver.o: ${SRC}/driver.cpp ${SRC}/class.cpp
${CC} ${FLAGS} ${INCS} -c $< -o $@
driver: ${OBJ}/driver.o ${OBJ}/class.o
${CC} ${FLAGS} ${OBJ}/driver.o ${OBJ}/class.o -o ${EXE}/driver
As you've noticed, the WHERE
clause doesn't allow you to use aggregates in it. That's what the HAVING
clause is for.
HAVING t1.field3=MAX(t1.field3)
You need to edit your my.cnf
file and make sure you have the port set as in the following line:
port = 3360
Then restart your MySQL service and you should be good to go. There is no query you can run to make this change because the port
is not a dynamic variable (q.v. here for MySQL documentation showing a table of all system variables).
To start, Joe Kington's answer provides very good advice using a gui-neutral approach, and you should definitely take his advice (especially about Blitting) and put it into practice. More info on this approach, read the Matplotlib Cookbook
However, the non-GUI-neutral (GUI-biased?) approach is key to speeding up the plotting. In other words, the backend is extremely important to plot speed.
Put these two lines before you import anything else from matplotlib:
import matplotlib
matplotlib.use('GTKAgg')
Of course, there are various options to use instead of GTKAgg
, but according to the cookbook mentioned before, this was the fastest. See the link about backends for more options.
you can also use for loop to append or write data to a file. example:
for i in {1..10}; do echo "Hello Linux Terminal"; >> file.txt done
">>" is used to append.
">" is used to write.
Using Quick Watch in Visual Studio you can access the LoaderExceptions from ViewDetails of the thrown exception like this:
($exception).LoaderExceptions
Easy stuff:
this function will accept the target $hash and $replacements is also a hash containing newkey=>oldkey associations.
This function will preserve original order, but could be problematic for very large (like above 10k records) arrays regarding performance & memory.
function keyRename(array $hash, array $replacements) {
$new=array();
foreach($hash as $k=>$v)
{
if($ok=array_search($k,$replacements))
$k=$ok;
$new[$k]=$v;
}
return $new;
}
this alternative function would do the same, with far better performance & memory usage, at the cost of loosing original order (which should not be a problem since it is hashtable!)
function keyRename(array $hash, array $replacements) {
foreach($hash as $k=>$v)
if($ok=array_search($k,$replacements))
{
$hash[$ok]=$v;
unset($hash[$k]);
}
return $hash;
}
getResourceAsStream
is the right way to do it for web apps (as you already learned).
The reason is that reading from the file system cannot work if you package your web app in a WAR. This is the proper way to package a web app. It's portable that way, because you aren't dependent on an absolute file path or the location where your app server is installed.
An alternative to adding LINQ would be to use this code instead:
List<Pax_Detail> paxList = new List<Pax_Detail>(pax);
The code from the accepted answer helped me to debug the issue. I then realized that the SN field of the certificate
argument wasn't the same as what I thought was my SMTP server. By setting the Host
property of the SmtpClient instance to the SN value of the certificate I was able to fix the issue.
You can use fprintf/sprintf with familiar C syntax. Maybe something like:
fprintf('x = %d, y = %d \n x+y=%d \n x*y=%d \n x/y=%f\n', x,y,d,e,f)
reading your comment, this is how you use your functions from the main program:
x = 2;
y = 2;
[d e f] = answer(x,y);
fprintf('%d + %d = %d\n', x,y,d)
fprintf('%d * %d = %d\n', x,y,e)
fprintf('%d / %d = %f\n', x,y,f)
Also for the answer() function, you can assign the output values to a vector instead of three distinct variables:
function result=answer(x,y)
result(1)=addxy(x,y);
result(2)=mxy(x,y);
result(3)=dxy(x,y);
and call it simply as:
out = answer(x,y);
You can 'slice' a string
very easily, just like you'd pull items from a list
:
a_string = 'This is a string'
To get the first 4 letters:
first_four_letters = a_string[:4]
>>> 'This'
Or the last 5:
last_five_letters = a_string[-5:]
>>> 'string'
So applying that logic to your problem:
the_string = '416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f '
first_32_chars = the_string[:32]
>>> 416d76b8811b0ddae2fdad8f4721ddbe
You could use addEventListener to add as many listeners as you want.
document.getElementById("Save").addEventListener('click',function ()
{
alert("hello");
//validation code to see State field is mandatory.
} );
Also add script
tag after the element to make sure Save
element is loaded at the time when script runs
Rather than moving script tag you could call it when dom is loaded. Then you should place your code inside the
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("Save").addEventListener('click',function ()
{
alert("hello");
//validation code to see State field is mandatory.
} );
});
How about using recursive functions?
To get a value:
def getFromDict(dataDict, maplist):
first, rest = maplist[0], maplist[1:]
if rest:
# if `rest` is not empty, run the function recursively
return getFromDict(dataDict[first], rest)
else:
return dataDict[first]
And to set a value:
def setInDict(dataDict, maplist, value):
first, rest = maplist[0], maplist[1:]
if rest:
try:
if not isinstance(dataDict[first], dict):
# if the key is not a dict, then make it a dict
dataDict[first] = {}
except KeyError:
# if key doesn't exist, create one
dataDict[first] = {}
setInDict(dataDict[first], rest, value)
else:
dataDict[first] = value
Maybe it's the best possiblity to create a TimerTask that sets the received Location to a certain value (null?) regularly. If a new value is received by the GPSListener it will update the location with the current data.
I think that would be a working solution.
change onClick to onClick="changeDivContent(this)"
and try
function changeDivContent(btn) {
content.innerHTML = btn.value
}
function changeDivContent(btn) {_x000D_
content.innerHTML = btn.value_x000D_
}
_x000D_
<input type="radio" name="radiobutton" value="A" onClick="changeDivContent(this)">_x000D_
<input type="radio" name="radiobutton" value="B" onClick="changeDivContent(this)">_x000D_
_x000D_
<div id="content"></div>
_x000D_
A note for others who may be using Owl Carousel v 1.3.2:
You can replace the navigation text in the settings where you're enabling the navigation.
navigation:true,
navigationText: [
"<i class='fa fa-chevron-left'></i>",
"<i class='fa fa-chevron-right'></i>"
]
Inline elements (like SPAN, LABEL, etc.) are displayed so that their height and width are calculated by the browser based on their content. If you want to control height and width you have to change those elements' blocks.
display: block;
makes the element displayed as a solid block (like DIV tags) which means that there is a line break after the element (it's not inline). Although you can use display: inline-block
to fix the issue of line break, this solution does not work in IE6 because IE6 doesn't recognize inline-block. If you want it to be cross-browser compatible then look at this article: http://webjazz.blogspot.com/2008/01/getting-inline-block-working-across.html
redirect statement is legacy
use http-request redirect instead
acl http ssl_fc,not
http-request redirect scheme https if http
Do you mean the conversion 011001100110111101101111
? foo
, for example? You just take the binary stream, split it into separate bytes (01100110
, 01101111
, 01101111
) and look up the ASCII character that corresponds to given number. For example, 01100110
is 102 in decimal and the ASCII character with code 102 is f
:
$ perl -E 'say 0b01100110'
102
$ perl -E 'say chr(102)'
f
(See what the chr
function does.) You can generalize this algorithm and have a different number of bits per character and different encodings, the point remains the same.
#include <bits/stdc++.h>
using namespace std;
int main(){
string time;
int hours,seconds,minutes;
string merid;
char delim;
stringstream ss;
cin >> time;
ss << time;
ss >> hours >> delim >> minutes >> delim >> seconds >> merid;
if((merid=="PM"&&hours!=12)||(merid=="AM"&&hours==12))
hours=(hours+12)%24;
printf("%02d:%02d:%02d", hours, minutes, seconds);
return 0;
}
In regular expressions, "/" is a special character which needs to be escaped (AKA flagged by placing a \ before it thus negating any specialized function it might serve).
Here's what you need:
var word = /\/(\w+)/ig; // /abc Match
Read up on RegEx special characters here: http://www.regular-expressions.info/characters.html
var date = new Date();
var targetDate = moment(date).subtract(1, 'day').toDate(); // date object
Now, you can format how you wanna see this date or you can compare this date with another etc.
toDate()
function is the point.
To add a comment under any code on NOTEPAD++ first we have to save and define the programming or scripting file type. Like, save the file as xml, html etc. Once the file is saved in proper format you will be able to add a comment directly using the shortcut ctrl+Q
not bad .. but try this one ... (should works for all but ist just -webkit included)
<br>
<input type="text" style="
background: transparent;
border-bottom: 1px solid #B5D5FF;
border-left: 1px solid;
border-right: 1px solid;
border-left-color: #B5D5FF;
border-image: -webkit-linear-gradient(top, #fff 50%, #B5D5FF 0%) 1 repeat;
">
//Feel free to edit and add all other browser..
Make sure your project defines a module and you have given a name to the module. Then rebuild, and Xcode will create the -Swift.h
header file and you will be able to import.
You can set module definition and module name in your project settings.
as others said Calendar.MONTH returns int and is zero indexed.
to get the current month as a String
use SimpleDateFormat.format()
method
Calendar cal = Calendar.getInstance();
System.out.println(new SimpleDateFormat("MMM").format(cal.getTime()));
returns NOV
You can use MATCH
for instance.
Select the column from the first cell, for example cell A2 to cell A100 and insert a conditional formatting, using 'New Rule...' and the option to conditional format based on a formula.
In the entry box, put:
=MATCH(A2, 'Sheet2'!A:A, 0)
Pick the desired formatting (change the font to red or fill the cell background, etc) and click OK.
MATCH
takes the value A2
from your data table, looks into 'Sheet2'!A:A
and if there's an exact match (that's why there's a 0
at the end), then it'll return the row number.
Note: Conditional formatting based on conditions from other sheets is available only on Excel 2010 onwards. If you're working on an earlier version, you might want to get the list of 'Don't check' in the same sheet.
EDIT: As per new information, you will have to use some reverse matching. Instead of the above formula, try:
=SUM(IFERROR(SEARCH('Sheet2'!$A$1:$A$44, A2),0))
Edited solution that will make your SplashScreen look great on all APIs including API21 to API23
If you are only targeting APIs24+ you can simply scale down your vector drawable directly in its xml file like so:
<vector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:aapt="http://schemas.android.com/aapt"
android:viewportWidth="640"
android:viewportHeight="640"
android:width="240dp"
android:height="240dp">
<path
android:pathData="M320.96 55.9L477.14 345L161.67 345L320.96 55.9Z"
android:strokeColor="#292929"
android:strokeWidth="24" />
</vector>
in the code above I am rescaling a drawable I drew on a 640x640 canvas to be 240x240. then i just put it in my splash screen drawable like so and it works great:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:opacity="opaque"
android:paddingBottom="20dp" android:paddingRight="20dp" android:paddingLeft="20dp" android:paddingTop="20dp">
<!-- The background color, preferably the same as your normal theme -->
<item>
<shape>
<size android:height="120dp" android:width="120dp"/>
<solid android:color="@android:color/white"/>
</shape>
</item>
<!-- Your product logo - 144dp color version of your app icon -->
<item
android:drawable="@drawable/logo_vect"
android:gravity="center">
</item>
</layer-list>
my code is actually only drawing the triangle in the picture at the bottom but here you see what you can achieve with this. Resolution is finally great as opposed to the pixelated edges I was getting when using bitmap. so use a vector drawable by all means (there is a site called vectr that I used to create mine without the hasle of downloading specialized software).
EDIT in order to make it work also on API21-22-23
While the solution above works for devices runing API24+ I got really disappointed after installing my app a device running API22. I noticed that the splashscreen was again trying to fill the entire view and looking like shit. After tearing my eyebrows out for half a day I finally brute-forced a solution by sheer willpower.
you need to create a second file named exactly like the splashscreen xml (lets say splash_screen.xml) and place it into 2 folders called drawable-v22 and drawable-v21 that you will create in the res/ folder (in order to see them you have to change your project view from Android to Project). This serves to tell your phone to redirect to files placed in those folders whenever the relevant device runs an API corresponding to the -vXX suffix in the drawable folder, see this link. place the following code in the Layer-list of the splash_screen.xml file that you create in these folders:
<item>
<shape>
<size android:height="120dp" android:width="120dp"/>
<solid android:color="@android:color/white"/>
</shape>
</item>
<!-- Your product logo - 144dp color version of your app icon -->
<item android:gravity="center">
<bitmap android:gravity="center"
android:src="logo_vect"/>
</item>
For some reason for these APIs you have to wrap your drawable in a bitmap in order to make it work and jet the final result looks the same. The issue is that you have to use the aproach with the aditional drawable folders as the second version of the splash_screen.xml file will lead to your splash screen not being shown at all on devices running APIs higher than 23. You might also have to place the first version of the splash_screen.xml into drawable-v24 as android defaults to the closest drawable-vXX folder it can find for resources. hope this helps