I don't like the proposed solution of using web.config
or app.config
. Try reading your own XML. Have a look at XML Settings Files – No more web.config.
Swift 3:
guard let url = URL(string: UIApplicationOpenSettingsURLString) else {return}
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
// Fallback on earlier versions
UIApplication.shared.openURL(url)
}
The maximum values do not depend on Eclipse, it depends on your OS (and obviously on the physical memory available).
You may want to take a look at this question: Max amount of memory per java process in Windows?
Most of what I write has already been covered by Pressacco, but this is specific to SpecFlow.
I was getting this message for the <specFlow>
element and therefore I added a specflow.xsd
file to the solution this answer (with some modifications to allow for the <plugins>
element).
Thereafter I (like Pressacco), right clicked within the file buffer of app.config
and selected properties, and within Schemas
, I added "specflow.xsd"
to the end. The entirety of Schemas
now reads:
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\1033\DotNetConfig.xsd" "C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\EntityFrameworkConfig_6_1_0.xsd" "C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\RazorCustomSchema.xsd" "specflow.xsd"
You need to place the expression in parentheses to stop them being treated as different parameters to the cmdlet:
Write-Host ($assoc.Id + " - " + $assoc.Name + " - " + $assoc.Owner)
Upgrading from Kepler to Luna worked for me.
I had just added some components for Java 1.8 support. It seems that they where not as compatible as I would like or that I mixed the wrong ones. It really caused a lot of problems. Trying to update the system reported errors as they couldn't fulfill some dependencies. Maven upgrades didn't work. Tried a lot of things.
So, if there is no reason to avoid the upgrade just add the luna repository to avalilable software sites (Luna http://download.eclipse.org/releases/luna/ ) and "check for updates". It is better to have all the components with the same version and there are some nice new features.
Run ps aux | grep nodejs
, find the PID of the process you're looking for, then run kill
starting with SIGTERM (kill -15 25239
). If that doesn't work then use SIGKILL instead, replacing -15
with -9
.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="match_parent" >
<RadioButton
android:id="@+id/butonSecim1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_weight=".50"
android:text="@string/buton1Text" />
<RadioButton
android:id="@+id/butonSecim2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_weight=".50"
android:text="@string/buton2Text" />
</RadioGroup>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TableLayout
android:id="@+id/bilgiAlani"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="invisible" >
<TableRow
android:id="@+id/BilgiAlanitableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/bilgiMesaji"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight=".100"
android:ems="10"
android:gravity="left|top"
android:inputType="textMultiLine" />
</TableRow>
</TableLayout>
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/metin4"
android:layout_height="match_parent"
android:layout_weight=".100"
android:text="deneme" />
</TableRow>
<TableRow
android:id="@+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/metin5"
android:layout_height="match_parent"
android:layout_weight=".100"
android:text="deneme" />
</TableRow>
</TableLayout>
</ScrollView>
Try to embed a table element.
<div>_x000D_
<table style='width:200px; height:100px;'>_x000D_
<td style='vertical-align:middle;'>_x000D_
copenhagen_x000D_
</td>_x000D_
</table>_x000D_
</div>
_x000D_
Referencing XCopy Force File
For forcing files, we could use pipeline "echo F |":
C:\Trash>xcopy 23.txt 24.txt
Does 24.txt specify a file name
or directory name on the target
(F = file, D = directory)?
C:\Trash>echo F | xcopy 23.txt 24.txt
Does 24.txt specify a file name
or directory name on the target
(F = file, D = directory)? F
C:23.txt
1 File(s) copied
For forcing a folder, we could use /i parameter for xcopy or using a backslash() at the end of the destination folder.
Parsing a string with date and time into a particular point in time (Java calls it an "Instant
") is quite complicated. Java has been tackling this in several iterations. The latest one, java.time
and java.time.chrono
, covers almost all needs (except Time Dilation :) ).
However, that complexity brings a lot of confusion.
The key to understand date parsing is:
LocalDateTime
, ZonedDateTime
et al. so complicatedThere are time zones.
A time zone is basically a "stripe"*[1] of the Earth's surface whose authorities follow the same rules of when does it have which time offset. This includes summer time rules.
The time zones change over time for various areas, mostly based on who conquers whom. And one time zone's rules change over time as well.
There are time offsets. That is not the same as time zones, because a time zone may be e.g. "Prague", but that has summer time offset and winter time offset.
If you get a timestamp with a time zone, the offset may vary, depending on what part of the year it is in. During the leap hour, the timestamp may mean 2 different times, so without additional information, it can't be reliably converted.
Note: By timestamp I mean "a string that contains a date and/or time, optionally with a time zone and/or time offset."
Several time zones may share the same time offset for certain periods. For instance, GMT/UTC time zone is the same as "London" time zone when the summer time offset is not in effect.
To make it a bit more complicated (but that's not too important for your use case) :
2040-12-31 24:00:00
may be a valid date-time.) This needs regular updates of the metadata that systems use to have the date conversions right. E.g. on Linux, you get regular updates to the Java packages including these new data.The updates do not always keep the previous behavior for both historical and future timestamps. So it may happen that parsing of the two timestamps around some time zone's change comparing them may give different results when running on different versions of the software. That also applies to comparing between the affected time zone and other time zone.
Should this cause a bug in your software, consider using some timestamp that does not have such complicated rules, like UNIX timestamp.
Because of 7, for the future dates, we can't convert dates exactly with certainty. So, for instance, current parsing of 8524-02-17 12:00:00
may be off a couple of seconds from the future parsing.
java.util.Date
which had a bit naive approach, assuming that there's just the year, month, day, and time. This quickly did not suffice.java.sql.Date
was introduced, with it's own limitations.Calendar
API was introduced.java.time
When you are consuming a timestamp string, you need to know what information it contains. This is the crucial point. If you don't get this right, you end up with a cryptic exceptions like "Can't create Instant" or "Zone offset missing" or "unknown zone id" etc.
Does it contain the date and the time?
Does it have a time offset?
A time offset is the +hh:mm
part. Sometimes, +00:00
may be substituted with Z
as 'Zulu time', UTC
as Universal Time Coordinated, or GMT
as Greenwich Mean Time. These also set the time zone.
For these timestamps, you use OffsetDateTime
.
Does it have a time zone?
For these timestamps, you use ZonedDateTime
.
Zone is specified either by
The list of time zones is compiled by a "TZ database", backed by ICAAN.
According to ZoneId
's javadoc, The zone id's can also somehow be specified as Z
and offset. I'm not sure how this maps to real zones.
If the timestamp, which only has a TZ, falls into a leap hour of time offset change, then it is ambiguous, and the interpretation is subject of ResolverStyle
, see below.
If it has neither, then the missing context is assumed or neglected. And the consumer has to decide. So it needs to be parsed as LocalDateTime
and converted to OffsetDateTime
by adding the missing info:
Duration
), or when you don't know and it doesn't really matter (e.g. local bus schedule).Partial time information
LocalDate
, LocalTime
, OffsetTime
, MonthDay
, Year
, or YearMonth
out of it.If you have the full information, you can get a java.time.Instant
. This is also internally used to convert between OffsetDateTime
and ZonedDateTime
.
There is an extensive documentation on DateTimeFormatter
which can both parse a timestamp string and format to string.
The pre-created DateTimeFormatter
s should cover moreless all standard timestamp formats. For instance, ISO_INSTANT
can parse 2011-12-03T10:15:30.123457Z
.
If you have some special format, then you can create your own DateTimeFormatter (which is also a parser).
private static final DateTimeFormatter TIMESTAMP_PARSER = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SX"))
.toFormatter();
I recommend to look at the source code of DateTimeFormatter
and get inspired on how to build one using DateTimeFormatterBuilder
. While you're there, also have a look at ResolverStyle
which controls whether the parser is LENIENT, SMART or STRICT for the formats and ambiguous information.
Now, the frequent mistake is to go into the complexity of TemporalAccessor
. This comes from how the developers were used to work with SimpleDateFormatter.parse(String)
. Right, DateTimeFormatter.parse("...")
gives you TemporalAccessor
.
// No need for this!
TemporalAccessor ta = TIMESTAMP_PARSER.parse("2011-... etc");
But, equiped with the knowledge from the previous section, you can conveniently parse into the type you need:
OffsetDateTime myTimestamp = OffsetDateTime.parse("2011-12-03T10:15:30.123457Z", TIMESTAMP_PARSER);
You do not actually need to the DateTimeFormatter
either. The types you want to parse have the parse(String)
methods.
OffsetDateTime myTimestamp = OffsetDateTime.parse("2011-12-03T10:15:30.123457Z");
Regarding TemporalAccessor
, you can use it if you have a vague idea of what information there is in the string, and want to decide at runtime.
I hope I shed some light of understanding onto your soul :)
Note: There's a backport of java.time
to Java 6 and 7: ThreeTen-Backport. For Android it has ThreeTenABP.
[1] Not just that they are not stripes, but there also some weird extremes. For instance, some neighboring pacific islands have +14:00 and -11:00 time zones. That means, that while on one island, there is 1st May 3 PM, on another island not so far, it is still 30 April 12 PM (if I counted correctly :) )
print my_string[0:100]
Resurrecting the dead here, but just in case someone stumbles against this like myself. I know where to get the maximum value of a double, the (more) interesting part was to how did they get to that number.
double has 64 bits. The first one is reserved for the sign.
Next 11 represent the exponent (that is 1023 biased). It's just another way to represent the positive/negative values. If there are 11 bits then the max value is 1023.
Then there are 52 bits that hold the mantissa.
This is easily computed like this for example:
public static void main(String[] args) {
String test = Strings.repeat("1", 52);
double first = 0.5;
double result = 0.0;
for (char c : test.toCharArray()) {
result += first;
first = first / 2;
}
System.out.println(result); // close approximation of 1
System.out.println(Math.pow(2, 1023) * (1 + result));
System.out.println(Double.MAX_VALUE);
}
You can also prove this in reverse order :
String max = "0" + Long.toBinaryString(Double.doubleToLongBits(Double.MAX_VALUE));
String sign = max.substring(0, 1);
String exponent = max.substring(1, 12); // 11111111110
String mantissa = max.substring(12, 64);
System.out.println(sign); // 0 - positive
System.out.println(exponent); // 2046 - 1023 = 1023
System.out.println(mantissa); // 0.99999...8
This should do the trick:
#include <stdio.h>
NSString *readLineAsNSString(FILE *file)
{
char buffer[4096];
// tune this capacity to your liking -- larger buffer sizes will be faster, but
// use more memory
NSMutableString *result = [NSMutableString stringWithCapacity:256];
// Read up to 4095 non-newline characters, then read and discard the newline
int charsRead;
do
{
if(fscanf(file, "%4095[^\n]%n%*c", buffer, &charsRead) == 1)
[result appendFormat:@"%s", buffer];
else
break;
} while(charsRead == 4095);
return result;
}
Use as follows:
FILE *file = fopen("myfile", "r");
// check for NULL
while(!feof(file))
{
NSString *line = readLineAsNSString(file);
// do stuff with line; line is autoreleased, so you should NOT release it (unless you also retain it beforehand)
}
fclose(file);
This code reads non-newline characters from the file, up to 4095 at a time. If you have a line that is longer than 4095 characters, it keeps reading until it hits a newline or end-of-file.
Note: I have not tested this code. Please test it before using it.
double amount = 25.00;
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(amount));
If you are using JSP 2.0 and above It will come with the EL support:
so that you can write in plain english and use and
with empty
operators to write your test:
<c:if test="${(empty object_1.attribute_A) and (empty object_2.attribute_B)}">
Here is a simple solution for dates:
from scipy.interpolate import make_interp_spline
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as dates
from datetime import datetime
data = {
datetime(2016, 9, 26, 0, 0): 26060, datetime(2016, 9, 27, 0, 0): 23243,
datetime(2016, 9, 28, 0, 0): 22534, datetime(2016, 9, 29, 0, 0): 22841,
datetime(2016, 9, 30, 0, 0): 22441, datetime(2016, 10, 1, 0, 0): 23248
}
#create data
date_np = np.array(list(data.keys()))
value_np = np.array(list(data.values()))
date_num = dates.date2num(date_np)
# smooth
date_num_smooth = np.linspace(date_num.min(), date_num.max(), 100)
spl = make_interp_spline(date_num, value_np, k=3)
value_np_smooth = spl(date_num_smooth)
# print
plt.plot(date_np, value_np)
plt.plot(dates.num2date(date_num_smooth), value_np_smooth)
plt.show()
I suggest using a custom Adapter, first create a Xml-file, for example layout/customlistview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" >
<ImageView
android:id="@+id/image"
android:layout_alignParentRight="true"
android:paddingRight="4dp" />
<TextView
android:id="@+id/title"
android:layout_toLeftOf="@id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="23sp"
android:maxLines="1" />
<TextView
android:id="@+id/subtitle"
android:layout_toLeftOf="@id/image" android:layout_below="@id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Assuming you have a custom class like this
public class CustomClass {
private long id;
private String title, subtitle, picture;
public CustomClass () {
}
public CustomClass (long id, String title, String subtitle, String picture) {
this.id = id;
this.title= title;
this.subtitle= subtitle;
this.picture= picture;
}
//add getters and setters
}
And a CustomAdapter.java
uses the xml-layout
public class CustomAdapter extends ArrayAdapter {
private Context context;
private int resource;
private LayoutInflater inflater;
public CustomAdapter (Context context, List<CustomClass> values) { // or String[][] or whatever
super(context, R.layout.customlistviewitem, values);
this.context = context;
this.resource = R.layout.customlistview;
this.inflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = (RelativeLayout) inflater.inflate(resource, null);
CustomClass item = (CustomClass) getItem(position);
TextView textviewTitle = (TextView) convertView.findViewById(R.id.title);
TextView textviewSubtitle = (TextView) convertView.findViewById(R.id.subtitle);
ImageView imageview = (ImageView) convertView.findViewById(R.id.image);
//fill the textviews and imageview with the values
textviewTitle = item.getTtile();
textviewSubtitle = item.getSubtitle();
if (item.getAfbeelding() != null) {
int imageResource = context.getResources().getIdentifier("drawable/" + item.getImage(), null, context.getPackageName());
Drawable image = context.getResources().getDrawable(imageResource);
}
imageview.setImageDrawable(image);
return convertView;
}
}
Did you manage to do it? Feel free to ask if you want more info on something :)
EDIT: Changed the adapter to suit a List instead of just a List
In case this helps anyone, if you are using a Git repo, make sure the jars make it into the WEB-INF/lib INSIDE the git repo and not just in the project WEB-INF/lib
Then copy image source
Now add ![alt tag](http://url/to/img.png)
to your README.md file
Done!
Alternatively you can use some image hosting site like imgur
and get it's url and add it in your README.md file or you can use some static file hosting too.
.. I found the above solutions didn't work for me (on current versions of firefox and safari at least).
In my case I'm actually trying to do it with an img tag, not background-image, though it should also work for background-image if you use z-height:
<img src='$url' style='position:absolute; top,left:0px; width,max-height:100%; border:0;' >
This scales the image to be 'fullscreen' (probably breaking the aspect ratio) which was what I wanted to do but had a hard-time finding.
It may also work for background-image though I gave up on trying that kind of solution after cover/contain didn't work for me.
I found contain behaviour didn't seem to match the documentation I could find anywhere - I understood the documentation to say contain should make the largest dimension get contained within the screen (maintained aspect). I found contain always made my image tiny (original image was large).
Contain was with some hacks closer to what I wanted than cover, which seems to be that the aspect is maintained but image is scaled to make the smallest-dimension match the screen - i.e. always make the image as big as it can until one of the dimensions would go offscreen...
I tried a bunch of different things, starting over included, but found height was essentially always ignored and would overflow. (I've been trying to scale a non-widescreen image to be fullscreen on both, broken-aspect is ok for me). Basically, the above is what worked for me, hope it helps someone.
This work for me
@Html.TextBoxFor(model => model.Age, htmlAttributes: new { @Value = "" })
may be this will help:
map.setCenter(window.markersArray[2].getPosition());
all the markers info are in markersArray array and it is global. So you can access it from anywhere using window.variablename. Each marker has a unique id and you can put that id in the key of array. so you create marker like this:
window.markersArray[2] = new google.maps.Marker({
position: new google.maps.LatLng(23.81927, 90.362349),
map: map,
title: 'your info '
});
Hope this will help.
I don't really know what you mean by "local access". But for that solution you need to be able to access over ssh the server to copy the files where is database is stored.
I cannot use mysqldump, because my database is big (7Go, mysqldump fail) If the version of the 2 mysql database is too different it might not work, you can check your mysql version using mysql -V.
1) Copy the data from your remote server to your local computer (vps is the alias to your remote server, can be replaced by [email protected])
ssh vps:/etc/init.d/mysql stop
scp -rC vps:/var/lib/mysql/ /tmp/var_lib_mysql
ssh vps:/etc/init.d/apache2 start
2) Import the data copied on your local computer
/etc/init.d/mysql stop
sudo chown -R mysql:mysql /tmp/var_lib_mysql
sudo nano /etc/mysql/my.cnf
-> [mysqld]
-> datadir=/tmp/var_lib_mysql
/etc/init.d/mysql start
If you have a different version, you may need to run
/etc/init.d/mysql stop
mysql_upgrade -u root -pPASSWORD --force #that step took almost 1hrs
/etc/init.d/mysql start
Malakgeorge answer is nice an can be easily wrapped into a jQuery function:
$.fn.sortSelectByText = function(){
this.each(function(){
var selected = $(this).val();
var opts_list = $(this).find('option');
opts_list.sort(function(a, b) { return $(a).text() > $(b).text() ? 1 : -1; });
$(this).html('').append(opts_list);
$(this).val(selected);
})
return this;
}
## list of columns
l1 = ['PM2.5', 'PM10', 'TEMP', 'BP', ' RH', 'WS','CO', 'O3', 'Nox', 'SO2']
for i in l1:
for j in range(0, 8431): #rows = 8431
df[i][j] = int(df[i][j])
I recommend you to use this only with small data. This code has complexity of O(n^2).
Try this:
dt.Rows[RowNumber]["ColumnName"] = "Your value"
For example: if you want to add value 5 (number 5) to 1st row and column name "index" you would do this
dt.Rows[0]["index"] = 5;
I believe DataTable row starts with 0
I believe urlencode is for query parameters, whereas the rawurlencode is for the path segments. This is mainly due to %20
for path segments vs +
for query parameters. See this answer which talks about the spaces: When to encode space to plus (+) or %20?
However %20
now works in query parameters as well, which is why rawurlencode is always safer. However the plus sign tends to be used where user experience of editing and readability of query parameters matter.
Note that this means rawurldecode
does not decode +
into spaces (http://au2.php.net/manual/en/function.rawurldecode.php). This is why the $_GET is always automatically passed through urldecode
, which means that +
and %20
are both decoded into spaces.
If you want the encoding and decoding to be consistent between inputs and outputs and you have selected to always use +
and not %20
for query parameters, then urlencode
is fine for query parameters (key and value).
The conclusion is:
Path Segments - always use rawurlencode/rawurldecode
Query Parameters - for decoding always use urldecode (done automatically), for encoding, both rawurlencode or urlencode is fine, just choose one to be consistent, especially when comparing URLs.
TryGetValue is slightly faster, because FindEntry will only be called once.
How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.
FYI: It's not actually catching an error.
It's calling:
public bool TryGetValue(TKey key, out TValue value)
{
int index = this.FindEntry(key);
if (index >= 0)
{
value = this.entries[index].value;
return true;
}
value = default(TValue);
return false;
}
ContainsKey is this:
public bool ContainsKey(TKey key)
{
return (this.FindEntry(key) >= 0);
}
You can execute any shell command using the shelljs module
const shell = require('shelljs')
shell.exec('./path_to_your_file')
Right click on eclipse icon and click on open file location then delete the eclipse folder from drive(Save backup of your eclipse workspace if you want). Also delete eclipse icon. Thats it..
I pieced a few of the other posts together, as the workbench 'preferences' fix did not work for me. (WB 6.3)
SELECT CAST(`column` AS CHAR(10000) CHARACTER SET utf8) FROM `table`;
You can use sp_help
in SQL Server 2008.
sp_help <table_name>;
Keyboard shortcut for the above command: select table name (i.e highlight it) and press ALT+F1.
Make sure you are using this org.json: https://mvnrepository.com/artifact/org.json/json
if you are using Java 8 then you can use
import org.json.JSONArray;
import org.json.JSONObject;
JSONArray array = ...;
array.forEach(item -> {
JSONObject obj = (JSONObject) item;
parse(obj);
});
Just added a simple test to prove that it works:
Add the following dependency into your pom.xml
file (To prove that it works, I have used the old jar which was there when I have posted this answer)
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
And the simple test code snippet will be:
import org.json.JSONArray;
import org.json.JSONObject;
public class Test {
public static void main(String args[]) {
JSONArray array = new JSONArray();
JSONObject object = new JSONObject();
object.put("key1", "value1");
array.put(object);
array.forEach(item -> {
System.out.println(item.toString());
});
}
}
output:
{"key1":"value1"}
with a little help of math
#include <math.h>
int main(){
int a = -1;
unsigned int b;
b = abs(a);
}
Make sure your modal is not placed in a container, try to add the !important annotation if it's not changing the width from the original one.
I was able to fix this error by simply initializing a variable that was being used later in my program. At the time, I wasn't using Option Explicit in my class/module.
Also works with the style tag:
<span class="glyphicon glyphicon-ok" style="color:#00FF00;"></span>
<span class="glyphicon glyphicon-remove" style="color:#FF0000;"></span>
You can try the following and it worked for me.
Import following scripts and css files as there are used by the date picker.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
The JS coding for the Date Picker I use.
<script>
$(document).ready(function(){
// alert ('Cliecked');
var date_input=$('input[name="orangeDateOfBirthForm"]'); //our date input has the name "date"
var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form').parent() : "body";
var options={
format: 'dd/mm/yyyy', //format of the date
container: container,
changeYear: true, // you can change the year as you need
changeMonth: true, // you can change the months as you need
todayHighlight: true,
autoclose: true,
yearRange: "1930:2100" // the starting to end of year range
};
date_input.datepicker(options);
});
</script>
The HTML Coding:
<input type="text" id="orangeDateOfBirthForm" name="orangeDateOfBirthForm" class="form-control validate" required>
<label data-error="wrong" data-success="right" for="orangeForm-email">Date of Birth</label>
INDEX=0
for i in $list; do
echo ${INDEX}_$i
let INDEX=${INDEX}+1
done
In Android 4
Go to Setting->Location services->
Uncheck Google`s location service.
Check GPS satelites.
For test you can use GPS Test.Please test Outdoor!
Offline maps are available on new version of Google map.
In addition to what the other answers have said, note that the '/' character in "dd/MM/yyyy" is not a literal character: it represents the date separator of the current user's culture. Therefore, if the current culture uses yyyy-MM-dd dates, then when you call toString it will give you a date such as "31-12-2016" (using dashes instead of slashes). To force it to use slashes, you need to escape that character:
DateTime.Now.ToString("dd/MM/yyyy") --> "19-12-2016" for a Japanese user
DateTime.Now.ToString("dd/MM/yyyy") --> "19/12/2016" for a UK user
DateTime.Now.ToString("dd\\/MM\\/yyyy") --> "19/12/2016" independent of region
First you have to download a JQuery plugin to allow Cross-domain requests. Download it here: https://github.com/padolsey/jQuery-Plugins/downloads
Import the file called query.xdomainsajax.js into your project and include it with this code:
<script type="text/javascript" src="/path/to/the/file/jquery.xdomainajax.js"></script>
To get the html of an external web page in text form you can write this:
$.ajax({
url: "http://www.website.com",
type: 'GET',
success: function(res) {
var text = res.responseText;
// then you can manipulate your text as you wish
}
});
Here is an option using a for
loop by groups rather by rows (like OP did)
for (i in unique(df$cat)) df$num[df$cat == i] <- seq_len(sum(df$cat == i))
Continuing this answer, There is another difference that if you want your method to return different values for example when it is first time called, second time called etc then you can pass values so for example...
PowerMockito.doReturn(false, false, true).when(SomeClass.class, "SomeMethod", Matchers.any(SomeClass.class));
So it will return false when the method is called in same test case and then it will return false again and lastly true.
Git for windows 2.6.3:
git submodule update --rebase --remote
querySelectorAll returns a NodeList which has its own forEach method:
document.querySelectorAll('input').forEach( input => {
// ...
});
getElementsByTagName now returns an HTMLCollection instead of a NodeList. So you would first need to convert it to an array to have access to methods like map and forEach:
Array.from(document.getElementsByTagName('input')).forEach( input => {
// ...
});
This error is thrown when the column of a table puts constraint [ mostly length ]. . E.g. if database schema for column myColumn is CHAR(2), then when your call from any of your application to insert value, you must pass String of length two.
The error basically says it; string of length three and above is inconsistent to fit the length restriction specified by database schema. That's why SQL Server warns and throws data loss/ Truncation error.
Could always do:
db.foo.find().forEach(function(f){print(tojson(f, '', true));});
To get that compact view.
Also, I find it very useful to limit the fields returned by the find so:
db.foo.find({},{name:1}).forEach(function(f){print(tojson(f, '', true));});
which would return only the _id and name field from foo.
When creating your own library, you can can create *.d.ts
files by using the tsc
(TypeScript Compiler) command like so:
(assuming you're building your library to the dist/lib
folder)
tsc -d --declarationDir dist/lib --declarationMap --emitDeclarationOnly
-d
(--declaration
): generates the *.d.ts
files--declarationDir dist/lib
: Output directory for generated declaration files.--declarationMap
: Generates a sourcemap for each corresponding ‘.d.ts’ file.--emitDeclarationOnly
: Only emit ‘.d.ts’ declaration files. (no compiled JS)(see the docs for all command line compiler options)
Or for instance in your package.json
:
"scripts": {
"build:types": "tsc -d --declarationDir dist/lib --declarationMap --emitDeclarationOnly",
}
and then run: yarn build:types
(or npm run build:types
)
Open Notepad
Type in the following:
javac *
java Main
SaveAs Main.bat or whatever name you wish to use for the batch file
Make sure that Main.java is in the same folder along with your batch file
Double Click on the batch file to run the Main.java file
The above answers do not handle blank/undefined values to fix this I used the below code and replaced blanks with NA :
function getMax(dateArray, filler) {
filler= filler?filler:"";
if (!dateArray.length) {
return filler;
}
var max = "";
dateArray.forEach(function(date) {
if (date) {
var d = new Date(date);
if (max && d.valueOf()>max.valueOf()) {
max = d;
} else if (!max) {
max = d;
}
}
});
return max;
};
console.log(getMax([],"NA"));
console.log(getMax(datesArray,"NA"));
console.log(getMax(datesArray));
function getMin(dateArray, filler) {
filler = filler ? filler : "";
if (!dateArray.length) {
return filler;
}
var min = "";
dateArray.forEach(function(date) {
if (date) {
var d = new Date(date);
if (min && d.valueOf() < min.valueOf()) {
min = d;
} else if (!min) {
min = d;
}
}
});
return min;
}
console.log(getMin([], "NA"));
console.log(getMin(datesArray, "NA"));
console.log(getMin(datesArray));
I have added a plain javascript demo here and used it as a filter with AngularJS in this codepen
I needed something similar for arrays. That helped me
some_array_rounded=np.around(some_array, 5)
The answer (which I know is not what you're looking for) is:
class SpecialDerived : Base
{
public override void Say()
{
Console.WriteLine("Called from Special Derived.");
base.Say();
}
}
The truth is, you only have direct interaction with the class you inherit from. Think of that class as a layer - providing as much or as little of it or its parent's functionality as it desires to its derived classes.
EDIT:
Your edit works, but I think I would use something like this:
class Derived : Base
{
protected bool _useBaseSay = false;
public override void Say()
{
if(this._useBaseSay)
base.Say();
else
Console.WriteLine("Called from Derived");
}
}
Of course, in a real implementation, you might do something more like this for extensibility and maintainability:
class Derived : Base
{
protected enum Mode
{
Standard,
BaseFunctionality,
Verbose
//etc
}
protected Mode Mode
{
get; set;
}
public override void Say()
{
if(this.Mode == Mode.BaseFunctionality)
base.Say();
else
Console.WriteLine("Called from Derived");
}
}
Then, derived classes can control their parents' state appropriately.
It may just be me but it seemed like most of these answers were not complete or would not work correctly. I made something very quick and dirty. That being said not sure how good of an idea it is to do it this way, but it works perfectly every time.
while (true)
{
if(DateTime.Now.ToString("HH:mm") == "22:00")
{
//do something here
//ExecuteFunctionTask();
//Make sure it doesn't execute twice by pausing 61 seconds. So that the time is past 2200 to 2201
Thread.Sleep(61000);
}
Thread.Sleep(10000);
}
In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):
select myintfield + 0.0 as myfloatfield from mytable
While @Heximal's answer works, I don't personally recommend it.
This is because it uses implicit casting. Although you didn't type CAST
, either the SUM()
or the 0.0
need to be cast to be the same data-types, before the +
can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +
. But SUM(aFloatField) + 0
does not yield an INT, because the 0
is being implicitly cast to a FLOAT.
I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.
If you want to be explicit, I would use the following.
CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT requires 8.0
You can try the following to see what happens...
CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))
Abusive one-liner!
Array.from(fd).reduce((obj, [k, v]) => ({...obj, [k]: v}), {});
Today I learned firefox has object spread support and array destructuring!
That example is pretty vague, but maybe something like this?
items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [''.join(items[3:6])]
It basically does a splice (or assignment to a slice) operation. It removes items 3 to 6 and inserts a new list in their place (in this case a list with one item, which is the concatenation of the three items that were removed.)
For any type of list, you could do this (using the +
operator on all items no matter what their type is):
items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [reduce(lambda x, y: x + y, items[3:6])]
This makes use of the reduce
function with a lambda
function that basically adds the items together using the +
operator.
The official postgres docker image will run .sql
scripts found in the /docker-entrypoint-initdb.d/
folder.
So all you need is to create the following sql script:
init.sql
CREATE USER docker;
CREATE DATABASE docker;
GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
and add it in your Dockerfile:
Dockerfile
FROM library/postgres
COPY init.sql /docker-entrypoint-initdb.d/
But since July 8th, 2015, if all you need is to create a user and database, it is easier to just make use to the POSTGRES_USER
, POSTGRES_PASSWORD
and POSTGRES_DB
environment variables:
docker run -e POSTGRES_USER=docker -e POSTGRES_PASSWORD=docker -e POSTGRES_DB=docker library/postgres
or with a Dockerfile:
FROM library/postgres
ENV POSTGRES_USER docker
ENV POSTGRES_PASSWORD docker
ENV POSTGRES_DB docker
From the documentation of the postgres Docker image, it is said that
[...] it will source any *.sh script found in that directory [
/docker-entrypoint-initdb.d
] to do further initialization before starting the service
What's important here is "before starting the service". This means your script make_db.sh will be executed before the postgres service would be started, hence the error message "could not connect to database postgres".
After that there is another useful piece of information:
If you need to execute SQL commands as part of your initialization, the use of Postgres single user mode is highly recommended.
Agreed this can be a bit mysterious at the first look. What it says is that your initialization script should start the postgres service in single mode before doing its actions. So you could change your make_db.ksh script as follows and it should get you closer to what you want:
NOTE, this has changed recently in the following commit. This will work with the latest change:
export PGUSER=postgres
psql <<- EOSQL
CREATE USER docker;
CREATE DATABASE docker;
GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL
Previously, the use of --single
mode was required:
gosu postgres postgres --single <<- EOSQL
CREATE USER docker;
CREATE DATABASE docker;
GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL
Log into the Twitter Developers section.
Go to "Create an app"
Fill in the details of the application you'll be using to connect with the API
Click on Create your Twitter application
Details of your new app will be shown along with your consumer key and consumer secret.
If you need access tokens, scroll down and click Create my access token
By default your apps will be granted for read-only access. To change this, go to the Settings tab and change the access level required in the "Application Type" section.
To get the consumer and access tokens for an existing application, go to My applications (which is available from the menu in the upper-right).
You can't decrypt but you can BRUTEFORCE IT...
I.E: iterate a password list and check if one of them match with stored hash.
script from github: https://github.com/BREAKTEAM/Debcrypt
GitHub has a new option relative to the preceding answers, just copy/paste the command lines from the PR:
Merge
or Squash and merge
buttonview command line instructions
javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean
This literally means that the mentioned class com.example.Bean
doesn't have a public (non-static!) getter method for the mentioned property foo
. Note that the field itself is irrelevant here!
The public getter method name must start with get
, followed by the property name which is capitalized at only the first letter of the property name as in Foo
.
public Foo getFoo() {
return foo;
}
You thus need to make sure that there is a getter method matching exactly the property name, and that the method is public
(non-static
) and that the method does not take any arguments and that it returns non-void
. If you have one and it still doesn't work, then chances are that you were busy editing code forth and back without firmly cleaning the build, rebuilding the code and redeploying/restarting the application. You need to make sure that you have done so.
For boolean
(not Boolean
!) properties, the getter method name must start with is
instead of get
.
public boolean isFoo() {
return foo;
}
Regardless of the type, the presence of the foo
field itself is thus not relevant. It can have a different name, or be completely absent, or even be static
. All of below should still be accessible by ${bean.foo}
.
public Foo getFoo() {
return bar;
}
public Foo getFoo() {
return new Foo("foo");
}
public Foo getFoo() {
return FOO_CONSTANT;
}
You see, the field is not what counts, but the getter method itself. Note that the property name itself should not be capitalized in EL. In other words, ${bean.Foo}
won't ever work, it should be ${bean.foo}
.
The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block.
#include <stdio.h>
int main ()
{
printf("Hello ");
goto Cleanup;
Cleanup: ; //This is an empty statement.
char *str = "World\n";
printf("%s\n", str);
}
Have you tried @Lazy
loading the datasource? Because you're initialising your embedded Tomcat container within the Spring context, you have to delay the initialisation of your DataSource
(until the JNDI vars have been setup).
N.B. I haven't had a chance to test this code yet!
@Lazy
@Bean(destroyMethod="")
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("java:comp/env/jdbc/myDataSource");
bean.setProxyInterface(DataSource.class);
//bean.setLookupOnStartup(false);
bean.afterPropertiesSet();
return (DataSource)bean.getObject();
}
You may also need to add the @Lazy
annotation wherever the DataSource is being used. e.g.
@Lazy
@Autowired
private DataSource dataSource;
string _connString = "metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=DATABASE;persist security info=True;user id=sa;password=YourPassword;multipleactiveresultsets=True;App=EntityFramework"";
EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder(_connString);
ctx = new Entities(_connString);
You can get the connection string from the web.config, and just set that in the EntityConnectionStringBuilder constructor, and use the EntityConnectionStringBuilder as an argument in the constructor for the context.
Cache the connection string by username. Simple example using a couple of generic methods to handle adding/retrieving from cache.
private static readonly ObjectCache cache = MemoryCache.Default;
// add to cache
AddToCache<string>(username, value);
// get from cache
string value = GetFromCache<string>(username);
if (value != null)
{
// got item, do something with it.
}
else
{
// item does not exist in cache.
}
public void AddToCache<T>(string token, T item)
{
cache.Add(token, item, DateTime.Now.AddMinutes(1));
}
public T GetFromCache<T>(string cacheKey) where T : class
{
try
{
return (T)cache[cacheKey];
}
catch
{
return null;
}
}
As in a similar question, use display: inline-block
with a placeholder element to vertically center the span inside of a block element:
html, body, #container, #placeholder { height: 100%; }_x000D_
_x000D_
#content, #placeholder { display:inline-block; vertical-align: middle; }
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div id="container">_x000D_
<span id="content">_x000D_
Content_x000D_
</span>_x000D_
<span id="placeholder"></span>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Vertical alignment is only applied to inline elements or table cells, so use it along with display:inline-block
or display:table-cell
with a display:table
parent when vertically centering block elements.
References:
No. As the documentation shows, you can only grant access to one object at a time.
ECMA2017 onwards:
Object.values(obj)
will fetch you all the property values as an array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
I want to point to the way Wordpress handles this:
define( 'ABSPATH', dirname( __FILE__ ) . '/' );
As Wordpress is very heavy used all over the web and also works fine locally I have much trust in this method. You can find this definition on the bottom of your wordpress wp-config.php
file
here is my soln to define the remote and local port and then write out to a file the received data, put this all in a class of your choice with the correct imports
static UdpClient sendClient = new UdpClient();
static int localPort = 49999;
static int remotePort = 49000;
static IPEndPoint localEP = new IPEndPoint(IPAddress.Any, localPort);
static IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), remotePort);
static string logPath = System.AppDomain.CurrentDomain.BaseDirectory + "/recvd.txt";
static System.IO.StreamWriter fw = new System.IO.StreamWriter(logPath, true);
private static void initStuff()
{
fw.AutoFlush = true;
sendClient.ExclusiveAddressUse = false;
sendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
sendClient.Client.Bind(localEP);
sendClient.BeginReceive(DataReceived, sendClient);
}
private static void DataReceived(IAsyncResult ar)
{
UdpClient c = (UdpClient)ar.AsyncState;
IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
fw.WriteLine(DateTime.Now.ToString("HH:mm:ss.ff tt") + " (" + receivedBytes.Length + " bytes)");
c.BeginReceive(DataReceived, ar.AsyncState);
}
static void Main(string[] args)
{
initStuff();
byte[] emptyByte = {};
sendClient.Send(emptyByte, emptyByte.Length, remoteEP);
}
Maybe an old thread, but this code might be useful to visitors who want to create without regex
def listToString(s):
# initialize an empty string
str1 = ""
# return string
return (str1.join(s))
r = "Hello! How are you? *Smiling_Face* *Heart* erwer"
r1 = list(r)
i = 0
r2 = list()
start = True
for string in r1:
if string == "*":
if(start):
start = False
else:
start = True
else:
if(start):
r2.append(string)
else:
print("skipped" + string)
print(listToString(r2))
Using async/await
async changeHandler(event) {
await this.setState({ yourName: event.target.value });
console.log(this.state.yourName);
}
There is no log file. Each node.js "app" is a separate entity. By default it will log errors to STDERR and output to STDOUT. You can change that when you run it from your shell to log to a file instead.
node my_app.js > my_app_log.log 2> my_app_err.log
Alternatively (recommended), you can add logging inside your application either manually or with one of the many log libraries:
I found the following css in order to style a Bootstrap input for a jquery autocomplete:
https://gist.github.com/daz/2168334#file-style-scss
.ui-autocomplete {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
float: left;
display: none;
min-width: 160px;
_width: 160px;
padding: 4px 0;
margin: 2px 0 0 0;
list-style: none;
background-color: #ffffff;
border-color: #ccc;
border-color: rgba(0, 0, 0, 0.2);
border-style: solid;
border-width: 1px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-webkit-background-clip: padding-box;
-moz-background-clip: padding;
background-clip: padding-box;
*border-right-width: 2px;
*border-bottom-width: 2px;
}
.ui-menu-item > a.ui-corner-all {
display: block;
padding: 3px 15px;
clear: both;
font-weight: normal;
line-height: 18px;
color: #555555;
white-space: nowrap;
}
.ui-state-hover, &.ui-state-active {
color: #ffffff;
text-decoration: none;
background-color: #0088cc;
border-radius: 0px;
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
background-image: none;
}
The difference between the two is best brought in what seems a necessary and sufficient definition of the dependencyManagement element available in Maven website docs:
dependencyManagement
"Default dependency information for projects that inherit from this one. The dependencies in this section are not immediately resolved. Instead, when a POM derived from this one declares a dependency described by a matching groupId and artifactId, the version and other values from this section are used for that dependency if they were not already specified." [ https://maven.apache.org/ref/3.6.1/maven-model/maven.html ]
It should be read along with some more information available on a different page:
“..the minimal set of information for matching a dependency reference against a dependencyManagement section is actually {groupId, artifactId, type, classifier}. In many cases, these dependencies will refer to jar artifacts with no classifier. This allows us to shorthand the identity set to {groupId, artifactId}, since the default for the type field is jar, and the default classifier is null.” [https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html ]
Thus, all the sub-elements (scope, exclusions etc.,) of a dependency element--other than groupId, artifactId, type, classifier, not just version--are available for lockdown/default at the point (and thus inherited from there onward) you specify the dependency within a dependencyElement. If you’d specified a dependency with the type and classifier sub-elements (see the first-cited webpage to check all sub-elements) as not jar and not null respectively, you’d need {groupId, artifactId, classifier, type} to reference (resolve) that dependency at any point in an inheritance originating from the dependencyManagement element. Else, {groupId, artifactId} would suffice if you do not intend to override the defaults for classifier and type (jar and null respectively). So default is a good keyword in that definition; any sub-element(s) (other than groupId, artifactId, classifier and type, of course) explicitly assigned value(s) at the point you reference a dependency override the defaults in the dependencyManagement element.
So, any dependency element outside of dependencyManagement, whether as a reference to some dependencyManagement element or as a standalone is immediately resolved (i.e. installed to the local repository and available for classpaths).
An improved version of @Thomas K's answer:
is_any_thread_alive()
according to this gist, which can terminates the main()
automatically.Example codes:
import threading
def job1():
...
def job2():
...
def is_any_thread_alive(threads):
return True in [t.is_alive() for t in threads]
if __name__ == "__main__":
...
t1 = threading.Thread(target=job1,daemon=True)
t2 = threading.Thread(target=job2,daemon=True)
t1.start()
t2.start()
while is_any_thread_alive([t1,t2]):
time.sleep(0)
Specify the optional selector to target what you want:
jQuery(this).parent('li').addClass('yourClass');
Or:
jQuery(this).parents('li').addClass('yourClass');
If your HTML is well-formed, you can easily employ an XML parser to do the job for you... If you're only reading, SAX would be ideal.
hey guys,i already find solution:
public static <T> T createApi(Context context, Class<T> clazz, String host, boolean debug) {
if (singleton == null) {
synchronized (RetrofitUtils.class) {
if (singleton == null) {
RestAdapter.Builder builder = new RestAdapter.Builder();
builder
.setEndpoint(host)
.setClient(new OkClient(OkHttpUtils.getInstance(context)))
.setRequestInterceptor(RequestIntercepts.newInstance())
.setConverter(new GsonConverter(GsonUtils.newInstance()))
.setErrorHandler(new ErrorHandlers())
.setLogLevel(debug ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)/*LogLevel.BASIC will cause response.getBody().in() close*/
.setLog(new RestAdapter.Log() {
@Override
public void log(String message) {
if (message.startsWith("{") || message.startsWith("["))
Logger.json(message);
else {
Logger.i(message);
}
}
});
singleton = builder.build();
}
}
}
return singleton.create(clazz);
}
You may want to look into using java's java.math.BigDecimal class if you really need precision math. Here is a good article from Oracle/Sun on the case for BigDecimal. While you can never represent 1/3 as someone mentioned, you can have the power to decide exactly how precise you want the result to be. setScale() is your friend.. :)
Ok, because I have way too much time on my hands at the moment here is a code example that relates to your question:
import java.math.BigDecimal;
/**
* Created by a wonderful programmer known as:
* Vincent Stoessel
* [email protected]
* on Mar 17, 2010 at 11:05:16 PM
*/
public class BigUp {
public static void main(String[] args) {
BigDecimal first, second, result ;
first = new BigDecimal("33.33333333333333") ;
second = new BigDecimal("100") ;
result = first.divide(second);
System.out.println("result is " + result);
//will print : result is 0.3333333333333333
}
}
and to plug my new favorite language, Groovy, here is a neater example of the same thing:
import java.math.BigDecimal
def first = new BigDecimal("33.33333333333333")
def second = new BigDecimal("100")
println "result is " + first/second // will print: result is 0.33333333333333
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).
Maven is a software management tool that can boost your productivity. I believe that such a tool is essential for software development in a new era.
However, Maven isn't appropriate for all code bases. If you need to support a large legacy code page, or you import code from a third party, then it would be better to avoid using. Maven expects things to be in a certain way (convention over configuration). If you are starting a new project, then this is more than fine. If, however, you have a full system you need to support, the lack of flexibility is a nightmare.
Another reason that people usually complain about maven is the steep learning curve. Also IDE integration is still not very mature. Apache is offering two plug-ins for Eclipse. The one is "mature", the other one offers a new approach. I suppose the new wouldn't be needed if the first one was adequate.
Another, more serious complain about Maven, is the use of XML for doing programming job. Perhaps tools like Buildr are the way to go.
From RMS's GDB debugger tutorial:
prompt > myprogram
Segmentation fault (core dumped)
prompt > gdb myprogram
...
(gdb) core core.pid
...
Make sure your file really is a core
image -- check it using file
.
Try this steps:
You need to allow Allow USB debugging in your device when popup.
Not using Mutex though, simple answer:
System.Diagnostics;
...
string thisprocessname = Process.GetCurrentProcess().ProcessName;
if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)
return;
Put it inside the Program.Main()
.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace Sample
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
//simple add Diagnostics namespace, and these 3 lines below
string thisprocessname = Process.GetCurrentProcess().ProcessName;
if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)
return;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Sample());
}
}
}
You can add MessageBox.Show
to the if
-statement and put "Application already running".
This might be helpful to someone.
That response is a Map, with a single element with key '212315952136472'. There's no 'data' key in the Map. If you want to loop through all entries, use something like this:
JSONObject userJson = JSON.parse(jsonResponse)
userJson.each { id, data -> println data.link }
If you know it's a single-element Map then you can directly access the link
:
def data = userJson.values().iterator().next()
String link = data.link
And if you knew the id (e.g. if you used it to make the request) then you can access the value more concisely:
String id = '212315952136472'
...
String link = userJson[id].link
COALESCE(field, 'default')
For example:
SELECT
t.id,
COALESCE(d.field, 'default')
FROM
test t
LEFT JOIN
detail d ON t.id = d.item
Also, you can use multiple columns to check their NULL
by COALESCE function.
For example:
mysql> SELECT COALESCE(NULL, 1, NULL);
-> 1
mysql> SELECT COALESCE(0, 1, NULL);
-> 0
mysql> SELECT COALESCE(NULL, NULL, NULL);
-> NULL
You can also combine them I guess:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
foo: function() {
alert("I'm foo!");
}
};
});
myApp.run(function($rootScope, myService) {
$rootScope.appData = myService;
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="appData.foo()">Call foo</button>
</body>
</html>
try
sudo /Applications/XAMPP/xamppfiles/bin/apachectl start
in terminal
This is the only install that resolved the issue for me.
SQL 2008 r2 w/ office 2010 64bit: "2007 Office System Driver: Data Connectivity Components"
In C A ternary operator " ? : " is available to construct conditional expressions of the form
exp1 ? exp2:exp3
where exp1,exp2 and exp3 are expressions
for Example
a=20;
b=25;
x=(a>b)?a:b;
in the above example x value will be assigned to b;
This can be written using if..else statement as follows
if (a>b)
x=a;
else
x=b;
**Hence there is no difference between these two. This for the programmer to write easily, but for compiler both are same.*
To remove Enter:
Update [table_name] set
[column_name]=Replace(REPLACE([column_name],CHAR(13),''),CHAR(10),'')
To remove Tab:
Update [table_name] set
[column_name]=REPLACE([column_name],CHAR(9),'')
To write for all versions of Office use a combination of the newer VBA7 and Win64 conditional Compiler Constants.
VBA7
determines if code is running in version 7 of the VB editor (VBA version shipped in Office 2010+).
Win64
determines which version (32-bit or 64-bit) of Office is running.
#If VBA7 Then
'Code is running VBA7 (2010 or later).
#If Win64 Then
'Code is running in 64-bit version of Microsoft Office.
#Else
'Code is running in 32-bit version of Microsoft Office.
#End If
#Else
'Code is running VBA6 (2007 or earlier).
#End If
See Microsoft Support Article for more details.
I am assuming that you know how to iterate over elements in some list:
for el in my_list:
# do something
Now sometimes not only you need to iterate over the elements, but also you need the index for each iteration. One way to do it is:
i = 0
for el in my_list:
# do somethings, and use value of "i" somehow
i += 1
However, a nicer way is to user the function "enumerate". What enumerate does is that it receives a list, and it returns a list-like object (an iterable that you can iterate over) but each element of this new list itself contains 2 elements: the index and the value from that original input list: So if you have
arr = ['a', 'b', 'c']
Then the command
enumerate(arr)
returns something like:
[(0,'a'), (1,'b'), (2,'c')]
Now If you iterate over a list (or an iterable) where each element itself has 2 sub-elements, you can capture both of those sub-elements in the for
loop like below:
for index, value in enumerate(arr):
print(index,value)
which would print out the sub-elements of the output of enumerate.
And in general you can basically "unpack" multiple items from list into multiple variables like below:
idx,value = (2,'c')
print(idx)
print(value)
which would print
2
c
This is the kind of assignment happening in each iteration of that loop with enumerate(arr)
as iterable.
You cannot put tr inside td. You can see the allowed content from MDN web docs documentation about td
. The relevant information is in the permitted content section.
Another way to achieve this is by using colspan
and rowspan
. Check this fiddle.
HTML:
<table width="100%">
<tr>
<td>Name 1</td>
<td>Name 2</td>
<td colspan="2">Name 3</td>
<td>Name 4</td>
</tr>
<tr>
<td rowspan="3">ITEM 1</td>
<td rowspan="3">ITEM 2</td>
<td>name1</td>
<td>price1</td>
<td rowspan="3">ITEM 4</td>
</tr>
<tr>
<td>name2</td>
<td>price2</td>
</tr>
<tr>
<td>name3</td>
<td>price3/td>
</tr>
</table>
And some CSS:
table {
border-collapse: collapse
}
td {
border: 1px solid #000000
}
s = 'hello'
ln = len(s)
i = 1
while True:
rev = s[ln-i]
print rev,
i = i + 1
if i == ln + 1 :
break
OUTPUT :
o l l e h
I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:
TypeError: 'int' object is not callable
My code for Python 3 is as follows:
# https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error
raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54
def intro():
print("Welcome! This program will convert measures for you.")
main()
def main():
print("Select operation.")
print("1.Miles to Kilometers")
print("2.Fahrenheit to Celsius")
print("3.Gallons to liters")
print("4.Pounds to kilograms")
print("5.Inches to centimeters")
choice = input("Enter your choice by number: ")
if choice == '1':
convertMK()
elif choice == '2':
converCF()
elif choice == '3':
convertGL()
elif choice == '4':
convertPK()
elif choice == '5':
convertPK()
else:
print("Error")
def convertMK():
input_M = float(input(("Miles: ")))
M_conv = (M) * input_M
print("Kilometers: {M_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def converCF():
input_F = float(input(("Fahrenheit: ")))
F_conv = (input_F - 32) * 5/9
print("Celcius: {F_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def convertGL():
input_G = float(input(("Gallons: ")))
G_conv = input_G * 3.6
print("Centimeters: {G_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertPK():
input_P = float(input(("Pounds: ")))
P_conv = input_P * 0.45
print("Centimeters: {P_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertIC():
input_cm = float(input(("Inches: ")))
inches_conv = input_cm * 2.54
print("Centimeters: {inches_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def end():
print("This program will close.")
exit()
intro()
I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.
def convertPK():
input_P = float(input(("Pounds: ")))
P_conv = input_P * 0.45
# Printing error in the line below
print("Centimeters: {P_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
I hope this helps.
Private Sub Click_Click()
Dim vaFiles As Variant
Dim i As Long
For j = 1 To 2
vaFiles = Application.GetOpenFilename _
(FileFilter:="Excel Filer (*.xlsx),*.xlsx", _
Title:="Open File(s)", MultiSelect:=True)
If Not IsArray(vaFiles) Then Exit Sub
With Application
.ScreenUpdating = False
For i = 1 To UBound(vaFiles)
Workbooks.Open vaFiles(i)
wrkbk_name = vaFiles(i)
Next i
.ScreenUpdating = True
End With
If j = 1 Then
work1 = Right(wrkbk_name, Len(wrkbk_name) - InStrRev(wrkbk_name, "\"))
Else: work2 = Right(wrkbk_name, Len(wrkbk_name) - InStrRev(wrkbk_name, "\"))
End If
Next j
'Filling the values of the group name
'check = Application.WorksheetFunction.Search(Name, work1)
check = InStr(UCase("Qoute Request"), work1)
If check = 1 Then
Application.Workbooks(work1).Activate
Else
Application.Workbooks(work2).Activate
End If
ActiveWorkbook.Sheets("GI Quote Request").Select
ActiveSheet.Range("B4:C12").Copy
Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Range("K3").Select
ActiveSheet.Paste
Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
Range("D3").Value = Range("L3").Value
Range("D7").Value = Range("L9").Value
Range("D11").Value = Range("L7").Value
For i = 4 To 5
If i = 5 Then
GoTo NextIteration
End If
If Left(ActiveSheet.Range("B" & i).Value, Len(ActiveSheet.Range("B" & i).Value) - 1) = Range("K" & i).Value Then
ActiveSheet.Range("D" & i).Value = Range("L" & i).Value
End If
NextIteration:
Next i
'eligibles part
Count = Range("D11").Value
For i = 27 To Count + 24
Range("C" & i).EntireRow.Offset(1, 0).Insert
Next i
check = Left(work1, InStrRev(work1, ".") - 1)
'check = InStr("Census", work1)
If check = "Census" Then
workbk = work1
Application.Workbooks(work1).Activate
Else
Application.Workbooks(work2).Activate
workbk = work2
End If
'DOB
ActiveWorkbook.Sheets("Sheet1").Select
ActiveSheet.Range("D2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
ActiveSheet.Range("C27").Select
ActiveSheet.Paste
'Gender
Application.Workbooks(workbk).Activate
ActiveWorkbook.Sheets("Sheet1").Select
ActiveSheet.Range("C2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
'Application.CutCopyMode = False
ActiveSheet.Range("k27").Select
ActiveSheet.Paste
For i = 27 To Count + 27
ActiveSheet.Range("E" & i).Value = Left(ActiveSheet.Range("k" & i).Value, 1)
Next i
'Salary
Application.Workbooks(workbk).Activate
ActiveWorkbook.Sheets("Sheet1").Select
ActiveSheet.Range("N2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
'Application.CutCopyMode = False
ActiveSheet.Range("F27").Select
ActiveSheet.Paste
ActiveSheet.Range("K3:L" & Count).Select
selction.ClearContents
End Sub
I think requests.head instead of requests.get will be more safe to call when handling url redirect,check the github issue here:
r = requests.head(url, allow_redirects=True)
print(r.url)
You can do:
$("#submittername").text("testing");
or
$("#submittername").html("testing <b>1 2 3</b>");
There is no any method getCurrentItem() in viewpager.i already checked the API
First thing, at the time the question was asked, uintptr_t
was not in C++. It's in C99, in <stdint.h>
, as an optional type. Many C++03 compilers do provide that file. It's also in C++11, in <cstdint>
, where again it is optional, and which refers to C99 for the definition.
In C99, it is defined as "an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer".
Take this to mean what it says. It doesn't say anything about size.
uintptr_t
might be the same size as a void*
. It might be larger. It could conceivably be smaller, although such a C++ implementation approaches perverse. For example on some hypothetical platform where void*
is 32 bits, but only 24 bits of virtual address space are used, you could have a 24-bit uintptr_t
which satisfies the requirement. I don't know why an implementation would do that, but the standard permits it.
Not to repeat an answer, but I think I can add a bit more.
Slickedit is an excellent IDE.
It supports large code-bases well without slowing down or spending all its time indexing. (This is a problem I had with eclipse's cdt). Slickedit's speed is probably the nicest thing about it, actually.
The code completion works well and there are a large amount of options for things like automatic formatting, beautification and refactoring.
It does have integrated debugging.
It has plug-in support and fairly active community creating them.
In theory, you should be able to integrate well with people doing the traditional makefile stuff, as it allows you to create a project directly from one, but that didn't work as smoothly as I would have liked when I tried it.
In addition to Linux, there are Mac and Windows versions of it, should you need them.
Hello guys Most of the codes you will find will return you server ip address not client ip address .however this code returns correct client ip address.Give it a try. For More info just check this
https://www.youtube.com/watch?v=Nkf37DsxYjI
for getting your local ip address using javascript you can use put this code inside your script tag
<script>
var RTCPeerConnection = /*window.RTCPeerConnection ||*/
window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
if (RTCPeerConnection) (function () {
var rtc = new RTCPeerConnection({ iceServers: [] });
if (1 || window.mozRTCPeerConnection) {
rtc.createDataChannel('', { reliable: false });
};
rtc.onicecandidate = function (evt) {
if (evt.candidate)
grepSDP("a=" + evt.candidate.candidate);
};
rtc.createOffer(function (offerDesc) {
grepSDP(offerDesc.sdp);
rtc.setLocalDescription(offerDesc);
}, function (e) { console.warn("offer failed", e); });
var addrs = Object.create(null);
addrs["0.0.0.0"] = false;
function updateDisplay(newAddr) {
if (newAddr in addrs) return;
else addrs[newAddr] = true;
var displayAddrs = Object.keys(addrs).filter(function
(k) { return addrs[k]; });
document.getElementById('list').textContent =
displayAddrs.join(" or perhaps ") || "n/a";
}
function grepSDP(sdp) {
var hosts = [];
sdp.split('\r\n').forEach(function (line) {
if (~line.indexOf("a=candidate")) {
var parts = line.split(' '),
addr = parts[4],
type = parts[7];
if (type === 'host') updateDisplay(addr);
} else if (~line.indexOf("c=")) {
var parts = line.split(' '),
addr = parts[2];
updateDisplay(addr);
}
});
}
})(); else
{
document.getElementById('list').innerHTML = "<code>ifconfig| grep inet | grep -v inet6 | cut -d\" \" -f2 | tail -n1</code>";
document.getElementById('list').nextSibling.textContent = "In Chrome and Firefox your IP should display automatically, by the power of WebRTCskull.";
}
</script>
<body>
<div id="list"></div>
</body>
and For getting your public ip address you can use put this code inside your script tag
function getIP(json) {
document.write("My public IP address is: ", json.ip);
}
<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
EG : COMPARE TO VILLAGE NAME
ALTER PROCEDURE POSMAST
(@COLUMN_NAME VARCHAR(50))
AS
SELECT * FROM TABLE_NAME
WHERE
village_name LIKE + @VILLAGE_NAME + '%';
You need to use Arrow function ()=>
ES6 feature to preserve this
context within setTimeout
.
// var that = this; // no need of this line
this.messageSuccess = true;
setTimeout(()=>{ //<<<---using ()=> syntax
this.messageSuccess = false;
}, 3000);
According Changes in the Connector/J API "The name of the class that implements java.sql.Driver in MySQL Connector/J has changed from com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver. The old class name has been deprecated."
This means that you just need to change the name of the driver:
Class.forName("com.mysql.jdbc.Driver");
to
Class.forName("com.mysql.cj.jdbc.Driver");
This is the real proxy redirection to the intended server.
server {
listen 80;
server_name localhost;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://xx.xxx.xxx.xxx/;
proxy_redirect off;
proxy_set_header Host $host;
}
}
Here's an easier way of doing this (source: here):
import matplotlib.pyplot as plt
from numpy.random import rand
fig, ax = plt.subplots()
for color in ['red', 'green', 'blue']:
n = 750
x, y = rand(2, n)
scale = 200.0 * rand(n)
ax.scatter(x, y, c=color, s=scale, label=color,
alpha=0.3, edgecolors='none')
ax.legend()
ax.grid(True)
plt.show()
And you'll get this:
Take a look at here for legend properties
If you need to handle newlines in diferent systems you can simply use the PHP predefined constant PHP_EOL (http://php.net/manual/en/reserved.constants.php) and simply use explode to avoid the overhead of the regular expression engine.
$lines = explode(PHP_EOL, $subject);
A brief example of how to switch between tabs in a browser (in case with one window):
// open the first tab
driver.get("https://www.google.com");
Thread.sleep(2000);
// open the second tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
driver.get("https://www.google.com");
Thread.sleep(2000);
// switch to the previous tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "" + Keys.SHIFT + "" + Keys.TAB);
Thread.sleep(2000);
I write Thread.sleep(2000)
just to have a timeout to see switching between the tabs.
You can use CTRL+TAB for switching to the next tab and CTRL+SHIFT+TAB for switching to the previous tab.
Beware! While it's true that "sort -u" and "sort|uniq" are equivalent, any additional options to sort can break the equivalence. Here's an example from the coreutils manual:
For example, 'sort -n -u' inspects only the value of the initial numeric string when checking for uniqueness, whereas 'sort -n | uniq' inspects the entire line.
Similarly, if you sort on key fields, the uniqueness test used by sort won't necessarily look at the entire line anymore. After being bitten by that bug in the past, these days I tend to use "sort|uniq" when writing Bash scripts. I'd rather have higher I/O overhead than run the risk that someone else in the shop won't know about that particular pitfall when they modify my code to add additional sort parameters.
The new default toArray
method in Collection
interface allows the elements of the collection to be transferred to a newly created array of the desired runtime type. It takes IntFunction<T[]> generator
as argument and can be used as:
String[] array = set.toArray(String[]::new);
There is already a similar method Collection.toArray(T[])
and this addition means we no longer be able to pass null
as argument because in that case reference to the method would be ambiguous. But it is still okay since both methods throw a NPE anyways.
In Java 8 we can use streams API:
String[] array = set.stream().toArray(String[]::new);
We can also make use of the overloaded version of toArray() which takes IntFunction<A[]> generator
as:
String[] array = set.stream().toArray(n -> new String[n]);
The purpose of the generator function here is to take an integer (size of desired array) and produce an array of desired size. I personally prefer the former approach using method reference than the later one using lambda expression.
Some great examples and libs presented in this thread, but they didn't quite have what I was looking for. My approach: angular-validity -- a promise based validation lib for asynchronous validation, with optional Bootstrap styling baked-in.
An angular-validity solution for the OP's use case might look something like this:
<input type="text" name="field4" ng-model="field4"
validity="eval"
validity-eval="!(field1 && field2 && field3 && !field4)"
validity-message-eval="This field is required">
Here's a Fiddle, if you want to take it for a spin. The lib is available on GitHub, has detailed documentation, and plenty of live demos.
Here is my implementation:
function daysBetween(one, another) {
return Math.round(Math.abs((+one) - (+another))/8.64e7);
}
+<date>
does the type coercion to the integer representation and has the same effect as <date>.getTime()
and 8.64e7
is the number of milliseconds in a day.
This should work:
User.Identity.Name
Identity
returns an IPrincipal
Here is the link to the Microsoft documentation.
Also, you can display current position by "drag" listener and write it to visible or hidden field. You may also need to store zoom. Here's copy&paste from working tool:
function map_init() {
var lt=48.451778;
var lg=31.646305;
var myLatlng = new google.maps.LatLng(lt,lg);
var mapOptions = {
center: new google.maps.LatLng(lt,lg),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'),mapOptions);
var marker = new google.maps.Marker({
position:myLatlng,
map:map,
draggable:true
});
google.maps.event.addListener(
marker,
'drag',
function() {
document.getElementById('lat1').innerHTML = marker.position.lat().toFixed(6);
document.getElementById('lng1').innerHTML = marker.position.lng().toFixed(6);
document.getElementById('zoom').innerHTML = mapObject.getZoom();
// Dynamically show it somewhere if needed
$(".x").text(marker.position.lat().toFixed(6));
$(".y").text(marker.position.lng().toFixed(6));
$(".z").text(map.getZoom());
}
);
}
I think what you want is a different content mode
. Try using UIViewContentModeScaleToFill
. This will scale the content to fit the size of ur UIImageView by changing the aspect ratio of the content if necessary.
Have a look to the content mode
section on the official doc to get a better idea of the different content mode available (it is illustrated with images).
You want to use single quotes:
if(c=='\0')
Double quotes (") are for strings, which are sequences of characters. Single quotes (') are for individual characters.
However, the end-of-line is represented by the newline character, which is '\n'.
Note that in both cases, the backslash is not part of the character, but just a way you represent special characters. Using backslashes you can represent various unprintable characters and also characters which would otherwise confuse the compiler.
Just to add to the correct answer above, in Vue.JS v1.0 you can write
<a v-on:click="doSomething">
So in this example it would be
v-on:change="foo"
You need to change permissions on the folder bootstrap/css. Your super user may be able to access it but it doesn't mean apache or nginx have access to it, that's why you still need to change the permissions.
Tip: I usually make the apache/nginx's user group owner of that kind of folders and give 775 permission to it.
Better use int.TryParse
to avoid exceptions;
var numbers = sNumbers
.Split(',')
.Where(x => int.TryParse(x, out _))
.Select(int.Parse)
.ToList();
I meant in the template()
call..
You just need to pass the results as an object. So instead of calling
var html = template(data);
do
var html = template({apidata: data});
and use {{#each apidata}}
in your template code
demo at http://jsfiddle.net/KPCh4/4/
(removed some leftover if
code that crashed)
IMHO
the pervasive, implicit localization in Java is its single largest design flaw. It may be intended for user interfaces, but frankly, who really uses Java for user interfaces today except for some IDEs where you can basically ignore localization because programmers aren't exactly the target audience for it. You can fix it (especially on Linux servers) by:
LC_ALL=C TZ=UTC
To the Java Community Process members I recommend:
UTF-8/UTC
as the FIXED default instead because that's simply the default today. There is no reason to do something else, except if you want to produce threads like this.I mean, come on, aren't global static variables an anti-OO pattern? Nothing else is those pervasive defaults given by some rudimentary environment variables.......
Maybe it is too simplistic, but I used this solution and I find it very useful when I have a primary key that I can use to compare data sets. Hope it can help.
a1 <- data.frame(a = 1:5, b = letters[1:5])
a2 <- data.frame(a = 1:3, b = letters[1:3])
different.names <- (!a1$a %in% a2$a)
not.in.a2 <- a1[different.names,]
Some receivers expect EOL sequence, which is typically two characters \r\n
, so try in your code replace the line
unsigned char cmd[] = {'I', 'N', 'I', 'T', ' ', '\r', '\0'};
with
unsigned char cmd[] = "INIT\r\n";
BTW, the above way is probably more efficient. There is no need to quote every character.
You could try using float:left;
or display:inline-block;
.
Both of these will change the element's behaviour from defaulting to 100% width to defaulting to the natural width of its contents.
However, note that they'll also both have an impact on the layout of the surrounding elements as well. I would suggest that inline-block
will have less of an impact though, so probably best to try that first.
//: Playground - noun: a place where people can play
import UIKit
class A {
class func a() {
print("yeah")
}
func getInnerValue() {
self.dynamicType.a()
}
}
class B: A {
override class func a() {
print("yeah yeah")
}
}
B.a() // yeah yeah
A.a() // yeah
B().getInnerValue() // yeah yeah
A().getInnerValue() // yeah
Yes it's a little tricky in TypeScript but you can do the below example like this
let decodeData = JSON.parse(`${jsonResponse}`);
_x000D_
In order to avoid such error you could use CASE
+ ISNUMERIC
to handle scenarios when you cannot convert to int.
Change
CONVERT(INT, CONVERT(VARCHAR(12), a.value))
To
CONVERT(INT,
CASE
WHEN IsNumeric(CONVERT(VARCHAR(12), a.value)) = 1 THEN CONVERT(VARCHAR(12),a.value)
ELSE 0 END)
Basically this is saying if you cannot convert me to int assign value of 0 (in my example)
Alternatively you can look at this article about creating a custom function that will check if a.value
is number: http://www.tek-tips.com/faqs.cfm?fid=6423
Go to inspect element and check if .justify-content-center is listed as a class name under 'Styles' tab. If not, probably you are using bootstrap v3 in which justify-content-center is not defined.
If so, please update bootstrap, worked for me.
The lookup time is slow because when you use mmap
to does not load content of array to memory when you invoke load
method. Data is lazy loaded when particular data is needed.
And this happens in lookup in your case. But second lookup won`t be so slow.
This is nice feature of mmap
when you have a big array you do not have to load whole data into memory.
To solve your can use joblib you can dump any object you want using joblib.dump
even two or more numpy arrays
, see the example
firstArray = np.arange(100)
secondArray = np.arange(50)
# I will put two arrays in dictionary and save to one file
my_dict = {'first' : firstArray, 'second' : secondArray}
joblib.dump(my_dict, 'file_name.dat')
Ctrl + / works for me in Chrome browser in MS Windows. On a Mac, use Cmd + / (thanks Anton K).
Please note, if /
did not work out of the box, try pressing the /
key on the Numpad. Credit: @DreamFlasher in comments to this question.
If you want this to work in IE 8 and below, use
<!--[if lte IE 8]>
lte
meaning "Less than or equal".
For more on conditional comments, see e.g. the quirksmode.org page.
From the context you describe, I suspect that what you're actually trying to make is something called an 'SEO slug'. The best general known practice for those is:
So, as an example, an article titled "The Usage of !@%$* to Represent Swearing In Comics" would get a slug of "usage-represent-swearing-comics".
Homework question? Well you can modify your original 'right triangle' code to generate an inverted 'right triangle' with spaces So that'll be like
for(i=0; i<6; i++)
{
for(j=6; j>=(6-i); j--)
{
print(" ");
}
for(x=0; x<=((2*i)+1); x++)
{
print("*");
}
print("\n");
}
/*what is wrong with the following?*/
DELIMITER $$
CREATE PROCEDURE GetStatusDescr(
in pStatus char(1),
out pStatusDescr char(10))
BEGIN
IF (pStatus == 'Y THEN
SET pStatusDescr = 'Active';
ELSEIF (pStatus == 'N') THEN
SET pStatusDescr = 'In-Active';
ELSE
SET pStatusDescr = 'Unknown';
END IF;
END$$
This post itself is not a direct answer to the question. What it is instead is a data-driven extensible benchmark that can be used to compare many of the answers (and variations of utilizing new features added in later, more modern, versions of Python) that have been posted to this question — and should therefore be helpful in determining which has the best performance.
In a few cases I've modified the code in the referenced answer to make it compatible with the benchmark framework.
First, here are the results for what currently are the latest versions of Python 2 & 3:
Fastest to slowest execution speeds with 32-bit Python 2.7.16
numpy version 1.16.5
Test file size: 1,024 KiB
100 executions, best of 3 repetitions
1 Tcll (array.array) : 3.8943 secs, rel speed 1.00x, 0.00% slower (262.95 KiB/sec)
2 Vinay Sajip (read all into memory) : 4.1164 secs, rel speed 1.06x, 5.71% slower (248.76 KiB/sec)
3 codeape + iter + partial : 4.1616 secs, rel speed 1.07x, 6.87% slower (246.06 KiB/sec)
4 codeape : 4.1889 secs, rel speed 1.08x, 7.57% slower (244.46 KiB/sec)
5 Vinay Sajip (chunked) : 4.1977 secs, rel speed 1.08x, 7.79% slower (243.94 KiB/sec)
6 Aaron Hall (Py 2 version) : 4.2417 secs, rel speed 1.09x, 8.92% slower (241.41 KiB/sec)
7 gerrit (struct) : 4.2561 secs, rel speed 1.09x, 9.29% slower (240.59 KiB/sec)
8 Rick M. (numpy) : 8.1398 secs, rel speed 2.09x, 109.02% slower (125.80 KiB/sec)
9 Skurmedel : 31.3264 secs, rel speed 8.04x, 704.42% slower ( 32.69 KiB/sec)
Benchmark runtime (min:sec) - 03:26
Fastest to slowest execution speeds with 32-bit Python 3.8.0
numpy version 1.17.4
Test file size: 1,024 KiB
100 executions, best of 3 repetitions
1 Vinay Sajip + "yield from" + "walrus operator" : 3.5235 secs, rel speed 1.00x, 0.00% slower (290.62 KiB/sec)
2 Aaron Hall + "yield from" : 3.5284 secs, rel speed 1.00x, 0.14% slower (290.22 KiB/sec)
3 codeape + iter + partial + "yield from" : 3.5303 secs, rel speed 1.00x, 0.19% slower (290.06 KiB/sec)
4 Vinay Sajip + "yield from" : 3.5312 secs, rel speed 1.00x, 0.22% slower (289.99 KiB/sec)
5 codeape + "yield from" + "walrus operator" : 3.5370 secs, rel speed 1.00x, 0.38% slower (289.51 KiB/sec)
6 codeape + "yield from" : 3.5390 secs, rel speed 1.00x, 0.44% slower (289.35 KiB/sec)
7 jfs (mmap) : 4.0612 secs, rel speed 1.15x, 15.26% slower (252.14 KiB/sec)
8 Vinay Sajip (read all into memory) : 4.5948 secs, rel speed 1.30x, 30.40% slower (222.86 KiB/sec)
9 codeape + iter + partial : 4.5994 secs, rel speed 1.31x, 30.54% slower (222.64 KiB/sec)
10 codeape : 4.5995 secs, rel speed 1.31x, 30.54% slower (222.63 KiB/sec)
11 Vinay Sajip (chunked) : 4.6110 secs, rel speed 1.31x, 30.87% slower (222.08 KiB/sec)
12 Aaron Hall (Py 2 version) : 4.6292 secs, rel speed 1.31x, 31.38% slower (221.20 KiB/sec)
13 Tcll (array.array) : 4.8627 secs, rel speed 1.38x, 38.01% slower (210.58 KiB/sec)
14 gerrit (struct) : 5.0816 secs, rel speed 1.44x, 44.22% slower (201.51 KiB/sec)
15 Rick M. (numpy) + "yield from" : 11.8084 secs, rel speed 3.35x, 235.13% slower ( 86.72 KiB/sec)
16 Skurmedel : 11.8806 secs, rel speed 3.37x, 237.18% slower ( 86.19 KiB/sec)
17 Rick M. (numpy) : 13.3860 secs, rel speed 3.80x, 279.91% slower ( 76.50 KiB/sec)
Benchmark runtime (min:sec) - 04:47
I also ran it with a much larger 10 MiB test file (which took nearly an hour to run) and got performance results which were comparable to those shown above.
Here's the code used to do the benchmarking:
from __future__ import print_function
import array
import atexit
from collections import deque, namedtuple
import io
from mmap import ACCESS_READ, mmap
import numpy as np
from operator import attrgetter
import os
import random
import struct
import sys
import tempfile
from textwrap import dedent
import time
import timeit
import traceback
try:
xrange
except NameError: # Python 3
xrange = range
class KiB(int):
""" KibiBytes - multiples of the byte units for quantities of information. """
def __new__(self, value=0):
return 1024*value
BIG_TEST_FILE = 1 # MiBs or 0 for a small file.
SML_TEST_FILE = KiB(64)
EXECUTIONS = 100 # Number of times each "algorithm" is executed per timing run.
TIMINGS = 3 # Number of timing runs.
CHUNK_SIZE = KiB(8)
if BIG_TEST_FILE:
FILE_SIZE = KiB(1024) * BIG_TEST_FILE
else:
FILE_SIZE = SML_TEST_FILE # For quicker testing.
# Common setup for all algorithms -- prefixed to each algorithm's setup.
COMMON_SETUP = dedent("""
# Make accessible in algorithms.
from __main__ import array, deque, get_buffer_size, mmap, np, struct
from __main__ import ACCESS_READ, CHUNK_SIZE, FILE_SIZE, TEMP_FILENAME
from functools import partial
try:
xrange
except NameError: # Python 3
xrange = range
""")
def get_buffer_size(path):
""" Determine optimal buffer size for reading files. """
st = os.stat(path)
try:
bufsize = st.st_blksize # Available on some Unix systems (like Linux)
except AttributeError:
bufsize = io.DEFAULT_BUFFER_SIZE
return bufsize
# Utility primarily for use when embedding additional algorithms into benchmark.
VERIFY_NUM_READ = """
# Verify generator reads correct number of bytes (assumes values are correct).
bytes_read = sum(1 for _ in file_byte_iterator(TEMP_FILENAME))
assert bytes_read == FILE_SIZE, \
'Wrong number of bytes generated: got {:,} instead of {:,}'.format(
bytes_read, FILE_SIZE)
"""
TIMING = namedtuple('TIMING', 'label, exec_time')
class Algorithm(namedtuple('CodeFragments', 'setup, test')):
# Default timeit "stmt" code fragment.
_TEST = """
#for b in file_byte_iterator(TEMP_FILENAME): # Loop over every byte.
# pass # Do stuff with byte...
deque(file_byte_iterator(TEMP_FILENAME), maxlen=0) # Data sink.
"""
# Must overload __new__ because (named)tuples are immutable.
def __new__(cls, setup, test=None):
""" Dedent (unindent) code fragment string arguments.
Args:
`setup` -- Code fragment that defines things used by `test` code.
In this case it should define a generator function named
`file_byte_iterator()` that will be passed that name of a test file
of binary data. This code is not timed.
`test` -- Code fragment that uses things defined in `setup` code.
Defaults to _TEST. This is the code that's timed.
"""
test = cls._TEST if test is None else test # Use default unless one is provided.
# Uncomment to replace all performance tests with one that verifies the correct
# number of bytes values are being generated by the file_byte_iterator function.
#test = VERIFY_NUM_READ
return tuple.__new__(cls, (dedent(setup), dedent(test)))
algorithms = {
'Aaron Hall (Py 2 version)': Algorithm("""
def file_byte_iterator(path):
with open(path, "rb") as file:
callable = partial(file.read, 1024)
sentinel = bytes() # or b''
for chunk in iter(callable, sentinel):
for byte in chunk:
yield byte
"""),
"codeape": Algorithm("""
def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
with open(filename, "rb") as f:
while True:
chunk = f.read(chunksize)
if chunk:
for b in chunk:
yield b
else:
break
"""),
"codeape + iter + partial": Algorithm("""
def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
with open(filename, "rb") as f:
for chunk in iter(partial(f.read, chunksize), b''):
for b in chunk:
yield b
"""),
"gerrit (struct)": Algorithm("""
def file_byte_iterator(filename):
with open(filename, "rb") as f:
fmt = '{}B'.format(FILE_SIZE) # Reads entire file at once.
for b in struct.unpack(fmt, f.read()):
yield b
"""),
'Rick M. (numpy)': Algorithm("""
def file_byte_iterator(filename):
for byte in np.fromfile(filename, 'u1'):
yield byte
"""),
"Skurmedel": Algorithm("""
def file_byte_iterator(filename):
with open(filename, "rb") as f:
byte = f.read(1)
while byte:
yield byte
byte = f.read(1)
"""),
"Tcll (array.array)": Algorithm("""
def file_byte_iterator(filename):
with open(filename, "rb") as f:
arr = array.array('B')
arr.fromfile(f, FILE_SIZE) # Reads entire file at once.
for b in arr:
yield b
"""),
"Vinay Sajip (read all into memory)": Algorithm("""
def file_byte_iterator(filename):
with open(filename, "rb") as f:
bytes_read = f.read() # Reads entire file at once.
for b in bytes_read:
yield b
"""),
"Vinay Sajip (chunked)": Algorithm("""
def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
with open(filename, "rb") as f:
chunk = f.read(chunksize)
while chunk:
for b in chunk:
yield b
chunk = f.read(chunksize)
"""),
} # End algorithms
#
# Versions of algorithms that will only work in certain releases (or better) of Python.
#
if sys.version_info >= (3, 3):
algorithms.update({
'codeape + iter + partial + "yield from"': Algorithm("""
def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
with open(filename, "rb") as f:
for chunk in iter(partial(f.read, chunksize), b''):
yield from chunk
"""),
'codeape + "yield from"': Algorithm("""
def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
with open(filename, "rb") as f:
while True:
chunk = f.read(chunksize)
if chunk:
yield from chunk
else:
break
"""),
"jfs (mmap)": Algorithm("""
def file_byte_iterator(filename):
with open(filename, "rb") as f, \
mmap(f.fileno(), 0, access=ACCESS_READ) as s:
yield from s
"""),
'Rick M. (numpy) + "yield from"': Algorithm("""
def file_byte_iterator(filename):
# data = np.fromfile(filename, 'u1')
yield from np.fromfile(filename, 'u1')
"""),
'Vinay Sajip + "yield from"': Algorithm("""
def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
with open(filename, "rb") as f:
chunk = f.read(chunksize)
while chunk:
yield from chunk # Added in Py 3.3
chunk = f.read(chunksize)
"""),
}) # End Python 3.3 update.
if sys.version_info >= (3, 5):
algorithms.update({
'Aaron Hall + "yield from"': Algorithm("""
from pathlib import Path
def file_byte_iterator(path):
''' Given a path, return an iterator over the file
that lazily loads the file.
'''
path = Path(path)
bufsize = get_buffer_size(path)
with path.open('rb') as file:
reader = partial(file.read1, bufsize)
for chunk in iter(reader, bytes()):
yield from chunk
"""),
}) # End Python 3.5 update.
if sys.version_info >= (3, 8, 0):
algorithms.update({
'Vinay Sajip + "yield from" + "walrus operator"': Algorithm("""
def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
with open(filename, "rb") as f:
while chunk := f.read(chunksize):
yield from chunk # Added in Py 3.3
"""),
'codeape + "yield from" + "walrus operator"': Algorithm("""
def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
with open(filename, "rb") as f:
while chunk := f.read(chunksize):
yield from chunk
"""),
}) # End Python 3.8.0 update.update.
#### Main ####
def main():
global TEMP_FILENAME
def cleanup():
""" Clean up after testing is completed. """
try:
os.remove(TEMP_FILENAME) # Delete the temporary file.
except Exception:
pass
atexit.register(cleanup)
# Create a named temporary binary file of pseudo-random bytes for testing.
fd, TEMP_FILENAME = tempfile.mkstemp('.bin')
with os.fdopen(fd, 'wb') as file:
os.write(fd, bytearray(random.randrange(256) for _ in range(FILE_SIZE)))
# Execute and time each algorithm, gather results.
start_time = time.time() # To determine how long testing itself takes.
timings = []
for label in algorithms:
try:
timing = TIMING(label,
min(timeit.repeat(algorithms[label].test,
setup=COMMON_SETUP + algorithms[label].setup,
repeat=TIMINGS, number=EXECUTIONS)))
except Exception as exc:
print('{} occurred timing the algorithm: "{}"\n {}'.format(
type(exc).__name__, label, exc))
traceback.print_exc(file=sys.stdout) # Redirect to stdout.
sys.exit(1)
timings.append(timing)
# Report results.
print('Fastest to slowest execution speeds with {}-bit Python {}.{}.{}'.format(
64 if sys.maxsize > 2**32 else 32, *sys.version_info[:3]))
print(' numpy version {}'.format(np.version.full_version))
print(' Test file size: {:,} KiB'.format(FILE_SIZE // KiB(1)))
print(' {:,d} executions, best of {:d} repetitions'.format(EXECUTIONS, TIMINGS))
print()
longest = max(len(timing.label) for timing in timings) # Len of longest identifier.
ranked = sorted(timings, key=attrgetter('exec_time')) # Sort so fastest is first.
fastest = ranked[0].exec_time
for rank, timing in enumerate(ranked, 1):
print('{:<2d} {:>{width}} : {:8.4f} secs, rel speed {:6.2f}x, {:6.2f}% slower '
'({:6.2f} KiB/sec)'.format(
rank,
timing.label, timing.exec_time, round(timing.exec_time/fastest, 2),
round((timing.exec_time/fastest - 1) * 100, 2),
(FILE_SIZE/timing.exec_time) / KiB(1), # per sec.
width=longest))
print()
mins, secs = divmod(time.time()-start_time, 60)
print('Benchmark runtime (min:sec) - {:02d}:{:02d}'.format(int(mins),
int(round(secs))))
main()
with cursor for loop (user = 'TRANEE', table = 'D')
declare
constr all_constraints.constraint_name%TYPE;
begin
for constr in
(select constraint_name from all_constraints
where table_name = 'D'
and owner = 'TRANEE')
loop
execute immediate 'alter table D disable constraint '||constr.constraint_name;
end loop;
end;
/
(If you change disable to enable, you can make all constraints enable)
ANSWER:
int number_of_elements = sizeof(array)/sizeof(array[0])
EXPLANATION:
Since the compiler sets a specific size chunk of memory aside for each type of data, and an array is simply a group of those, you simply divide the size of the array by the size of the data type. If I have an array of 30 strings, my system sets aside 24 bytes for each element(string) of the array. At 30 elements, that's a total of 720 bytes. 720/24 == 30 elements. The small, tight algorithm for that is:
int number_of_elements = sizeof(array)/sizeof(array[0])
which equates to
number_of_elements = 720/24
Note that you don't need to know what data type the array is, even if it's a custom data type.
In view file (HTML or EJS)
<div ng-repeat="item in vm.itemList | filter: myFilter > </div>
and In Controller
$scope.myFilter = function(item) {
return (item.propertyA === 'value' || item.propertyA === 'value');
}
Either Cybernate or OMG Ponies solution will work. The fundamental problem is that the DATE_FORMAT()
function returns a string, not a date. When you wrote
(Select Date_Format(orders.date_purchased,'%m/%d/%Y')) As Date
I think you were essentially asking MySQL to try to format the values in date_purchased
according to that format string, and instead of calling that column date_purchased
, call it "Date". But that column would no longer contain a date, it would contain a string. (Because Date_Format()
returns a string, not a date.)
I don't think that's what you wanted to do, but that's what you were doing.
Don't confuse how a value looks with what the value is.
simple
add(new JScrollPane(textArea), BorderLayout.CENTER);
You're remarkably close.
Here's the code you wrote in the question:
questionText.replace(/[0-9]/g, '');
The code you've written does indeed look at the questionText variable, and produce output which is the original string, but with the digits replaced with empty string.
However, it doesn't assign it automatically back to the original variable. You need to specify what to assign it to:
questionText = questionText.replace(/[0-9]/g, '');
Collection initializers are only available in VB.NET 2010, released 2010-04-12:
Dim theVar = New List(Of String) From { "one", "two", "three" }
One more directive
html
<btn-file-selector/>
code
.directive('btnFileSelector',[function(){
return {
restrict: 'AE',
template: '<div></div>',
link: function(s,e,a){
var el = angular.element(e);
var button = angular.element('<button type="button" class="btn btn-default btn-upload">Add File</button>');
var fileForm = angular.element('<input type="file" style="display:none;"/>');
fileForm.on('change', function(){
// Actions after the file is selected
console.log( fileForm[0].files[0].name );
});
button.bind('click',function(){
fileForm.click();
});
el.append(fileForm);
el.append(button);
}
}
}]);
if you are getting id from url try
$id = (isset($_GET['id']) ? $_GET['id'] : '');
if getting from form you need to use POST
method cause your form has method="post"
$id = (isset($_POST['id']) ? $_POST['id'] : '');
For php notices use isset()
or empty()
to check values exist or not or initialize variable first with blank or a value
$id= '';
Addition to the answer of Brett DeWoody: (which is updated now)
var dataValue = obj.srcElement.attributes.data.nodeValue;
Works fine in IE(9+) and Chrome, but Firefox does not know the srcElement property. I found:
var dataValue = obj.currentTarget.attributes.data.nodeValue;
Works in IE, Chrome and FF, I did not test Safari.
For best useful I create this function:
func dateFormatting() -> String {
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE dd MMMM yyyy - HH:mm:ss"//"EE" to get short style
let mydt = dateFormatter.string(from: date).capitalized
return "\(mydt)"
}
You simply call it wherever you want like this:
print("Date = \(self.dateFormatting())")
this is the Output:
Date = Monday 15 October 2018 - 17:26:29
if want only the time simply change :
dateFormatter.dateFormat = "HH:mm:ss"
and this is the output:
Date = 17:27:30
and that's it...
You need to add two new file one is index.html, copy and paste the below code and other is imageup.php which will upload your image
<form action="imageup.php" method="post" enctype="multipart/form-data">
<input type="file" name="banner" >
<input type="submit" value="submit">
</form>
imageup.php
<?php
$banner=$_FILES['banner']['name'];
$expbanner=explode('.',$banner);
$bannerexptype=$expbanner[1];
date_default_timezone_set('Australia/Melbourne');
$date = date('m/d/Yh:i:sa', time());
$rand=rand(10000,99999);
$encname=$date.$rand;
$bannername=md5($encname).'.'.$bannerexptype;
$bannerpath="uploads/banners/".$bannername;
move_uploaded_file($_FILES["banner"]["tmp_name"],$bannerpath);
?>
The above code will upload your image with encrypted name
I was getting this error. I'm using python 3 in a virtual environment found this in my apache logs
[Fri Dec 21 08:01:43.471561 2018] [mpm_prefork:notice] [pid 21786] AH00163: Apache/2.4.6 (Red Hat Enterprise Linux) mod_wsgi/3.4 Python/2.7.5 configured -- resuming normal operations
I had installed wsgi using yum -y install mod_wsgi
. This had installed mod_wsgi compiled for python 2. So I uninstalled it
yum remove mod_wsgi
and installed mod_wsgi compiled for python 3 using
yum install python35u-mod_wsgi
It worked after that
/Images/myImage.png
this has to be in root of your domain/subdomain
http://website.to/Images/myImage.png
and it will work
However, I think it would work like this, too
style.css:
body{
background: url(../images/yourimage.png);
}
Also, you can use this if you don't want to use the System.Web
assembly:
var encoded = System.Security.SecurityElement.Escape(unencoded)
Per this article, the difference between System.Security.SecurityElement.Escape()
and System.Web.HttpUtility.HtmlEncode()
is that the former also encodes apostrophe (')
characters.
Most UNIX-like operating systems have a basename
executable for a very similar purpose (and dirname
for the path):
pax> a=/tmp/file.txt
pax> b=$(basename $a)
pax> echo $b
file.txt
That unfortunately just gives you the file name, including the extension, so you'd need to find a way to strip that off as well.
So, given you have to do that anyway, you may as well find a method that can strip off the path and the extension.
One way to do that (and this is a bash
-only solution, needing no other executables):
pax> a=/tmp/xx/file.tar.gz
pax> xpath=${a%/*}
pax> xbase=${a##*/}
pax> xfext=${xbase##*.}
pax> xpref=${xbase%.*}
pax> echo;echo path=${xpath};echo pref=${xpref};echo ext=${xfext}
path=/tmp/xx
pref=file.tar
ext=gz
That little snippet sets xpath
(the file path), xpref
(the file prefix, what you were specifically asking for) and xfext
(the file extension).
I was with the same problem except with a slight difference, the version of PHPMailer 6.0, by the good friend avs099 I know that the new version of PHPMailer since February 2018 does not support the autoload, and had a serious problem to instantiate the libraries with the namespace in MVC, I leave the code for those who need it.
//Controller
protected function getLibraryWNS($libreria) {
$rutaLibreria = ROOT . 'libs' . DS . $libreria . '.php';
if(is_readable($rutaLibreria)){
require_once $rutaLibreria;
echo $rutaLibreria . '<br/>';
}
else{
throw new Exception('Error de libreria');
}
}
//loginController
public function enviarEmail($email, $nombre, $asunto, $cuerpo){
//Import the PHPMailer class into the global namespace
$this->getLibraryWNS('PHPMailer');
$this->getLibraryWNS('SMTP');
//Create a new PHPMailer instance
$mail = new \PHPMailer\PHPMailer\PHPMailer();
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// $mail->SMTPDebug = 0; // 0 = off (for production use), 1 = client messages, 2 = client and server messages Godaddy POR CONFIRMAR
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
//Whether to use SMTP authentication
$mail->SMTPAuth = true; // authentication enabled
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'ssl'; //Seguridad Correo Gmail
//Set the hostname of the mail server
$mail->Host = "smtp.gmail.com"; //Host Correo Gmail
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 465; //587;
//Verifica si el servidor acepta envios en HTML
$mail->IsHTML(true);
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = '[email protected]';
//Password to use for SMTP authentication
$mail->Password = 'tucontraseña';
//Set who the message is to be sent from
$mail->setFrom('[email protected]','Creador de Páginas Web');
$mail->Subject = $asunto;
$mail->Body = $cuerpo;
//Set who the message is to be sent to
$mail->addAddress($email, $nombre);
//Send the message, check for errors
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
return false;
} else {
echo "Message has been sent";
return true;
}
>>> A = [6, 7, 8, 9, 10, 11, 12]
>>> subset_of_A = [6, 9, 12];
>>> set(A) - set(subset_of_A)
set([8, 10, 11, 7])
>>>
There is no such syntax in SQL Server, though CREATE TABLE AS ... SELECT
does exist in PDW. In SQL Server you can use this query to create an empty table:
SELECT * INTO schema.newtable FROM schema.oldtable WHERE 1 = 0;
(If you want to make a copy of the table including all of the data, then leave out the WHERE
clause.)
Note that this creates the same column structure (including an IDENTITY column if one exists) but it does not copy any indexes, constraints, triggers, etc.
If this is an 8-bytes numeric value, you can try:
BigInteger n = new BigInteger(byteArray);
If this is an UTF-8 character buffer, then you can try:
BigInteger n = new BigInteger(new String(byteArray, "UTF-8"));
This is one of the reasons I try to avoid using MS Server... but anyway. Sometimes you just don't have an option (yei! and I have to use an outdated version!!).
My suggestion is to create a virtual table:
From:
SELECT * FROM table
To:
CREATE VIEW v_table AS
SELECT ROW_NUMBER() OVER (ORDER BY table_key) AS row,* FROM table
Then just query:
SELECT * FROM v_table WHERE row BETWEEN 10 AND 20
If fields are added, or removed, "row" is updated automatically.
The main problem with this option is that ORDER BY is fixed. So if you want a different order, you would have to create another view.
UPDATE
There is another problem with this approach: if you try to filter your data, it won't work as expected. For example, if you do:
SELECT * FROM v_table WHERE field = 'test' AND row BETWEEN 10 AND 20
WHERE becomes limited to those data which are in the rows between 10 and 20 (instead of searching the whole dataset and limiting the output).
This was added to the upgrade documentation on Dec 29, 2015, so if you upgraded before then you probably missed it.
When fetching any attribute from the model it checks if that column should be cast as an integer, string, etc.
By default, for auto-incrementing tables, the ID is assumed to be an integer in this method:
https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L2790
So the solution is:
class UserVerification extends Model
{
protected $primaryKey = 'your_key_name'; // or null
public $incrementing = false;
// In Laravel 6.0+ make sure to also set $keyType
protected $keyType = 'string';
}
Download the developer edition. There you can choose Express as license when installing.
purrr::flatten_*()
is also a good option. the flatten_*
functions add thin sanity checks and ensure type safety.
myList <- list('A'=1, 'B'=2, 'C'=3)
purrr::flatten_dbl(myList)
## [1] 1 2 3
Enter this in the custom number format field:
[>=1000]#,##0,"K€";0"€"
What that means is that if the number is greater than 1,000, display at least one digit (indicated by the zero), but no digits after the thousands place, indicated by nothing coming after the comma. Then you follow the whole thing with the string "K".
Edited to add comma and euro.
In the specific case of Wicket: This is the very reason why I asked the Wicket devs to add support for an explicit two phase component initialization process in the framework's lifecycle of constructing a component i.e.
There was quite an active debate about whether it was necessary or not (it fully is necessary IMHO) as this link demonstrates http://apache-wicket.1842946.n4.nabble.com/VOTE-WICKET-3218-Component-onInitialize-is-broken-for-Pages-td3341090i20.html)
The good news is that the excellent devs at Wicket did end up introducing two phase initialization (to make the most aweseome Java UI framework even more awesome!) so with Wicket you can do all your post construction initialization in the onInitialize method that is called by the framework automatically if you override it - at this point in the lifecycle of your component its constructor has completed its work so virtual methods work as expected.
Opaque responses can't be accessed by JavaScript, but you can still cache them with the Cache API and respond with them in the fetch
event handler in a service worker. So they're useful for making your app offline, also for resources that you can't control (e.g. resources on a CDN that doesn't set the CORS headers).
Contains is used in Linq ,Just like Like is used in SQL .
string _search="/12/";
. . .
.Where(s => s.Hierarchy.Contains(_search))
You can write your SQL script in Linq as Following :
var result= Organizations.Join(OrganizationsHierarchy.Where(s=>s.Hierarchy.Contains("/12/")),s=>s.Id,s=>s.OrganizationsId,(org,orgH)=>new {org,orgH});
Change <?php echo $proxy ?>
to ' . $proxy . '
.
You use <?php
when you're outputting HTML by leaving PHP mode with ?>
. When you using echo
, you have to use concatenation, or wrap your string in double quotes and use interpolation.
Only <
and &
are required to be escaped if they are to be treated character data and not markup:
Here's how you could use different methods to do selective column slicing, including selective label based, index based and the selective ranges based column slicing.
In [37]: import pandas as pd
In [38]: import numpy as np
In [43]: df = pd.DataFrame(np.random.rand(4,7), columns = list('abcdefg'))
In [44]: df
Out[44]:
a b c d e f g
0 0.409038 0.745497 0.890767 0.945890 0.014655 0.458070 0.786633
1 0.570642 0.181552 0.794599 0.036340 0.907011 0.655237 0.735268
2 0.568440 0.501638 0.186635 0.441445 0.703312 0.187447 0.604305
3 0.679125 0.642817 0.697628 0.391686 0.698381 0.936899 0.101806
In [45]: df.loc[:, ["a", "b", "c"]] ## label based selective column slicing
Out[45]:
a b c
0 0.409038 0.745497 0.890767
1 0.570642 0.181552 0.794599
2 0.568440 0.501638 0.186635
3 0.679125 0.642817 0.697628
In [46]: df.loc[:, "a":"c"] ## label based column ranges slicing
Out[46]:
a b c
0 0.409038 0.745497 0.890767
1 0.570642 0.181552 0.794599
2 0.568440 0.501638 0.186635
3 0.679125 0.642817 0.697628
In [47]: df.iloc[:, 0:3] ## index based column ranges slicing
Out[47]:
a b c
0 0.409038 0.745497 0.890767
1 0.570642 0.181552 0.794599
2 0.568440 0.501638 0.186635
3 0.679125 0.642817 0.697628
### with 2 different column ranges, index based slicing:
In [49]: df[df.columns[0:1].tolist() + df.columns[1:3].tolist()]
Out[49]:
a b c
0 0.409038 0.745497 0.890767
1 0.570642 0.181552 0.794599
2 0.568440 0.501638 0.186635
3 0.679125 0.642817 0.697628
I suggest not using an array unless you have multiple objects to consider. There isn't anything wrong this statement:
var myMappings = {
"Name": 0.1,
"Phone": 0.1,
"Address": 0.5,
"Zip": 0.1,
"Comments": 0.2
};
for (var col in myMappings) {
alert((myMappings[col] * 100) + "%");
}
Is this what you are wanting?
<body>_x000D_
<div id="div1" style="height: 500px;">_x000D_
<div id="div2" style="height: inherit; overflow: auto; border:1px solid red;">_x000D_
<div id="div3" style="height:1500px;border:5px solid yellow;">hello</div>_x000D_
</div>_x000D_
</div>_x000D_
</body>
_x000D_
I had the same problem using
this.router.url
I get the current route with query params. A workaround I did was using this instead:
this.router.url.split('?')[0]
Not a really nice solution, but helpful.
Whether null char is allowed or not really depends on base64 codec in question. Given vagueness of Base64 standard (there is no authoritative exact specification), many implementations would just ignore it as white space. And then others can flag it as a problem. And buggiest ones wouldn't notice and would happily try decoding it... :-/
But it sounds c# implementation does not like it (which is one valid approach) so if removing it helps, that should be done.
One minor additional comment: UTF-8 is not a requirement, ISO-8859-x aka Latin-x, and 7-bit Ascii would work as well. This because Base64 was specifically designed to only use 7-bit subset which works with all 7-bit ascii compatible encodings.
Just use not
:
if not your_variable:
print("your_variable is empty")
and for your 0 as string
use:
if your_variable == "0":
print("your_variable is 0 (string)")
combine them:
if not your_variable or your_variable == "0":
print("your_variable is empty")
Python is about simplicity, so is this answer :)
Like reorder()
in Alex Brown's answer, we could also use forcats::fct_reorder()
. It will basically sort the factors specified in the 1st arg, according to the values in the 2nd arg after applying a specified function (default = median, which is what we use here as just have one value per factor level).
It is a shame that in the OP's question, the order required is also alphabetical as that is the default sort order when you create factors, so will hide what this function is actually doing. To make it more clear, I'll replace "Goalkeeper" with "Zoalkeeper".
library(tidyverse)
library(forcats)
theTable <- data.frame(
Name = c('James', 'Frank', 'Jean', 'Steve', 'John', 'Tim'),
Position = c('Zoalkeeper', 'Zoalkeeper', 'Defense',
'Defense', 'Defense', 'Striker'))
theTable %>%
count(Position) %>%
mutate(Position = fct_reorder(Position, n, .desc = TRUE)) %>%
ggplot(aes(x = Position, y = n)) + geom_bar(stat = 'identity')
.search-table-outter {border:2px solid red; overflow-x:scroll;}
.search-table{table-layout: fixed; margin:40px auto 0px auto; }
.search-table, td, th{border-collapse:collapse; border:1px solid #777;}
th{padding:20px 7px; font-size:15px; color:#444; background:#66C2E0;}
td{padding:5px 10px; height:35px;}
You should provide scroll in div.
To have a centered title in ABS (if you want to have this in the default ActionBar
, just remove the "support" in the method names), you could just do this:
In your Activity, in your onCreate()
method:
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.abs_layout);
abs_layout
:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<android.support.v7.widget.AppCompatTextView
android:id="@+id/tvTitle"
style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#FFFFFF" />
</LinearLayout>
Now you should have an Actionbar
with just a title. If you want to set a custom background, set it in the Layout above (but then don't forget to set android:layout_height="match_parent"
).
or with:
getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.yourimage));
Some clarifications (not really an answer)
In kubernetes, every pod gets assigned an IP address, and every container in the pod gets assigned that same IP address. Thus, as Alex Robinson stated in his answer, you can just use hostname -i
inside your container to get the pod IP address.
I tested with a pod running two dumb containers, and indeed hostname -i
was outputting the same IP address inside both containers. Furthermore, that IP was equivalent to the one obtained using kubectl describe pod
from outside, which validates the whole thing IMO.
However, PiersyP's answer seems more clean to me.
From kubernetes docs:
The applications in a pod all use the same network namespace (same IP and port space), and can thus “find” each other and communicate using localhost. Because of this, applications in a pod must coordinate their usage of ports. Each pod has an IP address in a flat shared networking space that has full communication with other physical computers and pods across the network.
Another piece from kubernetes docs:
Until now this document has talked about containers. In reality, Kubernetes applies IP addresses at the Pod scope - containers within a Pod share their network namespaces - including their IP address. This means that containers within a Pod can all reach each other’s ports on localhost.
yum install php-mbstring (as per http://php.net/manual/en/mbstring.installation.php)
I think you have to install the EPEL repository http://fedoraproject.org/wiki/EPEL
In [1]: df
Out[1]:
data
0 1
1 2
2 3
3 4
You want to apply a function that conditionally returns a value based on the selected dataframe column.
In [2]: df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false')
Out[2]:
0 true
1 true
2 false
3 false
Name: data
You can then assign that returned column to a new column in your dataframe:
In [3]: df['desired_output'] = df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false')
In [4]: df
Out[4]:
data desired_output
0 1 true
1 2 true
2 3 false
3 4 false
You can use
SELECT SYS_EXTRACT_UTC(TIMESTAMP '2000-03-28 11:30:00.00 -02:00') FROM DUAL;
You may also need to change your timezone
ALTER SESSION SET TIME_ZONE = 'Europe/Berlin';
Or read it
SELECT SESSIONTIMEZONE, CURRENT_TIMESTAMP FROM dual;
That works for me: Add Custom Font in React Native
download your fonts and place them in assets/fonts folder, add this line in package.json
"rnpm": {
"assets": ["assets/fonts/Sarpanch"]}
then open terminal and run this command: react-native link
Now your are good to go. For more detailed step. visit the link above mentioned
The ViewExpiredException
will be thrown whenever the javax.faces.STATE_SAVING_METHOD
is set to server
(default) and the enduser sends a HTTP POST request on a view via <h:form>
with <h:commandLink>
, <h:commandButton>
or <f:ajax>
, while the associated view state isn't available in the session anymore.
The view state is identified as value of a hidden input field javax.faces.ViewState
of the <h:form>
. With the state saving method set to server
, this contains only the view state ID which references a serialized view state in the session. So, when the session is expired for some reason (either timed out in server or client side, or the session cookie is not maintained anymore for some reason in browser, or by calling HttpSession#invalidate()
in server, or due a server specific bug with session cookies as known in WildFly), then the serialized view state is not available anymore in the session and the enduser will get this exception. To understand the working of the session, see also How do servlets work? Instantiation, sessions, shared variables and multithreading.
There is also a limit on the amount of views JSF will store in the session. When the limit is hit, then the least recently used view will be expired. See also com.sun.faces.numberOfViewsInSession vs com.sun.faces.numberOfLogicalViews.
With the state saving method set to client
, the javax.faces.ViewState
hidden input field contains instead the whole serialized view state, so the enduser won't get a ViewExpiredException
when the session expires. It can however still happen on a cluster environment ("ERROR: MAC did not verify" is symptomatic) and/or when there's a implementation-specific timeout on the client side state configured and/or when server re-generates the AES key during restart, see also Getting ViewExpiredException in clustered environment while state saving method is set to client and user session is valid how to solve it.
Regardless of the solution, make sure you do not use enableRestoreView11Compatibility
. it does not at all restore the original view state. It basically recreates the view and all associated view scoped beans from scratch and hereby thus losing all of original data (state). As the application will behave in a confusing way ("Hey, where are my input values..??"), this is very bad for user experience. Better use stateless views or <o:enableRestorableView>
instead so you can manage it on a specific view only instead of on all views.
As to the why JSF needs to save view state, head to this answer: Why JSF saves the state of UI components on server?
In order to avoid ViewExpiredException
when e.g. navigating back after logout when the state saving is set to server
, only redirecting the POST request after logout is not sufficient. You also need to instruct the browser to not cache the dynamic JSF pages, otherwise the browser may show them from the cache instead of requesting a fresh one from the server when you send a GET request on it (e.g. by back button).
The javax.faces.ViewState
hidden field of the cached page may contain a view state ID value which is not valid anymore in the current session. If you're (ab)using POST (command links/buttons) instead of GET (regular links/buttons) for page-to-page navigation, and click such a command link/button on the cached page, then this will in turn fail with a ViewExpiredException
.
To fire a redirect after logout in JSF 2.0, either add <redirect />
to the <navigation-case>
in question (if any), or add ?faces-redirect=true
to the outcome
value.
<h:commandButton value="Logout" action="logout?faces-redirect=true" />
or
public String logout() {
// ...
return "index?faces-redirect=true";
}
To instruct the browser to not cache the dynamic JSF pages, create a Filter
which is mapped on the servlet name of the FacesServlet
and adds the needed response headers to disable the browser cache. E.g.
@WebFilter(servletNames={"Faces Servlet"}) // Must match <servlet-name> of your FacesServlet.
public class NoCacheFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
if (!req.getRequestURI().startsWith(req.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER)) { // Skip JSF resources (CSS/JS/Images/etc)
res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
res.setHeader("Pragma", "no-cache"); // HTTP 1.0.
res.setDateHeader("Expires", 0); // Proxies.
}
chain.doFilter(request, response);
}
// ...
}
In order to avoid ViewExpiredException
when refreshing the current page when the state saving is set to server
, you not only need to make sure you are performing page-to-page navigation exclusively by GET (regular links/buttons), but you also need to make sure that you are exclusively using ajax to submit the forms. If you're submitting the form synchronously (non-ajax) anyway, then you'd best either make the view stateless (see later section), or to send a redirect after POST (see previous section).
Having a ViewExpiredException
on page refresh is in default configuration a very rare case. It can only happen when the limit on the amount of views JSF will store in the session is hit. So, it will only happen when you've manually set that limit way too low, or that you're continuously creating new views in the "background" (e.g. by a badly implemented ajax poll in the same page or by a badly implemented 404 error page on broken images of the same page). See also com.sun.faces.numberOfViewsInSession vs com.sun.faces.numberOfLogicalViews for detail on that limit. Another cause is having duplicate JSF libraries in runtime classpath conflicting each other. The correct procedure to install JSF is outlined in our JSF wiki page.
When you want to handle an unavoidable ViewExpiredException
after a POST action on an arbitrary page which was already opened in some browser tab/window while you're logged out in another tab/window, then you'd like to specify an error-page
for that in web.xml
which goes to a "Your session is timed out" page. E.g.
<error-page>
<exception-type>javax.faces.application.ViewExpiredException</exception-type>
<location>/WEB-INF/errorpages/expired.xhtml</location>
</error-page>
Use if necessary a meta refresh header in the error page in case you intend to actually redirect further to home or login page.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Session expired</title>
<meta http-equiv="refresh" content="0;url=#{request.contextPath}/login.xhtml" />
</head>
<body>
<h1>Session expired</h1>
<h3>You will be redirected to login page</h3>
<p><a href="#{request.contextPath}/login.xhtml">Click here if redirect didn't work or when you're impatient</a>.</p>
</body>
</html>
(the 0
in content
represents the amount of seconds before redirect, 0
thus means "redirect immediately", you can use e.g. 3
to let the browser wait 3 seconds with the redirect)
Note that handling exceptions during ajax requests requires a special ExceptionHandler
. See also Session timeout and ViewExpiredException handling on JSF/PrimeFaces ajax request. You can find a live example at OmniFaces FullAjaxExceptionHandler
showcase page (this also covers non-ajax requests).
Also note that your "general" error page should be mapped on <error-code>
of 500
instead of an <exception-type>
of e.g. java.lang.Exception
or java.lang.Throwable
, otherwise all exceptions wrapped in ServletException
such as ViewExpiredException
would still end up in the general error page. See also ViewExpiredException shown in java.lang.Throwable error-page in web.xml.
<error-page>
<error-code>500</error-code>
<location>/WEB-INF/errorpages/general.xhtml</location>
</error-page>
A completely different alternative is to run JSF views in stateless mode. This way nothing of JSF state will be saved and the views will never expire, but just be rebuilt from scratch on every request. You can turn on stateless views by setting the transient
attribute of <f:view>
to true
:
<f:view transient="true">
</f:view>
This way the javax.faces.ViewState
hidden field will get a fixed value of "stateless"
in Mojarra (have not checked MyFaces at this point). Note that this feature was introduced in Mojarra 2.1.19 and 2.2.0 and is not available in older versions.
The consequence is that you cannot use view scoped beans anymore. They will now behave like request scoped beans. One of the disadvantages is that you have to track the state yourself by fiddling with hidden inputs and/or loose request parameters. Mainly those forms with input fields with rendered
, readonly
or disabled
attributes which are controlled by ajax events will be affected.
Note that the <f:view>
does not necessarily need to be unique throughout the view and/or reside in the master template only. It's also completely legit to redeclare and nest it in a template client. It basically "extends" the parent <f:view>
then. E.g. in master template:
<f:view contentType="text/html">
<ui:insert name="content" />
</f:view>
and in template client:
<ui:define name="content">
<f:view transient="true">
<h:form>...</h:form>
</f:view>
</f:view>
You can even wrap the <f:view>
in a <c:if>
to make it conditional. Note that it would apply on the entire view, not only on the nested contents, such as the <h:form>
in above example.
Unrelated to the concrete problem, using HTTP POST for pure page-to-page navigation isn't very user/SEO friendly. In JSF 2.0 you should really prefer <h:link>
or <h:button>
over the <h:commandXxx>
ones for plain vanilla page-to-page navigation.
So instead of e.g.
<h:form id="menu">
<h:commandLink value="Foo" action="foo?faces-redirect=true" />
<h:commandLink value="Bar" action="bar?faces-redirect=true" />
<h:commandLink value="Baz" action="baz?faces-redirect=true" />
</h:form>
better do
<h:link value="Foo" outcome="foo" />
<h:link value="Bar" outcome="bar" />
<h:link value="Baz" outcome="baz" />
To initiate a google-chrome-headless browsing context using Selenium driven ChromeDriver now you can just set the --headless
property to true
through an instance of Options()
class as follows:
Effective code block:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.headless = True
driver = webdriver.Chrome(options=options, executable_path=r'C:\path\to\chromedriver.exe')
driver.get("http://google.com/")
print ("Headless Chrome Initialized")
driver.quit()
Invoking google-chrome in headless mode programmatically have become much easier with the availability of the method set_headless(headless=True)
as follows :
Documentation :
set_headless(headless=True)
Sets the headless argument
Args:
headless: boolean value indicating to set the headless option
Sample Code :
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.set_headless(headless=True)
driver = webdriver.Chrome(options=options, executable_path=r'C:\path\to\chromedriver.exe')
driver.get("http://google.com/")
print ("Headless Chrome Initialized")
driver.quit()
Note :
--disable-gpu
argument is implemented internally.
While working with Selenium Client 3.11.x, ChromeDriver v2.38 and Google Chrome v65.0.3325.181 in Headless mode you have to consider the following points :
You need to add the argument --headless
to invoke Chrome in headless mode.
For Windows OS systems you need to add the argument --disable-gpu
As per Headless: make --disable-gpu flag unnecessary --disable-gpu
flag is not required on Linux Systems and MacOS.
As per SwiftShader fails an assert on Windows in headless mode --disable-gpu
flag will become unnecessary on Windows Systems too.
Argument start-maximized
is required for a maximized Viewport.
Here is the link to details about Viewport.
You may require to add the argument --no-sandbox
to bypass the OS security model.
Effective windows code block :
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--headless") # Runs Chrome in headless mode.
options.add_argument('--no-sandbox') # Bypass OS security model
options.add_argument('--disable-gpu') # applicable to windows os only
options.add_argument('start-maximized') #
options.add_argument('disable-infobars')
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\path\to\chromedriver.exe')
driver.get("http://google.com/")
print ("Headless Chrome Initialized on Windows OS")
Effective linux code block :
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--headless") # Runs Chrome in headless mode.
options.add_argument('--no-sandbox') # # Bypass OS security model
options.add_argument('start-maximized')
options.add_argument('disable-infobars')
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=options, executable_path='/path/to/chromedriver')
driver.get("http://google.com/")
print ("Headless Chrome Initialized on Linux OS")
How to make firefox headless programmatically in Selenium with python?
Here is the link to the Sandbox story.
if you want to execute ENABLE TRIGGER Directly From Source :
we can't write like this:
Conn.Execute "ENABLE TRIGGER trigger_name ON table_name"
instead, we can write :
Conn.Execute "ALTER TABLE table_name DISABLE TRIGGER trigger_name"
The next()
method (offcial doc here) simply move the pointer of the result rows set to the next row (if it can). Anyway you can read this from the offcial doc as well:
Moves the cursor down one row from its current position.
This method return true if there's another row or false otherwise.
It does work in Firefox (including 2.0.0.20
). See http://jsbin.com/akili (add /edit
to the url to edit):
<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>
The first click changes the id
to "two"
, the second click errors because the element with id="one"
now can't be found!
Perhaps you have another element already with id="two"
(FYI you can't have more than one element with the same id
).
Another way to solve this problem (it's not so good practice but looks beauty):
static class Helper
{
public static object AsSingleParam(this object[] arg)
{
return (object)arg;
}
}
Usage:
f(new object[] { 1, 2, 3 }.AsSingleParam());
I just encountered the same issue on my windows 7 machine. I followed the directions in MongoDBs Docs for the install, but it wouldn't let me execute "net start MongoDB" unless I was in "C:\". I didn't want to go back and reinstall MongoDB to follow the instructions included in the Webiyo link referenced above though. If you already installed MongoDB according to their docs and want to be able to execute "net start MongoDB" from where ever your project directory is:
Go to HKEY_LOCAL_MACHINE > SYSTEM > CurrentControlSet > services > MongoDB
Double click ImagePath under the Name column
Paste in the following ImagePath ( edit the folder directory and names to match your needs ):
C:\mongodb\bin\mongod.exe --service --rest --master --logpath=C:\mongodb\log\mongolog.txt --dbpath=C:\mongodb\data\db --config C:\mongodb\mongod.cfg
Note that if you direct copy this ImagePath value and your "data" folder is in the mongodb directory instead of C:\ add the following line to your "mongod.cfg" file: dbpath=C:\mongodb\data\db
After I did this, when I run "net stop MongoDB" I get the message "System error 109 has occurred. The pipe has been ended." You may see it as well. This message has been discussed thoroughly at jira.mongodb.org.
To save you the time of reading the whole back and forth discussion, Tad Marshalls post sums up this issue:
"... it was working fine in 2.1.0; later changes broke it again. But yes, you get this error message in the current code.
The explanation is that mongod.exe is exiting from a callback thread created by the Windows Service Control Manager when it calls us due to "net stop mongodb" and this breaks the RPC pipe it used to create the callback thread. We need to reorganize our exit logic to avoid doing this.
The error message is the only real effect of this issue; we exit on command, cleanly, and inform the Windows Service Control Manager that we are stopped, but then the "net" command displays an error message because we didn't return from the RPC call the way it expected us to."
Focus doesn't work on divs by default. But, according to this, you can make it work:
The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (
<input>
,<select>
, etc.) and links (<a href>
). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.
Adding to Dmitri Chebotarev Answer,
If you want to alter multiple columns at a time , you can do it like below
DB::statement('
ALTER TABLE `events`
MODIFY `event_date` DATE NOT NULL,
MODIFY `event_start_time` TIME NOT NULL,
MODIFY `event_end_time` TIME NOT NULL;
');
It seems to me there is value in considering some rewrites to your SQL code before attempting to translate it.
Personally, I'd write such a query as a union (although I'd avoid nulls entirely!):
SELECT f.value
FROM period as p JOIN facts AS f ON p.id = f.periodid
WHERE p.companyid = 100
AND f.otherid = 17
UNION
SELECT NULL AS value
FROM period as p
WHERE p.companyid = 100
AND NOT EXISTS (
SELECT *
FROM facts AS f
WHERE p.id = f.periodid
AND f.otherid = 17
);
So I guess I agree with the spirit of @MAbraham1's answer (though their code seems to be unrelated to the question).
However, it seems the query is expressly designed to produce a single column result comprising duplicate rows -- indeed duplicate nulls! It's hard not to come to the conclusion that this approach is flawed.
You can try the below function to get value from JSON string,
public static String GetJSONValue(String JSONString, String Field)
{
return JSONString.substring(JSONString.indexOf(Field), JSONString.indexOf("\n", JSONString.indexOf(Field))).replace(Field+"\": \"", "").replace("\"", "").replace(",","");
}
Its actually enough to add -m to startup parameters on Sql Server Configuration Manager, restart service, go to ssms an add checkbox sysadmin on your account, then remove -m restart again and use as usual.
Database Engine Service Startup Options
-m Starts an instance of SQL Server in single-user mode.
If you're using cyrus/sasl/imap on your mailserver, then one fast and efficient way to purge everything in a mailbox that is older then number of days specified is to use cyrus/imap ipurge command. For example, here is an example removing everything (be carefull!!), older then 30 days from user vleo. Notice, that you must be logged in as cyrus (imap mail administrator) user:
[cyrus@mailserver ~]$ /usr/lib/cyrus-imapd/ipurge -f -d 30 user.vleo
Working on user.vleo...
total messages 4
total bytes 113183
Deleted messages 0
Deleted bytes 0
Remaining messages 4
Remaining bytes 113183
Try this
MsgBox("Are you sure want to Exit", MsgBoxStyle.YesNo, "")
If True Then
End
End If
class Something {
constructor(){
var _property = "test";
Object.defineProperty(this, "property", {
get: function(){ return _property}
});
}
}
var instance = new Something();
console.log(instance.property); //=> "test"
instance.property = "can read from outside, but can't write";
console.log(instance.property); //=> "test"
In my IBM AIX Server (OS version: AIX 5.2), use:
find ./ -type f -print -exec grep -n -i "stringYouWannaFind" {} \;
this will print out path/file name and relative line number in the file like:
./inc/xxxx_x.h
2865: /** Description : stringYouWannaFind */
anyway,it works for me : )
var campaignTitle= CKEDITOR.instances['CampaignTitle'].getData();